Skip to main content

visloc_tracking/
trajectory.rs

1//! Trajectory representation, TUM/KITTI parsing, Umeyama alignment, and
2//! ATE / RPE / KITTI-odometry evaluation.
3
4use super::*;
5
6#[derive(Debug, Clone, PartialEq)]
7pub struct TrajectorySample {
8    pub frame_id: FrameId,
9    pub pose: Pose,
10    pub state: TrackingState,
11    pub event: TrackingEvent,
12    pub inlier_count: usize,
13    pub inlier_ratio: f64,
14    pub reprojection_error: Option<f64>,
15}
16
17impl TrajectorySample {
18    pub fn from_tracking_result(result: &TrackingResult) -> Option<Self> {
19        if !result.localization.success {
20            return None;
21        }
22
23        Some(Self {
24            frame_id: result.frame_id,
25            pose: result.localization.pose.clone()?,
26            state: result.state,
27            event: result.event,
28            inlier_count: result.localization.inlier_count,
29            inlier_ratio: result.localization.inlier_ratio,
30            reprojection_error: result.localization.reprojection_error,
31        })
32    }
33
34    pub fn camera_center_world(&self) -> Point3<f64> {
35        self.pose.camera_center_world()
36    }
37
38    pub fn to_csv_record(&self) -> String {
39        let center = self.camera_center_world();
40        let q = self.pose.world_to_camera.rotation.quaternion();
41        let t = self.pose.world_to_camera.translation;
42        format!(
43            "{},{},{},{},{},{},{},{},{},{},{},{:?},{:?},{},{},{}",
44            self.frame_id,
45            center.x,
46            center.y,
47            center.z,
48            q.w,
49            q.i,
50            q.j,
51            q.k,
52            t.x,
53            t.y,
54            t.z,
55            self.state,
56            self.event,
57            self.inlier_count,
58            self.inlier_ratio,
59            optional_f64_csv(self.reprojection_error)
60        )
61    }
62
63    pub fn to_kitti_pose_record(&self) -> String {
64        let camera_to_world = self.pose.camera_to_world().matrix();
65        let mut values = Vec::with_capacity(12);
66        for row in 0..3 {
67            for column in 0..4 {
68                values.push(camera_to_world[(row, column)].to_string());
69            }
70        }
71        values.join(" ")
72    }
73
74    pub fn to_tum_pose_record(&self) -> String {
75        let camera_to_world = self.pose.camera_to_world();
76        let q = camera_to_world.rotation.quaternion();
77        let t = camera_to_world.translation;
78        format!(
79            "{} {} {} {} {} {} {} {}",
80            self.frame_id,
81            export_f64(t.x),
82            export_f64(t.y),
83            export_f64(t.z),
84            export_f64(q.i),
85            export_f64(q.j),
86            export_f64(q.k),
87            export_f64(q.w)
88        )
89    }
90}
91
92#[derive(Debug, Clone, Default, PartialEq)]
93pub struct PoseTrajectory {
94    pub(crate) samples: Vec<TrajectorySample>,
95}
96
97#[derive(Debug, Clone, PartialEq, Eq)]
98pub struct TumTrajectoryParseError {
99    pub line_number: usize,
100    pub line: String,
101    pub message: String,
102}
103
104impl TumTrajectoryParseError {
105    pub(crate) fn new(line_number: usize, line: &str, message: impl Into<String>) -> Self {
106        Self {
107            line_number,
108            line: line.to_string(),
109            message: message.into(),
110        }
111    }
112}
113
114impl fmt::Display for TumTrajectoryParseError {
115    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
116        write!(
117            formatter,
118            "invalid TUM trajectory line {}: {} ({})",
119            self.line_number, self.line, self.message
120        )
121    }
122}
123
124impl std::error::Error for TumTrajectoryParseError {}
125
126#[derive(Debug, Clone, PartialEq, Eq)]
127pub struct KittiTrajectoryParseError {
128    pub line_number: usize,
129    pub line: String,
130    pub message: String,
131}
132
133impl KittiTrajectoryParseError {
134    pub(crate) fn new(line_number: usize, line: &str, message: impl Into<String>) -> Self {
135        Self {
136            line_number,
137            line: line.to_string(),
138            message: message.into(),
139        }
140    }
141}
142
143impl fmt::Display for KittiTrajectoryParseError {
144    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
145        write!(
146            formatter,
147            "invalid KITTI trajectory line {}: {} ({})",
148            self.line_number, self.line, self.message
149        )
150    }
151}
152
153impl std::error::Error for KittiTrajectoryParseError {}
154
155#[derive(Debug)]
156pub enum TrajectoryFileError {
157    Io(std::io::Error),
158    TumParse(TumTrajectoryParseError),
159    KittiParse(KittiTrajectoryParseError),
160}
161
162impl fmt::Display for TrajectoryFileError {
163    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
164        match self {
165            Self::Io(error) => write!(formatter, "trajectory file I/O error: {error}"),
166            Self::TumParse(error) => write!(formatter, "{error}"),
167            Self::KittiParse(error) => write!(formatter, "{error}"),
168        }
169    }
170}
171
172impl std::error::Error for TrajectoryFileError {
173    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
174        match self {
175            Self::Io(error) => Some(error),
176            Self::TumParse(error) => Some(error),
177            Self::KittiParse(error) => Some(error),
178        }
179    }
180}
181
182#[derive(Debug, Clone, PartialEq)]
183pub struct TrajectorySummary {
184    pub pose_count: usize,
185    pub first_frame_id: Option<FrameId>,
186    pub last_frame_id: Option<FrameId>,
187    pub total_path_length: f64,
188    pub mean_inlier_count: Option<f64>,
189    pub mean_inlier_ratio: Option<f64>,
190    pub mean_reprojection_error: Option<f64>,
191    pub min_camera_center_world: Option<[f64; 3]>,
192    pub max_camera_center_world: Option<[f64; 3]>,
193}
194
195#[derive(Debug, Clone, Copy, PartialEq)]
196pub struct TrajectoryTranslationError {
197    pub frame_id: FrameId,
198    pub translation_error: f64,
199}
200
201impl TrajectoryTranslationError {
202    pub fn to_csv_record(&self) -> String {
203        format!("{},{}", self.frame_id, self.translation_error)
204    }
205}
206
207#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
208pub enum TrajectoryAlignment {
209    #[default]
210    None,
211    FirstMatchedTranslation,
212    /// Rigid SE(3) alignment via Umeyama (1991): finds the rotation +
213    /// translation that minimises the sum of squared distances between
214    /// frame-id-matched camera centres. Scale is fixed at 1.
215    Umeyama,
216    /// Similarity SO(3) + scale + translation alignment via Umeyama
217    /// (1991): the standard ATE protocol used to compare monocular
218    /// / scale-ambiguous SLAM systems against ground truth.
219    UmeyamaWithScale,
220}
221
222#[derive(Debug, Clone, PartialEq)]
223pub struct TrajectorySimilarityTransform {
224    pub scale: f64,
225    pub rotation: Rotation3<f64>,
226    pub translation: Vector3<f64>,
227}
228
229impl TrajectorySimilarityTransform {
230    pub fn identity() -> Self {
231        Self {
232            scale: 1.0,
233            rotation: Rotation3::identity(),
234            translation: Vector3::zeros(),
235        }
236    }
237
238    pub fn pure_translation(translation: Vector3<f64>) -> Self {
239        Self {
240            scale: 1.0,
241            rotation: Rotation3::identity(),
242            translation,
243        }
244    }
245
246    pub fn apply(&self, point: &Point3<f64>) -> Point3<f64> {
247        let v = self.rotation * (point.coords * self.scale) + self.translation;
248        Point3::from(v)
249    }
250}
251
252/// Closed-form similarity registration (Umeyama 1991).
253///
254/// Returns the transform `T = (scale, R, t)` that minimises
255/// `sum_i || T(source_i) - target_i ||^2`. When `with_scale` is false
256/// the scale is fixed at 1 (rigid SE(3) Procrustes). Returns `None`
257/// when there are fewer than two correspondences or the source point
258/// cloud has zero spread.
259pub fn umeyama_similarity_transform(
260    source: &[Point3<f64>],
261    target: &[Point3<f64>],
262    with_scale: bool,
263) -> Option<TrajectorySimilarityTransform> {
264    if source.len() != target.len() || source.len() < 2 {
265        return None;
266    }
267    let n = source.len() as f64;
268    let source_centroid = source
269        .iter()
270        .fold(Vector3::<f64>::zeros(), |acc, p| acc + p.coords)
271        / n;
272    let target_centroid = target
273        .iter()
274        .fold(Vector3::<f64>::zeros(), |acc, p| acc + p.coords)
275        / n;
276
277    let mut sigma = Matrix3::<f64>::zeros();
278    let mut source_variance = 0.0f64;
279    for (s, t) in source.iter().zip(target.iter()) {
280        let xs = s.coords - source_centroid;
281        let xt = t.coords - target_centroid;
282        sigma += xt * xs.transpose();
283        source_variance += xs.norm_squared();
284    }
285    sigma /= n;
286    source_variance /= n;
287    if source_variance <= f64::EPSILON {
288        return None;
289    }
290    if !sigma.iter().all(|value| value.is_finite()) {
291        return None;
292    }
293
294    let svd = sigma.try_svd(true, true, f64::EPSILON * 5.0, 10_000)?;
295    let u = svd.u?;
296    let v_t = svd.v_t?;
297    let singular_values = svd.singular_values;
298
299    let det_uv = u.determinant() * v_t.determinant();
300    let mut s_diag = Vector3::new(1.0, 1.0, 1.0);
301    if det_uv < 0.0 {
302        s_diag.z = -1.0;
303    }
304    let s_matrix = Matrix3::from_diagonal(&s_diag);
305    let rotation_matrix = u * s_matrix * v_t;
306    let rotation = Rotation3::from_matrix_unchecked(rotation_matrix);
307
308    let scale = if with_scale {
309        let trace_ds = singular_values.x * s_diag.x
310            + singular_values.y * s_diag.y
311            + singular_values.z * s_diag.z;
312        trace_ds / source_variance
313    } else {
314        1.0
315    };
316
317    let translation = target_centroid - rotation * (source_centroid * scale);
318
319    Some(TrajectorySimilarityTransform {
320        scale,
321        rotation,
322        translation,
323    })
324}
325
326#[derive(Debug, Clone, PartialEq)]
327pub struct TrajectoryErrorSummary {
328    pub estimated_pose_count: usize,
329    pub reference_pose_count: usize,
330    pub matched_pose_count: usize,
331    pub missing_reference_count: usize,
332    pub missing_estimate_count: usize,
333    pub mean_translation_error: Option<f64>,
334    pub rmse_translation_error: Option<f64>,
335    pub max_translation_error: Option<f64>,
336}
337
338#[derive(Debug, Clone, Default, PartialEq)]
339pub struct TrajectoryEvaluationConfig {
340    pub max_mean_translation_error: Option<f64>,
341    pub max_rmse_translation_error: Option<f64>,
342    pub max_max_translation_error: Option<f64>,
343    pub min_matched_pose_count: Option<usize>,
344    pub min_match_ratio: Option<f64>,
345}
346
347#[derive(Debug, Clone, PartialEq)]
348pub struct KittiOdometryBenchmarkConfig {
349    /// Segment lengths in meters used by the KITTI odometry leaderboard.
350    /// The current public KITTI leaderboard reports `[100, 200, ..., 800]`.
351    /// Older devkit/debug runs often use short windows such as
352    /// `[5, 10, 50, 100, 150, ..., 400]`; pass those explicitly when a
353    /// sequence is too short for the official windows.
354    pub segment_lengths_m: Vec<f64>,
355    /// Frame stride for start indices. KITTI's devkit uses every frame.
356    pub start_frame_step: usize,
357}
358
359impl Default for KittiOdometryBenchmarkConfig {
360    fn default() -> Self {
361        Self {
362            segment_lengths_m: vec![100.0, 200.0, 300.0, 400.0, 500.0, 600.0, 700.0, 800.0],
363            start_frame_step: 1,
364        }
365    }
366}
367
368#[derive(Debug, Clone, PartialEq)]
369pub struct KittiOdometrySegmentError {
370    pub first_frame_id: FrameId,
371    pub last_frame_id: FrameId,
372    pub length_m: f64,
373    /// KITTI translational error for this segment, as a fraction of segment
374    /// length. Multiply by 100 for percent.
375    pub translational_error_ratio: f64,
376    /// KITTI rotational error for this segment in degrees per meter.
377    pub rotational_error_deg_per_m: f64,
378}
379
380impl KittiOdometrySegmentError {
381    pub fn translational_error_percent(&self) -> f64 {
382        self.translational_error_ratio * 100.0
383    }
384
385    pub fn to_csv_record(&self) -> String {
386        format!(
387            "{},{},{},{},{},{}",
388            self.first_frame_id,
389            self.last_frame_id,
390            self.length_m,
391            self.translational_error_ratio,
392            self.translational_error_percent(),
393            self.rotational_error_deg_per_m
394        )
395    }
396}
397
398#[derive(Debug, Clone, PartialEq)]
399pub struct KittiOdometryBenchmarkSummary {
400    pub estimated_pose_count: usize,
401    pub reference_pose_count: usize,
402    pub matched_pose_count: usize,
403    pub segment_count: usize,
404    pub mean_translational_error_percent: Option<f64>,
405    pub mean_rotational_error_deg_per_m: Option<f64>,
406    pub segment_errors: Vec<KittiOdometrySegmentError>,
407}
408
409impl KittiOdometryBenchmarkSummary {
410    pub fn max_translational_error_percent(&self) -> Option<f64> {
411        self.segment_errors
412            .iter()
413            .map(KittiOdometrySegmentError::translational_error_percent)
414            .reduce(f64::max)
415    }
416
417    pub fn max_rotational_error_deg_per_m(&self) -> Option<f64> {
418        self.segment_errors
419            .iter()
420            .map(|error| error.rotational_error_deg_per_m)
421            .reduce(f64::max)
422    }
423
424    pub fn segment_errors_csv(&self) -> String {
425        let mut output = String::from(
426            "first_frame_id,last_frame_id,length_m,translational_error_ratio,translational_error_percent,rotational_error_deg_per_m\n",
427        );
428        for error in &self.segment_errors {
429            output.push_str(&error.to_csv_record());
430            output.push('\n');
431        }
432        output
433    }
434
435    pub fn to_json(&self) -> String {
436        let mut output = String::new();
437        writeln!(&mut output, "{{").unwrap();
438        writeln!(
439            &mut output,
440            "  \"estimated_pose_count\": {},",
441            self.estimated_pose_count
442        )
443        .unwrap();
444        writeln!(
445            &mut output,
446            "  \"reference_pose_count\": {},",
447            self.reference_pose_count
448        )
449        .unwrap();
450        writeln!(
451            &mut output,
452            "  \"matched_pose_count\": {},",
453            self.matched_pose_count
454        )
455        .unwrap();
456        writeln!(&mut output, "  \"segment_count\": {},", self.segment_count).unwrap();
457        writeln!(
458            &mut output,
459            "  \"mean_translational_error_percent\": {},",
460            optional_f64_json(self.mean_translational_error_percent)
461        )
462        .unwrap();
463        writeln!(
464            &mut output,
465            "  \"mean_rotational_error_deg_per_m\": {},",
466            optional_f64_json(self.mean_rotational_error_deg_per_m)
467        )
468        .unwrap();
469        writeln!(
470            &mut output,
471            "  \"max_translational_error_percent\": {},",
472            optional_f64_json(self.max_translational_error_percent())
473        )
474        .unwrap();
475        writeln!(
476            &mut output,
477            "  \"max_rotational_error_deg_per_m\": {}",
478            optional_f64_json(self.max_rotational_error_deg_per_m())
479        )
480        .unwrap();
481        output.push_str("}\n");
482        output
483    }
484
485    pub fn write_segment_errors_csv(&self, path: impl AsRef<Path>) -> std::io::Result<()> {
486        std::fs::write(path, self.segment_errors_csv())
487    }
488
489    pub fn write_json(&self, path: impl AsRef<Path>) -> std::io::Result<()> {
490        std::fs::write(path, self.to_json())
491    }
492}
493
494/// Configuration for the TUM-style relative pose error (RPE).
495///
496/// RPE (Sturm et al., 2012) measures *local* drift: for each pair of poses a
497/// fixed number of steps apart it compares the relative motion of the estimate
498/// against the reference. Unlike the absolute trajectory error (ATE), RPE needs
499/// no global alignment — a relative motion is invariant to any rigid transform
500/// applied to the whole trajectory — which makes it the canonical companion
501/// metric to ATE for SLAM back-ends and visual odometry front-ends.
502#[derive(Debug, Clone, PartialEq, Eq)]
503pub struct RelativePoseErrorConfig {
504    /// Step gap Δ between the two poses of each relative-motion pair, counted in
505    /// matched (frame-id-intersected) trajectory steps. `delta = 1` reports the
506    /// per-step drift; larger values probe drift accumulated over longer
507    /// windows.
508    pub delta: usize,
509    /// Stride between successive start indices. `1` evaluates every pose.
510    pub start_step: usize,
511}
512
513impl Default for RelativePoseErrorConfig {
514    fn default() -> Self {
515        Self {
516            delta: 1,
517            start_step: 1,
518        }
519    }
520}
521
522/// One relative-pose-error sample over a single Δ-spaced pair.
523#[derive(Debug, Clone, PartialEq)]
524pub struct RelativePoseError {
525    pub first_frame_id: FrameId,
526    pub last_frame_id: FrameId,
527    /// Translational drift of the relative motion, in meters.
528    pub translation_error: f64,
529    /// Rotational drift of the relative motion, in degrees.
530    pub rotation_error_deg: f64,
531}
532
533impl RelativePoseError {
534    pub fn to_csv_record(&self) -> String {
535        format!(
536            "{},{},{},{}",
537            self.first_frame_id,
538            self.last_frame_id,
539            self.translation_error,
540            self.rotation_error_deg
541        )
542    }
543}
544
545/// Distribution statistics for one RPE channel (translation or rotation).
546#[derive(Debug, Clone, Copy, PartialEq)]
547pub struct RelativePoseErrorStatistics {
548    /// Root-mean-square error — the headline RPE figure reported in the TUM
549    /// protocol.
550    pub rmse: f64,
551    pub mean: f64,
552    pub median: f64,
553    /// Population standard deviation (`rmse² = mean² + std²`).
554    pub std: f64,
555    pub min: f64,
556    pub max: f64,
557}
558
559impl RelativePoseErrorStatistics {
560    /// Statistics of a non-empty error sample. Returns `None` when `values` is
561    /// empty.
562    fn from_values(values: &[f64]) -> Option<Self> {
563        if values.is_empty() {
564            return None;
565        }
566        let n = values.len() as f64;
567        let mean = values.iter().sum::<f64>() / n;
568        let sum_sq = values.iter().map(|v| v * v).sum::<f64>();
569        let rmse = (sum_sq / n).sqrt();
570        let std = (sum_sq / n - mean * mean).max(0.0).sqrt();
571        let mut sorted = values.to_vec();
572        sorted.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
573        let middle = sorted.len() / 2;
574        let median = if sorted.len() % 2 == 1 {
575            sorted[middle]
576        } else {
577            0.5 * (sorted[middle - 1] + sorted[middle])
578        };
579        Some(Self {
580            rmse,
581            mean,
582            median,
583            std,
584            min: sorted[0],
585            max: sorted[sorted.len() - 1],
586        })
587    }
588}
589
590/// Aggregated TUM-style relative pose error over all Δ-spaced pairs.
591#[derive(Debug, Clone, PartialEq)]
592pub struct RelativePoseErrorSummary {
593    pub estimated_pose_count: usize,
594    pub reference_pose_count: usize,
595    pub matched_pose_count: usize,
596    /// The step gap Δ used (clamped to at least 1).
597    pub delta: usize,
598    pub pair_count: usize,
599    /// Translational error statistics in meters (`None` when no pair exists).
600    pub translation: Option<RelativePoseErrorStatistics>,
601    /// Rotational error statistics in degrees (`None` when no pair exists).
602    pub rotation_deg: Option<RelativePoseErrorStatistics>,
603    pub errors: Vec<RelativePoseError>,
604}
605
606impl RelativePoseErrorSummary {
607    pub fn errors_csv(&self) -> String {
608        let mut output =
609            String::from("first_frame_id,last_frame_id,translation_error,rotation_error_deg\n");
610        for error in &self.errors {
611            output.push_str(&error.to_csv_record());
612            output.push('\n');
613        }
614        output
615    }
616
617    pub fn write_errors_csv(&self, path: impl AsRef<Path>) -> std::io::Result<()> {
618        std::fs::write(path, self.errors_csv())
619    }
620
621    pub fn to_json(&self) -> String {
622        let mut output = String::new();
623        writeln!(&mut output, "{{").unwrap();
624        writeln!(
625            &mut output,
626            "  \"estimated_pose_count\": {},",
627            self.estimated_pose_count
628        )
629        .unwrap();
630        writeln!(
631            &mut output,
632            "  \"reference_pose_count\": {},",
633            self.reference_pose_count
634        )
635        .unwrap();
636        writeln!(
637            &mut output,
638            "  \"matched_pose_count\": {},",
639            self.matched_pose_count
640        )
641        .unwrap();
642        writeln!(&mut output, "  \"delta\": {},", self.delta).unwrap();
643        writeln!(&mut output, "  \"pair_count\": {},", self.pair_count).unwrap();
644        writeln!(
645            &mut output,
646            "  \"translation_m\": {},",
647            relative_pose_error_statistics_json(self.translation)
648        )
649        .unwrap();
650        writeln!(
651            &mut output,
652            "  \"rotation_deg\": {}",
653            relative_pose_error_statistics_json(self.rotation_deg)
654        )
655        .unwrap();
656        output.push_str("}\n");
657        output
658    }
659
660    pub fn write_json(&self, path: impl AsRef<Path>) -> std::io::Result<()> {
661        std::fs::write(path, self.to_json())
662    }
663}
664
665#[derive(Debug, Clone, PartialEq)]
666pub struct TrajectoryEvaluationResult {
667    pub passed: bool,
668    pub summary: TrajectoryErrorSummary,
669    pub config: TrajectoryEvaluationConfig,
670    pub match_ratio: Option<f64>,
671    pub failures: Vec<TrajectoryEvaluationFailure>,
672}
673
674#[derive(Debug, Clone, PartialEq)]
675pub enum TrajectoryEvaluationFailure {
676    MeanTranslationErrorTooHigh { actual: f64, maximum: f64 },
677    RmseTranslationErrorTooHigh { actual: f64, maximum: f64 },
678    MaxTranslationErrorTooHigh { actual: f64, maximum: f64 },
679    NotEnoughMatchedPoses { actual: usize, minimum: usize },
680    MatchRatioTooLow { actual: f64, minimum: f64 },
681    NoMatchedPoses,
682}
683
684impl TrajectoryErrorSummary {
685    pub fn from_trajectories(estimated: &PoseTrajectory, reference: &PoseTrajectory) -> Self {
686        let errors = estimated.translation_errors_against(reference);
687        Self::from_translation_errors(estimated, reference, &errors)
688    }
689
690    fn from_translation_errors(
691        estimated: &PoseTrajectory,
692        reference: &PoseTrajectory,
693        errors: &[TrajectoryTranslationError],
694    ) -> Self {
695        let matched_pose_count = errors.len();
696        let estimated_ids = estimated.frame_id_set();
697        let reference_ids = reference.frame_id_set();
698        let missing_reference_count = estimated_ids.difference(&reference_ids).count();
699        let missing_estimate_count = reference_ids.difference(&estimated_ids).count();
700
701        let (mean_translation_error, rmse_translation_error, max_translation_error) =
702            if errors.is_empty() {
703                (None, None, None)
704            } else {
705                let sum = errors
706                    .iter()
707                    .map(|error| error.translation_error)
708                    .sum::<f64>();
709                let squared_sum = errors
710                    .iter()
711                    .map(|error| error.translation_error * error.translation_error)
712                    .sum::<f64>();
713                let max = errors
714                    .iter()
715                    .map(|error| error.translation_error)
716                    .fold(0.0_f64, f64::max);
717                (
718                    Some(sum / matched_pose_count as f64),
719                    Some((squared_sum / matched_pose_count as f64).sqrt()),
720                    Some(max),
721                )
722            };
723
724        Self {
725            estimated_pose_count: estimated.len(),
726            reference_pose_count: reference.len(),
727            matched_pose_count,
728            missing_reference_count,
729            missing_estimate_count,
730            mean_translation_error,
731            rmse_translation_error,
732            max_translation_error,
733        }
734    }
735
736    pub fn to_json(&self) -> String {
737        format!(
738            concat!(
739                "{{\n",
740                "  \"estimated_pose_count\": {},\n",
741                "  \"reference_pose_count\": {},\n",
742                "  \"matched_pose_count\": {},\n",
743                "  \"missing_reference_count\": {},\n",
744                "  \"missing_estimate_count\": {},\n",
745                "  \"mean_translation_error\": {},\n",
746                "  \"rmse_translation_error\": {},\n",
747                "  \"max_translation_error\": {}\n",
748                "}}\n"
749            ),
750            self.estimated_pose_count,
751            self.reference_pose_count,
752            self.matched_pose_count,
753            self.missing_reference_count,
754            self.missing_estimate_count,
755            optional_f64_json(self.mean_translation_error),
756            optional_f64_json(self.rmse_translation_error),
757            optional_f64_json(self.max_translation_error)
758        )
759    }
760
761    fn to_json_inline(&self) -> String {
762        format!(
763            concat!(
764                "{{",
765                "\"estimated_pose_count\": {}, ",
766                "\"reference_pose_count\": {}, ",
767                "\"matched_pose_count\": {}, ",
768                "\"missing_reference_count\": {}, ",
769                "\"missing_estimate_count\": {}, ",
770                "\"mean_translation_error\": {}, ",
771                "\"rmse_translation_error\": {}, ",
772                "\"max_translation_error\": {}",
773                "}}"
774            ),
775            self.estimated_pose_count,
776            self.reference_pose_count,
777            self.matched_pose_count,
778            self.missing_reference_count,
779            self.missing_estimate_count,
780            optional_f64_json(self.mean_translation_error),
781            optional_f64_json(self.rmse_translation_error),
782            optional_f64_json(self.max_translation_error)
783        )
784    }
785
786    pub fn write_json(&self, path: impl AsRef<Path>) -> std::io::Result<()> {
787        std::fs::write(path, self.to_json())
788    }
789
790    pub fn evaluate(&self, config: TrajectoryEvaluationConfig) -> TrajectoryEvaluationResult {
791        TrajectoryEvaluationResult::from_summary(self.clone(), config)
792    }
793}
794
795impl TrajectoryEvaluationResult {
796    pub fn from_summary(
797        summary: TrajectoryErrorSummary,
798        config: TrajectoryEvaluationConfig,
799    ) -> Self {
800        let match_ratio = if summary.reference_pose_count == 0 {
801            None
802        } else {
803            Some(summary.matched_pose_count as f64 / summary.reference_pose_count as f64)
804        };
805        let mut failures = Vec::new();
806
807        if summary.matched_pose_count == 0 {
808            failures.push(TrajectoryEvaluationFailure::NoMatchedPoses);
809        }
810
811        if let Some(maximum) = config.max_mean_translation_error {
812            match summary.mean_translation_error {
813                Some(actual) if actual > maximum => {
814                    failures.push(TrajectoryEvaluationFailure::MeanTranslationErrorTooHigh {
815                        actual,
816                        maximum,
817                    })
818                }
819                None => failures.push(TrajectoryEvaluationFailure::NoMatchedPoses),
820                _ => {}
821            }
822        }
823
824        if let Some(maximum) = config.max_rmse_translation_error {
825            match summary.rmse_translation_error {
826                Some(actual) if actual > maximum => {
827                    failures.push(TrajectoryEvaluationFailure::RmseTranslationErrorTooHigh {
828                        actual,
829                        maximum,
830                    })
831                }
832                None => failures.push(TrajectoryEvaluationFailure::NoMatchedPoses),
833                _ => {}
834            }
835        }
836
837        if let Some(maximum) = config.max_max_translation_error {
838            match summary.max_translation_error {
839                Some(actual) if actual > maximum => {
840                    failures.push(TrajectoryEvaluationFailure::MaxTranslationErrorTooHigh {
841                        actual,
842                        maximum,
843                    })
844                }
845                None => failures.push(TrajectoryEvaluationFailure::NoMatchedPoses),
846                _ => {}
847            }
848        }
849
850        if let Some(minimum) = config.min_matched_pose_count {
851            if summary.matched_pose_count < minimum {
852                failures.push(TrajectoryEvaluationFailure::NotEnoughMatchedPoses {
853                    actual: summary.matched_pose_count,
854                    minimum,
855                });
856            }
857        }
858
859        if let Some(minimum) = config.min_match_ratio {
860            match match_ratio {
861                Some(actual) if actual < minimum => {
862                    failures.push(TrajectoryEvaluationFailure::MatchRatioTooLow { actual, minimum })
863                }
864                None => failures.push(TrajectoryEvaluationFailure::MatchRatioTooLow {
865                    actual: 0.0,
866                    minimum,
867                }),
868                _ => {}
869            }
870        }
871
872        failures.dedup();
873        let passed = failures.is_empty();
874
875        Self {
876            passed,
877            summary,
878            config,
879            match_ratio,
880            failures,
881        }
882    }
883
884    pub fn to_json(&self) -> String {
885        format!(
886            concat!(
887                "{{\n",
888                "  \"passed\": {},\n",
889                "  \"match_ratio\": {},\n",
890                "  \"config\": {},\n",
891                "  \"summary\": {},\n",
892                "  \"failures\": {}\n",
893                "}}\n"
894            ),
895            self.passed,
896            optional_f64_json(self.match_ratio),
897            self.config.to_json_inline(),
898            self.summary.to_json_inline(),
899            trajectory_evaluation_failures_json(&self.failures)
900        )
901    }
902
903    pub fn write_json(&self, path: impl AsRef<Path>) -> std::io::Result<()> {
904        std::fs::write(path, self.to_json())
905    }
906}
907
908impl TrajectoryEvaluationConfig {
909    fn to_json_inline(&self) -> String {
910        format!(
911            concat!(
912                "{{",
913                "\"max_mean_translation_error\": {}, ",
914                "\"max_rmse_translation_error\": {}, ",
915                "\"max_max_translation_error\": {}, ",
916                "\"min_matched_pose_count\": {}, ",
917                "\"min_match_ratio\": {}",
918                "}}"
919            ),
920            optional_f64_json(self.max_mean_translation_error),
921            optional_f64_json(self.max_rmse_translation_error),
922            optional_f64_json(self.max_max_translation_error),
923            optional_usize_json(self.min_matched_pose_count),
924            optional_f64_json(self.min_match_ratio)
925        )
926    }
927}
928
929impl TrajectoryEvaluationFailure {
930    pub const fn reason(&self) -> &'static str {
931        match self {
932            Self::MeanTranslationErrorTooHigh { .. } => "mean_translation_error_too_high",
933            Self::RmseTranslationErrorTooHigh { .. } => "rmse_translation_error_too_high",
934            Self::MaxTranslationErrorTooHigh { .. } => "max_translation_error_too_high",
935            Self::NotEnoughMatchedPoses { .. } => "not_enough_matched_poses",
936            Self::MatchRatioTooLow { .. } => "match_ratio_too_low",
937            Self::NoMatchedPoses => "no_matched_poses",
938        }
939    }
940
941    pub(crate) fn to_json_inline(&self) -> String {
942        match self {
943            Self::MeanTranslationErrorTooHigh { actual, maximum }
944            | Self::RmseTranslationErrorTooHigh { actual, maximum }
945            | Self::MaxTranslationErrorTooHigh { actual, maximum } => format!(
946                "{{\"reason\": \"{}\", \"actual\": {}, \"maximum\": {}}}",
947                self.reason(),
948                actual,
949                maximum
950            ),
951            Self::NotEnoughMatchedPoses { actual, minimum } => format!(
952                "{{\"reason\": \"{}\", \"actual\": {}, \"minimum\": {}}}",
953                self.reason(),
954                actual,
955                minimum
956            ),
957            Self::MatchRatioTooLow { actual, minimum } => format!(
958                "{{\"reason\": \"{}\", \"actual\": {}, \"minimum\": {}}}",
959                self.reason(),
960                actual,
961                minimum
962            ),
963            Self::NoMatchedPoses => {
964                format!("{{\"reason\": \"{}\"}}", self.reason())
965            }
966        }
967    }
968}
969
970impl TrajectorySummary {
971    pub fn from_trajectory(trajectory: &PoseTrajectory) -> Self {
972        let pose_count = trajectory.len();
973        let first_frame_id = trajectory.samples.first().map(|sample| sample.frame_id);
974        let last_frame_id = trajectory.samples.last().map(|sample| sample.frame_id);
975        let total_path_length = trajectory.total_path_length();
976        let mean_reprojection_error = trajectory.mean_reprojection_error();
977
978        let (mean_inlier_count, mean_inlier_ratio) = if pose_count == 0 {
979            (None, None)
980        } else {
981            let inlier_count_sum: usize = trajectory
982                .samples
983                .iter()
984                .map(|sample| sample.inlier_count)
985                .sum();
986            let inlier_ratio_sum: f64 = trajectory
987                .samples
988                .iter()
989                .map(|sample| sample.inlier_ratio)
990                .sum();
991            (
992                Some(inlier_count_sum as f64 / pose_count as f64),
993                Some(inlier_ratio_sum / pose_count as f64),
994            )
995        };
996
997        let (min_camera_center_world, max_camera_center_world) =
998            trajectory.camera_center_bounds_world();
999
1000        Self {
1001            pose_count,
1002            first_frame_id,
1003            last_frame_id,
1004            total_path_length,
1005            mean_inlier_count,
1006            mean_inlier_ratio,
1007            mean_reprojection_error,
1008            min_camera_center_world,
1009            max_camera_center_world,
1010        }
1011    }
1012
1013    pub fn to_json(&self) -> String {
1014        format!(
1015            concat!(
1016                "{{\n",
1017                "  \"pose_count\": {},\n",
1018                "  \"first_frame_id\": {},\n",
1019                "  \"last_frame_id\": {},\n",
1020                "  \"total_path_length\": {},\n",
1021                "  \"mean_inlier_count\": {},\n",
1022                "  \"mean_inlier_ratio\": {},\n",
1023                "  \"mean_reprojection_error\": {},\n",
1024                "  \"min_camera_center_world\": {},\n",
1025                "  \"max_camera_center_world\": {}\n",
1026                "}}\n"
1027            ),
1028            self.pose_count,
1029            optional_frame_id_json(self.first_frame_id),
1030            optional_frame_id_json(self.last_frame_id),
1031            self.total_path_length,
1032            optional_f64_json(self.mean_inlier_count),
1033            optional_f64_json(self.mean_inlier_ratio),
1034            optional_f64_json(self.mean_reprojection_error),
1035            optional_vec3_json(self.min_camera_center_world),
1036            optional_vec3_json(self.max_camera_center_world)
1037        )
1038    }
1039}
1040
1041impl PoseTrajectory {
1042    pub fn new() -> Self {
1043        Self::default()
1044    }
1045
1046    pub fn from_tracking_results(results: &[TrackingResult]) -> Self {
1047        let mut trajectory = Self::new();
1048        for result in results {
1049            trajectory.push_result(result);
1050        }
1051        trajectory
1052    }
1053
1054    pub fn from_tum_poses_str(text: &str) -> Result<Self, TumTrajectoryParseError> {
1055        let mut trajectory = Self::new();
1056        for (line_index, line) in text.lines().enumerate() {
1057            let line_number = line_index + 1;
1058            let trimmed = line.trim();
1059            if trimmed.is_empty() || trimmed.starts_with('#') {
1060                continue;
1061            }
1062
1063            let fields = trimmed.split_whitespace().collect::<Vec<_>>();
1064            if fields.len() != 8 {
1065                return Err(TumTrajectoryParseError::new(
1066                    line_number,
1067                    line,
1068                    format!("expected 8 fields, got {}", fields.len()),
1069                ));
1070            }
1071
1072            let frame_id = parse_tum_frame_id(fields[0], line_number, line)?;
1073            let tx = parse_tum_f64(fields[1], "tx", line_number, line)?;
1074            let ty = parse_tum_f64(fields[2], "ty", line_number, line)?;
1075            let tz = parse_tum_f64(fields[3], "tz", line_number, line)?;
1076            let qx = parse_tum_f64(fields[4], "qx", line_number, line)?;
1077            let qy = parse_tum_f64(fields[5], "qy", line_number, line)?;
1078            let qz = parse_tum_f64(fields[6], "qz", line_number, line)?;
1079            let qw = parse_tum_f64(fields[7], "qw", line_number, line)?;
1080            let Some(rotation) = UnitQuaternion::try_new(Quaternion::new(qw, qx, qy, qz), 1.0e-12)
1081            else {
1082                return Err(TumTrajectoryParseError::new(
1083                    line_number,
1084                    line,
1085                    "quaternion norm is too small",
1086                ));
1087            };
1088
1089            let camera_to_world = SE3::new(rotation, Vector3::new(tx, ty, tz));
1090            trajectory.push_sample(TrajectorySample {
1091                frame_id,
1092                pose: Pose {
1093                    world_to_camera: camera_to_world.inverse(),
1094                },
1095                state: TrackingState::Tracking,
1096                event: TrackingEvent::Tracked,
1097                inlier_count: 0,
1098                inlier_ratio: 0.0,
1099                reprojection_error: None,
1100            });
1101        }
1102        Ok(trajectory)
1103    }
1104
1105    pub fn read_tum_poses(path: impl AsRef<Path>) -> Result<Self, TrajectoryFileError> {
1106        let text = std::fs::read_to_string(path).map_err(TrajectoryFileError::Io)?;
1107        Self::from_tum_poses_str(&text).map_err(TrajectoryFileError::TumParse)
1108    }
1109
1110    pub fn from_kitti_poses_str(text: &str) -> Result<Self, KittiTrajectoryParseError> {
1111        let mut trajectory = Self::new();
1112        let mut pose_index = 0_u64;
1113        for (line_index, line) in text.lines().enumerate() {
1114            let line_number = line_index + 1;
1115            let trimmed = line.trim();
1116            if trimmed.is_empty() || trimmed.starts_with('#') {
1117                continue;
1118            }
1119
1120            let fields = trimmed.split_whitespace().collect::<Vec<_>>();
1121            if fields.len() != 12 {
1122                return Err(KittiTrajectoryParseError::new(
1123                    line_number,
1124                    line,
1125                    format!("expected 12 fields, got {}", fields.len()),
1126                ));
1127            }
1128
1129            let mut values = [0.0_f64; 12];
1130            for (index, field) in fields.iter().enumerate() {
1131                values[index] = parse_kitti_f64(field, index, line_number, line)?;
1132            }
1133
1134            let rotation = Matrix3::new(
1135                values[0], values[1], values[2], values[4], values[5], values[6], values[8],
1136                values[9], values[10],
1137            );
1138            let translation = Vector3::new(values[3], values[7], values[11]);
1139            let camera_to_world = SE3::new(
1140                UnitQuaternion::from_rotation_matrix(&Rotation3::from_matrix_unchecked(rotation)),
1141                translation,
1142            );
1143            trajectory.push_sample(TrajectorySample {
1144                frame_id: pose_index,
1145                pose: Pose {
1146                    world_to_camera: camera_to_world.inverse(),
1147                },
1148                state: TrackingState::Tracking,
1149                event: TrackingEvent::Tracked,
1150                inlier_count: 0,
1151                inlier_ratio: 0.0,
1152                reprojection_error: None,
1153            });
1154            pose_index += 1;
1155        }
1156        Ok(trajectory)
1157    }
1158
1159    pub fn read_kitti_poses(path: impl AsRef<Path>) -> Result<Self, TrajectoryFileError> {
1160        let text = std::fs::read_to_string(path).map_err(TrajectoryFileError::Io)?;
1161        Self::from_kitti_poses_str(&text).map_err(TrajectoryFileError::KittiParse)
1162    }
1163
1164    pub fn push_result(&mut self, result: &TrackingResult) -> bool {
1165        if let Some(sample) = TrajectorySample::from_tracking_result(result) {
1166            self.samples.push(sample);
1167            true
1168        } else {
1169            false
1170        }
1171    }
1172
1173    pub fn push_sample(&mut self, sample: TrajectorySample) {
1174        self.samples.push(sample);
1175    }
1176
1177    pub fn samples(&self) -> &[TrajectorySample] {
1178        &self.samples
1179    }
1180
1181    pub fn into_samples(self) -> Vec<TrajectorySample> {
1182        self.samples
1183    }
1184
1185    pub fn len(&self) -> usize {
1186        self.samples.len()
1187    }
1188
1189    pub fn is_empty(&self) -> bool {
1190        self.samples.is_empty()
1191    }
1192
1193    pub fn frame_ids(&self) -> Vec<FrameId> {
1194        self.samples.iter().map(|sample| sample.frame_id).collect()
1195    }
1196
1197    fn frame_id_set(&self) -> HashSet<FrameId> {
1198        self.samples.iter().map(|sample| sample.frame_id).collect()
1199    }
1200
1201    pub fn camera_centers_world(&self) -> Vec<Point3<f64>> {
1202        self.samples
1203            .iter()
1204            .map(TrajectorySample::camera_center_world)
1205            .collect()
1206    }
1207
1208    pub fn camera_center_bounds_world(&self) -> (Option<[f64; 3]>, Option<[f64; 3]>) {
1209        let Some(first) = self.samples.first() else {
1210            return (None, None);
1211        };
1212
1213        let first_center = first.camera_center_world();
1214        let mut min = [first_center.x, first_center.y, first_center.z];
1215        let mut max = min;
1216
1217        for sample in self.samples.iter().skip(1) {
1218            let center = sample.camera_center_world();
1219            min[0] = min[0].min(center.x);
1220            min[1] = min[1].min(center.y);
1221            min[2] = min[2].min(center.z);
1222            max[0] = max[0].max(center.x);
1223            max[1] = max[1].max(center.y);
1224            max[2] = max[2].max(center.z);
1225        }
1226
1227        (Some(min), Some(max))
1228    }
1229
1230    pub(crate) fn trajectory_alignment_transform(
1231        &self,
1232        reference_by_frame_id: &HashMap<FrameId, Point3<f64>>,
1233        alignment: TrajectoryAlignment,
1234    ) -> TrajectorySimilarityTransform {
1235        match alignment {
1236            TrajectoryAlignment::None => TrajectorySimilarityTransform::identity(),
1237            TrajectoryAlignment::FirstMatchedTranslation => self
1238                .samples
1239                .iter()
1240                .find_map(|sample| {
1241                    let reference_center = reference_by_frame_id.get(&sample.frame_id)?;
1242                    Some(TrajectorySimilarityTransform::pure_translation(
1243                        reference_center.coords - sample.camera_center_world().coords,
1244                    ))
1245                })
1246                .unwrap_or_else(TrajectorySimilarityTransform::identity),
1247            TrajectoryAlignment::Umeyama | TrajectoryAlignment::UmeyamaWithScale => {
1248                let mut source = Vec::with_capacity(self.samples.len());
1249                let mut target = Vec::with_capacity(self.samples.len());
1250                for sample in &self.samples {
1251                    if let Some(reference_center) = reference_by_frame_id.get(&sample.frame_id) {
1252                        source.push(sample.camera_center_world());
1253                        target.push(*reference_center);
1254                    }
1255                }
1256                let with_scale = matches!(alignment, TrajectoryAlignment::UmeyamaWithScale);
1257                umeyama_similarity_transform(&source, &target, with_scale)
1258                    .unwrap_or_else(TrajectorySimilarityTransform::identity)
1259            }
1260        }
1261    }
1262
1263    pub fn total_path_length(&self) -> f64 {
1264        self.samples
1265            .windows(2)
1266            .map(|window| {
1267                (window[1].camera_center_world() - window[0].camera_center_world()).norm()
1268            })
1269            .sum()
1270    }
1271
1272    pub fn kitti_odometry_benchmark_against(
1273        &self,
1274        reference: &PoseTrajectory,
1275        config: &KittiOdometryBenchmarkConfig,
1276    ) -> KittiOdometryBenchmarkSummary {
1277        let estimated_by_frame_id: HashMap<FrameId, &TrajectorySample> = self
1278            .samples
1279            .iter()
1280            .map(|sample| (sample.frame_id, sample))
1281            .collect();
1282        let matched: Vec<(&TrajectorySample, &TrajectorySample)> = reference
1283            .samples
1284            .iter()
1285            .filter_map(|reference_sample| {
1286                let estimated_sample = estimated_by_frame_id.get(&reference_sample.frame_id)?;
1287                Some((*estimated_sample, reference_sample))
1288            })
1289            .collect();
1290
1291        let distances = cumulative_reference_distances(&matched);
1292        let mut segment_errors = Vec::new();
1293        let start_step = config.start_frame_step.max(1);
1294        for first_index in (0..matched.len()).step_by(start_step) {
1295            let first_distance = distances[first_index];
1296            for &length_m in &config.segment_lengths_m {
1297                if !(length_m.is_finite() && length_m > 0.0) {
1298                    continue;
1299                }
1300                let target_distance = first_distance + length_m;
1301                let Some(last_index) = first_index_for_distance(&distances, target_distance) else {
1302                    continue;
1303                };
1304                if last_index <= first_index {
1305                    continue;
1306                }
1307                let (estimated_first, reference_first) = matched[first_index];
1308                let (estimated_last, reference_last) = matched[last_index];
1309                let estimated_delta = relative_camera_to_world(estimated_first, estimated_last);
1310                let reference_delta = relative_camera_to_world(reference_first, reference_last);
1311                let error = estimated_delta.inverse().compose(&reference_delta);
1312                let translation_error = error.translation.norm() / length_m;
1313                let rotation_error = error.rotation.angle().to_degrees() / length_m;
1314                segment_errors.push(KittiOdometrySegmentError {
1315                    first_frame_id: reference_first.frame_id,
1316                    last_frame_id: reference_last.frame_id,
1317                    length_m,
1318                    translational_error_ratio: translation_error,
1319                    rotational_error_deg_per_m: rotation_error,
1320                });
1321            }
1322        }
1323
1324        let mean_translational_error_percent = if segment_errors.is_empty() {
1325            None
1326        } else {
1327            Some(
1328                segment_errors
1329                    .iter()
1330                    .map(KittiOdometrySegmentError::translational_error_percent)
1331                    .sum::<f64>()
1332                    / segment_errors.len() as f64,
1333            )
1334        };
1335        let mean_rotational_error_deg_per_m = if segment_errors.is_empty() {
1336            None
1337        } else {
1338            Some(
1339                segment_errors
1340                    .iter()
1341                    .map(|error| error.rotational_error_deg_per_m)
1342                    .sum::<f64>()
1343                    / segment_errors.len() as f64,
1344            )
1345        };
1346        KittiOdometryBenchmarkSummary {
1347            estimated_pose_count: self.len(),
1348            reference_pose_count: reference.len(),
1349            matched_pose_count: matched.len(),
1350            segment_count: segment_errors.len(),
1351            mean_translational_error_percent,
1352            mean_rotational_error_deg_per_m,
1353            segment_errors,
1354        }
1355    }
1356
1357    /// Compute the TUM-style relative pose error (RPE) of this trajectory
1358    /// against `reference`.
1359    ///
1360    /// Poses are matched by frame id; the i-th and (i+Δ)-th matched poses form
1361    /// each relative-motion pair, where Δ is `config.delta`. For each pair the
1362    /// relative camera motion of the estimate (`ΔP`) and of the reference
1363    /// (`ΔQ`) are compared via the residual `E = ΔQ⁻¹ · ΔP`, contributing its
1364    /// translation norm (m) and rotation angle (deg). Because relative motion
1365    /// is invariant to a global rigid transform of either trajectory, RPE needs
1366    /// no prior alignment — its defining advantage over the ATE.
1367    pub fn relative_pose_error_against(
1368        &self,
1369        reference: &PoseTrajectory,
1370        config: &RelativePoseErrorConfig,
1371    ) -> RelativePoseErrorSummary {
1372        let estimated_by_frame_id: HashMap<FrameId, &TrajectorySample> = self
1373            .samples
1374            .iter()
1375            .map(|sample| (sample.frame_id, sample))
1376            .collect();
1377        let matched: Vec<(&TrajectorySample, &TrajectorySample)> = reference
1378            .samples
1379            .iter()
1380            .filter_map(|reference_sample| {
1381                let estimated_sample = estimated_by_frame_id.get(&reference_sample.frame_id)?;
1382                Some((*estimated_sample, reference_sample))
1383            })
1384            .collect();
1385
1386        let delta = config.delta.max(1);
1387        let start_step = config.start_step.max(1);
1388        let mut errors = Vec::new();
1389        let mut first_index = 0;
1390        while first_index + delta < matched.len() {
1391            let last_index = first_index + delta;
1392            let (estimated_first, reference_first) = matched[first_index];
1393            let (estimated_last, reference_last) = matched[last_index];
1394            let estimated_delta = relative_camera_to_world(estimated_first, estimated_last);
1395            let reference_delta = relative_camera_to_world(reference_first, reference_last);
1396            let residual = reference_delta.inverse().compose(&estimated_delta);
1397            errors.push(RelativePoseError {
1398                first_frame_id: reference_first.frame_id,
1399                last_frame_id: reference_last.frame_id,
1400                translation_error: residual.translation.norm(),
1401                rotation_error_deg: residual.rotation.angle().to_degrees(),
1402            });
1403            first_index += start_step;
1404        }
1405
1406        let translation_values: Vec<f64> = errors.iter().map(|e| e.translation_error).collect();
1407        let rotation_values: Vec<f64> = errors.iter().map(|e| e.rotation_error_deg).collect();
1408        RelativePoseErrorSummary {
1409            estimated_pose_count: self.len(),
1410            reference_pose_count: reference.len(),
1411            matched_pose_count: matched.len(),
1412            delta,
1413            pair_count: errors.len(),
1414            translation: RelativePoseErrorStatistics::from_values(&translation_values),
1415            rotation_deg: RelativePoseErrorStatistics::from_values(&rotation_values),
1416            errors,
1417        }
1418    }
1419
1420    pub fn mean_reprojection_error(&self) -> Option<f64> {
1421        let mut sum = 0.0;
1422        let mut count = 0;
1423        for sample in &self.samples {
1424            if let Some(error) = sample.reprojection_error {
1425                sum += error;
1426                count += 1;
1427            }
1428        }
1429
1430        if count == 0 {
1431            None
1432        } else {
1433            Some(sum / count as f64)
1434        }
1435    }
1436
1437    pub fn to_csv(&self) -> String {
1438        let mut output = String::from(
1439            "frame_id,camera_center_x,camera_center_y,camera_center_z,qw,qx,qy,qz,tx,ty,tz,state,event,inlier_count,inlier_ratio,reprojection_error\n",
1440        );
1441        for sample in &self.samples {
1442            output.push_str(&sample.to_csv_record());
1443            output.push('\n');
1444        }
1445        output
1446    }
1447
1448    pub fn write_csv(&self, path: impl AsRef<Path>) -> std::io::Result<()> {
1449        std::fs::write(path, self.to_csv())
1450    }
1451
1452    pub fn to_kitti_poses(&self) -> String {
1453        let mut output = String::new();
1454        for sample in &self.samples {
1455            output.push_str(&sample.to_kitti_pose_record());
1456            output.push('\n');
1457        }
1458        output
1459    }
1460
1461    pub fn write_kitti_poses(&self, path: impl AsRef<Path>) -> std::io::Result<()> {
1462        std::fs::write(path, self.to_kitti_poses())
1463    }
1464
1465    pub fn to_tum_poses(&self) -> String {
1466        let mut output = String::new();
1467        for sample in &self.samples {
1468            output.push_str(&sample.to_tum_pose_record());
1469            output.push('\n');
1470        }
1471        output
1472    }
1473
1474    pub fn write_tum_poses(&self, path: impl AsRef<Path>) -> std::io::Result<()> {
1475        std::fs::write(path, self.to_tum_poses())
1476    }
1477
1478    pub fn translation_errors_against(
1479        &self,
1480        reference: &PoseTrajectory,
1481    ) -> Vec<TrajectoryTranslationError> {
1482        self.translation_errors_against_with_alignment(reference, TrajectoryAlignment::None)
1483    }
1484
1485    pub fn translation_errors_against_with_alignment(
1486        &self,
1487        reference: &PoseTrajectory,
1488        alignment: TrajectoryAlignment,
1489    ) -> Vec<TrajectoryTranslationError> {
1490        let reference_by_frame_id = reference
1491            .samples
1492            .iter()
1493            .map(|sample| (sample.frame_id, sample.camera_center_world()))
1494            .collect::<HashMap<_, _>>();
1495        let transform = self.trajectory_alignment_transform(&reference_by_frame_id, alignment);
1496
1497        self.samples
1498            .iter()
1499            .filter_map(|sample| {
1500                let reference_center = reference_by_frame_id.get(&sample.frame_id)?;
1501                let aligned_center = transform.apply(&sample.camera_center_world());
1502                Some(TrajectoryTranslationError {
1503                    frame_id: sample.frame_id,
1504                    translation_error: (aligned_center - reference_center).norm(),
1505                })
1506            })
1507            .collect()
1508    }
1509
1510    pub fn translation_error_summary_against(
1511        &self,
1512        reference: &PoseTrajectory,
1513    ) -> TrajectoryErrorSummary {
1514        TrajectoryErrorSummary::from_trajectories(self, reference)
1515    }
1516
1517    pub fn translation_error_summary_against_with_alignment(
1518        &self,
1519        reference: &PoseTrajectory,
1520        alignment: TrajectoryAlignment,
1521    ) -> TrajectoryErrorSummary {
1522        let errors = self.translation_errors_against_with_alignment(reference, alignment);
1523        TrajectoryErrorSummary::from_translation_errors(self, reference, &errors)
1524    }
1525
1526    pub fn translation_errors_csv_against(&self, reference: &PoseTrajectory) -> String {
1527        self.translation_errors_csv_against_with_alignment(reference, TrajectoryAlignment::None)
1528    }
1529
1530    pub fn translation_errors_csv_against_with_alignment(
1531        &self,
1532        reference: &PoseTrajectory,
1533        alignment: TrajectoryAlignment,
1534    ) -> String {
1535        let mut output = String::from("frame_id,translation_error\n");
1536        for error in self.translation_errors_against_with_alignment(reference, alignment) {
1537            output.push_str(&error.to_csv_record());
1538            output.push('\n');
1539        }
1540        output
1541    }
1542
1543    pub fn write_translation_errors_csv_against(
1544        &self,
1545        reference: &PoseTrajectory,
1546        path: impl AsRef<Path>,
1547    ) -> std::io::Result<()> {
1548        std::fs::write(path, self.translation_errors_csv_against(reference))
1549    }
1550
1551    pub fn write_translation_errors_csv_against_with_alignment(
1552        &self,
1553        reference: &PoseTrajectory,
1554        alignment: TrajectoryAlignment,
1555        path: impl AsRef<Path>,
1556    ) -> std::io::Result<()> {
1557        std::fs::write(
1558            path,
1559            self.translation_errors_csv_against_with_alignment(reference, alignment),
1560        )
1561    }
1562
1563    pub fn write_translation_error_summary_json_against(
1564        &self,
1565        reference: &PoseTrajectory,
1566        path: impl AsRef<Path>,
1567    ) -> std::io::Result<()> {
1568        self.translation_error_summary_against(reference)
1569            .write_json(path)
1570    }
1571
1572    pub fn write_translation_error_summary_json_against_with_alignment(
1573        &self,
1574        reference: &PoseTrajectory,
1575        alignment: TrajectoryAlignment,
1576        path: impl AsRef<Path>,
1577    ) -> std::io::Result<()> {
1578        self.translation_error_summary_against_with_alignment(reference, alignment)
1579            .write_json(path)
1580    }
1581
1582    pub fn to_html_report(&self) -> String {
1583        let summary = self.summary();
1584        let svg = trajectory_svg(self);
1585        let mut output = String::new();
1586        output.push_str("<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n");
1587        output
1588            .push_str("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n");
1589        output.push_str("<title>visloc-rs trajectory report</title>\n");
1590        output.push_str("<style>");
1591        output.push_str(
1592            "body{margin:0;font-family:system-ui,-apple-system,Segoe UI,sans-serif;background:#f6f7f9;color:#182026}\
1593             main{max-width:1080px;margin:0 auto;padding:28px}\
1594             h1{font-size:24px;margin:0 0 8px}\
1595             .sub{margin:0 0 22px;color:#52616b}\
1596             .grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:10px;margin:18px 0}\
1597             .metric{background:white;border:1px solid #dde3ea;border-radius:8px;padding:12px}\
1598             .label{display:block;font-size:12px;color:#65727e}\
1599             .value{display:block;font-size:22px;font-weight:700;margin-top:4px}\
1600             .panel{background:white;border:1px solid #dde3ea;border-radius:8px;padding:16px;margin-top:14px}\
1601             .legend{display:flex;gap:18px;flex-wrap:wrap;margin:10px 0 0;color:#52616b;font-size:13px}\
1602             .swatch{display:inline-block;width:26px;height:4px;border-radius:2px;vertical-align:middle;margin-right:6px}\
1603             code{background:#eef2f5;border-radius:4px;padding:2px 4px}\
1604             svg{width:100%;height:auto;display:block}",
1605        );
1606        output.push_str("</style>\n</head>\n<body>\n<main>\n");
1607        output.push_str("<h1>visloc-rs trajectory report</h1>\n");
1608        output.push_str(
1609            "<p class=\"sub\">Estimated camera-center trajectory from sequence localization.</p>\n",
1610        );
1611        output.push_str("<section class=\"grid\">\n");
1612        push_metric_card(&mut output, "Poses", &summary.pose_count.to_string());
1613        push_metric_card(
1614            &mut output,
1615            "First frame",
1616            &format_optional_frame_id(summary.first_frame_id),
1617        );
1618        push_metric_card(
1619            &mut output,
1620            "Last frame",
1621            &format_optional_frame_id(summary.last_frame_id),
1622        );
1623        push_metric_card(
1624            &mut output,
1625            "Path length",
1626            &format_optional_metric(Some(summary.total_path_length), "m"),
1627        );
1628        push_metric_card(
1629            &mut output,
1630            "Mean inliers",
1631            &format_optional_count(summary.mean_inlier_count),
1632        );
1633        push_metric_card(
1634            &mut output,
1635            "Mean reprojection",
1636            &format_optional_metric(summary.mean_reprojection_error, "px"),
1637        );
1638        output.push_str("</section>\n");
1639        output.push_str("<section class=\"panel\">\n");
1640        output.push_str(&svg);
1641        output.push_str(
1642            "<div class=\"legend\"><span><span class=\"swatch\" style=\"background:#e0574f\"></span>estimated trajectory</span></div>\n",
1643        );
1644        output.push_str("</section>\n</main>\n</body>\n</html>\n");
1645        output
1646    }
1647
1648    pub fn write_html_report(&self, path: impl AsRef<Path>) -> std::io::Result<()> {
1649        std::fs::write(path, self.to_html_report())
1650    }
1651
1652    pub fn to_html_report_against(&self, reference: &PoseTrajectory) -> String {
1653        self.to_html_report_against_with_alignment(reference, TrajectoryAlignment::None)
1654    }
1655
1656    pub fn to_html_report_against_with_alignment(
1657        &self,
1658        reference: &PoseTrajectory,
1659        alignment: TrajectoryAlignment,
1660    ) -> String {
1661        let summary = self.translation_error_summary_against_with_alignment(reference, alignment);
1662        let errors = self.translation_errors_against_with_alignment(reference, alignment);
1663        let svg = trajectory_comparison_svg(self, reference, alignment);
1664        let mut output = String::new();
1665        output.push_str("<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n");
1666        output
1667            .push_str("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n");
1668        output.push_str("<title>visloc-rs trajectory evaluation</title>\n");
1669        output.push_str("<style>");
1670        output.push_str(
1671            "body{margin:0;font-family:system-ui,-apple-system,Segoe UI,sans-serif;background:#f6f7f9;color:#182026}\
1672             main{max-width:1080px;margin:0 auto;padding:28px}\
1673             h1{font-size:24px;margin:0 0 8px}\
1674             .sub{margin:0 0 22px;color:#52616b}\
1675             .grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:10px;margin:18px 0}\
1676             .metric{background:white;border:1px solid #dde3ea;border-radius:8px;padding:12px}\
1677             .label{display:block;font-size:12px;color:#65727e}\
1678             .value{display:block;font-size:22px;font-weight:700;margin-top:4px}\
1679             .panel{background:white;border:1px solid #dde3ea;border-radius:8px;padding:16px;margin-top:14px}\
1680             .legend{display:flex;gap:18px;flex-wrap:wrap;margin:10px 0 0;color:#52616b;font-size:13px}\
1681             .swatch{display:inline-block;width:26px;height:4px;border-radius:2px;vertical-align:middle;margin-right:6px}\
1682             table{width:100%;border-collapse:collapse;font-size:13px}\
1683             th,td{text-align:right;border-bottom:1px solid #e7ecf0;padding:6px 8px}\
1684             th:first-child,td:first-child{text-align:left}\
1685             code{background:#eef2f5;border-radius:4px;padding:2px 4px}\
1686             svg{width:100%;height:auto;display:block}",
1687        );
1688        output.push_str("</style>\n</head>\n<body>\n<main>\n");
1689        output.push_str("<h1>visloc-rs trajectory evaluation</h1>\n");
1690        let _ = writeln!(
1691            output,
1692            "<p class=\"sub\">Estimated trajectory compared with reference poses. Alignment: <code>{alignment:?}</code></p>"
1693        );
1694        output.push_str("<section class=\"grid\">\n");
1695        push_metric_card(
1696            &mut output,
1697            "Estimated poses",
1698            &summary.estimated_pose_count.to_string(),
1699        );
1700        push_metric_card(
1701            &mut output,
1702            "Reference poses",
1703            &summary.reference_pose_count.to_string(),
1704        );
1705        push_metric_card(
1706            &mut output,
1707            "Matched poses",
1708            &summary.matched_pose_count.to_string(),
1709        );
1710        push_metric_card(
1711            &mut output,
1712            "Mean error",
1713            &format_optional_metric(summary.mean_translation_error, "m"),
1714        );
1715        push_metric_card(
1716            &mut output,
1717            "RMSE",
1718            &format_optional_metric(summary.rmse_translation_error, "m"),
1719        );
1720        push_metric_card(
1721            &mut output,
1722            "Max error",
1723            &format_optional_metric(summary.max_translation_error, "m"),
1724        );
1725        output.push_str("</section>\n");
1726        output.push_str("<section class=\"panel\">\n");
1727        output.push_str(&svg);
1728        output.push_str(
1729            "<div class=\"legend\"><span><span class=\"swatch\" style=\"background:#e0574f\"></span>estimated</span><span><span class=\"swatch\" style=\"background:#2676c9\"></span>reference</span><span><span class=\"swatch\" style=\"background:#9aa7b2\"></span>matched error</span></div>\n",
1730        );
1731        output.push_str("</section>\n");
1732        output.push_str("<section class=\"panel\">\n<h2>Matched translation errors</h2>\n");
1733        output.push_str(
1734            "<table><thead><tr><th>frame</th><th>translation error</th></tr></thead><tbody>\n",
1735        );
1736        for error in errors.iter().take(80) {
1737            let _ = writeln!(
1738                output,
1739                "<tr><td>{}</td><td>{}</td></tr>",
1740                error.frame_id,
1741                format_optional_metric(Some(error.translation_error), "m")
1742            );
1743        }
1744        if errors.len() > 80 {
1745            let _ = writeln!(
1746                output,
1747                "<tr><td colspan=\"2\">{} more rows omitted</td></tr>",
1748                errors.len() - 80
1749            );
1750        }
1751        output.push_str("</tbody></table>\n</section>\n</main>\n</body>\n</html>\n");
1752        output
1753    }
1754
1755    pub fn write_html_report_against(
1756        &self,
1757        reference: &PoseTrajectory,
1758        path: impl AsRef<Path>,
1759    ) -> std::io::Result<()> {
1760        std::fs::write(path, self.to_html_report_against(reference))
1761    }
1762
1763    pub fn write_html_report_against_with_alignment(
1764        &self,
1765        reference: &PoseTrajectory,
1766        alignment: TrajectoryAlignment,
1767        path: impl AsRef<Path>,
1768    ) -> std::io::Result<()> {
1769        std::fs::write(
1770            path,
1771            self.to_html_report_against_with_alignment(reference, alignment),
1772        )
1773    }
1774
1775    pub fn summary(&self) -> TrajectorySummary {
1776        TrajectorySummary::from_trajectory(self)
1777    }
1778
1779    pub fn to_summary_json(&self) -> String {
1780        self.summary().to_json()
1781    }
1782
1783    pub fn write_summary_json(&self, path: impl AsRef<Path>) -> std::io::Result<()> {
1784        std::fs::write(path, self.to_summary_json())
1785    }
1786}
1787
1788fn parse_tum_frame_id(
1789    value: &str,
1790    line_number: usize,
1791    line: &str,
1792) -> Result<FrameId, TumTrajectoryParseError> {
1793    value.parse::<FrameId>().map_err(|error| {
1794        TumTrajectoryParseError::new(line_number, line, format!("invalid frame_id: {error}"))
1795    })
1796}
1797
1798fn parse_tum_f64(
1799    value: &str,
1800    field_name: &str,
1801    line_number: usize,
1802    line: &str,
1803) -> Result<f64, TumTrajectoryParseError> {
1804    value.parse::<f64>().map_err(|error| {
1805        TumTrajectoryParseError::new(line_number, line, format!("invalid {field_name}: {error}"))
1806    })
1807}
1808
1809fn parse_kitti_f64(
1810    value: &str,
1811    field_index: usize,
1812    line_number: usize,
1813    line: &str,
1814) -> Result<f64, KittiTrajectoryParseError> {
1815    value.parse::<f64>().map_err(|error| {
1816        KittiTrajectoryParseError::new(
1817            line_number,
1818            line,
1819            format!("invalid field {field_index}: {error}"),
1820        )
1821    })
1822}
1823
1824fn cumulative_reference_distances(matched: &[(&TrajectorySample, &TrajectorySample)]) -> Vec<f64> {
1825    let mut distances = Vec::with_capacity(matched.len());
1826    let mut cumulative = 0.0;
1827    for (index, (_, reference_sample)) in matched.iter().enumerate() {
1828        if index > 0 {
1829            let previous = matched[index - 1].1.camera_center_world();
1830            let current = reference_sample.camera_center_world();
1831            cumulative += (current - previous).norm();
1832        }
1833        distances.push(cumulative);
1834    }
1835    distances
1836}
1837
1838fn first_index_for_distance(distances: &[f64], target_distance: f64) -> Option<usize> {
1839    distances
1840        .iter()
1841        .position(|distance| *distance >= target_distance)
1842}
1843
1844fn relative_camera_to_world(first: &TrajectorySample, last: &TrajectorySample) -> SE3 {
1845    let first_camera_to_world = first.pose.world_to_camera.inverse();
1846    let last_camera_to_world = last.pose.world_to_camera.inverse();
1847    first_camera_to_world
1848        .inverse()
1849        .compose(&last_camera_to_world)
1850}
1851
1852#[cfg(test)]
1853mod umeyama_alignment_tests {
1854    use super::*;
1855    use nalgebra::{Point3, Rotation3, UnitQuaternion, Vector3};
1856
1857    fn make_source() -> Vec<Point3<f64>> {
1858        vec![
1859            Point3::new(0.0, 0.0, 0.0),
1860            Point3::new(1.0, 0.0, 0.0),
1861            Point3::new(0.0, 1.0, 0.0),
1862            Point3::new(0.0, 0.0, 1.0),
1863            Point3::new(2.5, -1.0, 0.5),
1864        ]
1865    }
1866
1867    fn transform_points(
1868        points: &[Point3<f64>],
1869        scale: f64,
1870        rotation: &Rotation3<f64>,
1871        translation: &Vector3<f64>,
1872    ) -> Vec<Point3<f64>> {
1873        points
1874            .iter()
1875            .map(|p| Point3::from(rotation * (p.coords * scale) + translation))
1876            .collect()
1877    }
1878
1879    #[test]
1880    fn umeyama_recovers_pure_translation() {
1881        let source = make_source();
1882        let translation = Vector3::new(5.0, -2.0, 1.5);
1883        let target = transform_points(&source, 1.0, &Rotation3::identity(), &translation);
1884        let transform = umeyama_similarity_transform(&source, &target, false).expect("transform");
1885        assert!((transform.scale - 1.0).abs() < 1e-12);
1886        assert!((transform.translation - translation).norm() < 1e-10);
1887        assert!(transform.rotation.matrix().relative_eq(
1888            Rotation3::<f64>::identity().matrix(),
1889            1e-10,
1890            1e-10
1891        ));
1892    }
1893
1894    #[test]
1895    fn umeyama_recovers_rotation_and_translation() {
1896        let source = make_source();
1897        let rotation = Rotation3::from_euler_angles(0.3, -0.4, 0.5);
1898        let translation = Vector3::new(-1.0, 2.0, -3.0);
1899        let target = transform_points(&source, 1.0, &rotation, &translation);
1900        let transform = umeyama_similarity_transform(&source, &target, false).expect("transform");
1901        assert!((transform.scale - 1.0).abs() < 1e-10);
1902        assert!((transform.translation - translation).norm() < 1e-8);
1903        assert!(transform
1904            .rotation
1905            .matrix()
1906            .relative_eq(rotation.matrix(), 1e-8, 1e-8));
1907        let aligned: Vec<Point3<f64>> = source.iter().map(|p| transform.apply(p)).collect();
1908        for (a, t) in aligned.iter().zip(target.iter()) {
1909            assert!((a - t).norm() < 1e-8);
1910        }
1911    }
1912
1913    #[test]
1914    fn umeyama_recovers_similarity_with_scale() {
1915        let source = make_source();
1916        let scale = 3.4;
1917        let rotation = Rotation3::from_euler_angles(-0.2, 0.8, 0.1);
1918        let translation = Vector3::new(2.0, 0.5, -1.0);
1919        let target = transform_points(&source, scale, &rotation, &translation);
1920        let transform = umeyama_similarity_transform(&source, &target, true).expect("transform");
1921        assert!((transform.scale - scale).abs() < 1e-8);
1922        assert!((transform.translation - translation).norm() < 1e-7);
1923        assert!(transform
1924            .rotation
1925            .matrix()
1926            .relative_eq(rotation.matrix(), 1e-8, 1e-8));
1927    }
1928
1929    #[test]
1930    fn umeyama_returns_none_for_insufficient_points() {
1931        let source = vec![Point3::new(0.0, 0.0, 0.0)];
1932        let target = vec![Point3::new(1.0, 0.0, 0.0)];
1933        assert!(umeyama_similarity_transform(&source, &target, false).is_none());
1934    }
1935
1936    #[test]
1937    fn umeyama_returns_none_for_zero_variance_source() {
1938        let source = vec![Point3::new(0.0, 0.0, 0.0), Point3::new(0.0, 0.0, 0.0)];
1939        let target = vec![Point3::new(1.0, 0.0, 0.0), Point3::new(0.0, 1.0, 0.0)];
1940        assert!(umeyama_similarity_transform(&source, &target, false).is_none());
1941    }
1942
1943    fn pose_with_camera_center(frame_id: FrameId, center: Point3<f64>) -> TrajectorySample {
1944        let pose = Pose::from_world_to_camera(UnitQuaternion::identity(), -center.coords);
1945        TrajectorySample {
1946            frame_id,
1947            pose,
1948            state: TrackingState::Tracking,
1949            event: TrackingEvent::Tracked,
1950            inlier_count: 0,
1951            inlier_ratio: 0.0,
1952            reprojection_error: None,
1953        }
1954    }
1955
1956    fn build_trajectory(centers: &[(FrameId, Point3<f64>)]) -> PoseTrajectory {
1957        let mut trajectory = PoseTrajectory::new();
1958        for (id, p) in centers {
1959            trajectory.push_sample(pose_with_camera_center(*id, *p));
1960        }
1961        trajectory
1962    }
1963
1964    #[test]
1965    fn trajectory_alignment_umeyama_drives_error_to_zero_for_similarity_perturbation() {
1966        let scale = 2.0;
1967        let rotation = Rotation3::from_euler_angles(0.1, -0.2, 0.3);
1968        let translation = Vector3::new(7.0, -4.0, 2.0);
1969        let reference_centers: Vec<(FrameId, Point3<f64>)> = (0..6)
1970            .map(|i| {
1971                let p = Point3::new(i as f64, (i as f64).sin(), (i as f64).cos());
1972                (i as FrameId, p)
1973            })
1974            .collect();
1975        let estimated_centers: Vec<(FrameId, Point3<f64>)> = reference_centers
1976            .iter()
1977            .map(|(id, p)| {
1978                let inv_translation = -translation;
1979                let inv_rotation = rotation.inverse();
1980                let inv_scale = 1.0 / scale;
1981                let pre = p.coords + inv_translation;
1982                let body = inv_rotation * pre * inv_scale;
1983                (*id, Point3::from(body))
1984            })
1985            .collect();
1986        let reference = build_trajectory(&reference_centers);
1987        let estimated = build_trajectory(&estimated_centers);
1988
1989        let aligned_summary = estimated.translation_error_summary_against_with_alignment(
1990            &reference,
1991            TrajectoryAlignment::UmeyamaWithScale,
1992        );
1993        let rmse = aligned_summary.rmse_translation_error.expect("rmse");
1994        assert!(
1995            rmse < 1e-7,
1996            "expected near-zero ATE after similarity alignment, got {rmse}"
1997        );
1998
1999        let raw_summary = estimated.translation_error_summary_against_with_alignment(
2000            &reference,
2001            TrajectoryAlignment::None,
2002        );
2003        let raw_rmse = raw_summary.rmse_translation_error.expect("raw rmse");
2004        assert!(
2005            raw_rmse > 1.0,
2006            "expected substantial raw error before alignment, got {raw_rmse}"
2007        );
2008    }
2009
2010    #[test]
2011    fn trajectory_alignment_umeyama_rigid_does_not_remove_scale() {
2012        let reference_centers: Vec<(FrameId, Point3<f64>)> = (0..5)
2013            .map(|i| (i as FrameId, Point3::new(i as f64, 0.0, 0.0)))
2014            .collect();
2015        let estimated_centers: Vec<(FrameId, Point3<f64>)> = reference_centers
2016            .iter()
2017            .map(|(id, p)| (*id, Point3::from(p.coords * 0.5)))
2018            .collect();
2019        let reference = build_trajectory(&reference_centers);
2020        let estimated = build_trajectory(&estimated_centers);
2021
2022        let rigid = estimated.translation_error_summary_against_with_alignment(
2023            &reference,
2024            TrajectoryAlignment::Umeyama,
2025        );
2026        let scaled = estimated.translation_error_summary_against_with_alignment(
2027            &reference,
2028            TrajectoryAlignment::UmeyamaWithScale,
2029        );
2030        let rigid_rmse = rigid.rmse_translation_error.expect("rigid rmse");
2031        let scaled_rmse = scaled.rmse_translation_error.expect("scaled rmse");
2032        assert!(
2033            scaled_rmse < 1e-8,
2034            "expected near-zero ATE after similarity alignment, got {scaled_rmse}"
2035        );
2036        assert!(
2037            rigid_rmse > 0.1,
2038            "expected non-trivial residual under rigid alignment of half-scale trajectory, got {rigid_rmse}"
2039        );
2040    }
2041
2042    fn rpe_sample(frame_id: FrameId, camera_to_world: SE3) -> TrajectorySample {
2043        let world_to_camera = camera_to_world.inverse();
2044        TrajectorySample {
2045            frame_id,
2046            pose: Pose::from_world_to_camera(world_to_camera.rotation, world_to_camera.translation),
2047            state: TrackingState::Tracking,
2048            event: TrackingEvent::Tracked,
2049            inlier_count: 0,
2050            inlier_ratio: 0.0,
2051            reprojection_error: None,
2052        }
2053    }
2054
2055    fn rpe_trajectory(poses: &[(FrameId, SE3)]) -> PoseTrajectory {
2056        let mut trajectory = PoseTrajectory::new();
2057        for (id, camera_to_world) in poses {
2058            trajectory.push_sample(rpe_sample(*id, camera_to_world.clone()));
2059        }
2060        trajectory
2061    }
2062
2063    #[test]
2064    fn relative_pose_error_is_zero_when_estimate_matches_reference() {
2065        let poses: Vec<(FrameId, SE3)> = (0..8)
2066            .map(|i| {
2067                let c2w = SE3::new(
2068                    UnitQuaternion::from_euler_angles(0.0, 0.0, 0.05 * i as f64),
2069                    Vector3::new(i as f64, (i as f64 * 0.3).sin(), 0.0),
2070                );
2071                (i as FrameId, c2w)
2072            })
2073            .collect();
2074        let trajectory = rpe_trajectory(&poses);
2075
2076        let summary = trajectory
2077            .relative_pose_error_against(&trajectory, &RelativePoseErrorConfig::default());
2078
2079        assert_eq!(summary.pair_count, 7);
2080        let translation = summary.translation.expect("translation stats");
2081        let rotation = summary.rotation_deg.expect("rotation stats");
2082        assert!(
2083            translation.rmse < 1e-9,
2084            "translation rmse {}",
2085            translation.rmse
2086        );
2087        assert!(rotation.rmse < 1e-9, "rotation rmse {}", rotation.rmse);
2088    }
2089
2090    #[test]
2091    fn relative_pose_error_is_invariant_to_a_global_rigid_transform() {
2092        // RPE compares *relative* motion, which is unchanged by left-multiplying
2093        // every pose by a fixed rigid transform — so a globally displaced and
2094        // rotated estimate scores ~0 RPE while its raw (unaligned) ATE is large.
2095        let global = SE3::new(
2096            UnitQuaternion::from_euler_angles(0.1, -0.2, 0.3),
2097            Vector3::new(7.0, -4.0, 2.0),
2098        );
2099        let reference_poses: Vec<(FrameId, SE3)> = (0..10)
2100            .map(|i| {
2101                let c2w = SE3::new(
2102                    UnitQuaternion::from_euler_angles(0.0, 0.0, 0.1 * i as f64),
2103                    Vector3::new(i as f64, (i as f64).sin(), (i as f64).cos()),
2104                );
2105                (i as FrameId, c2w)
2106            })
2107            .collect();
2108        let estimated_poses: Vec<(FrameId, SE3)> = reference_poses
2109            .iter()
2110            .map(|(id, c2w)| (*id, global.compose(c2w)))
2111            .collect();
2112        let reference = rpe_trajectory(&reference_poses);
2113        let estimated = rpe_trajectory(&estimated_poses);
2114
2115        let summary = estimated.relative_pose_error_against(
2116            &reference,
2117            &RelativePoseErrorConfig {
2118                delta: 2,
2119                start_step: 1,
2120            },
2121        );
2122        assert_eq!(summary.delta, 2);
2123        let translation = summary.translation.expect("translation stats");
2124        let rotation = summary.rotation_deg.expect("rotation stats");
2125        assert!(
2126            translation.rmse < 1e-9 && rotation.rmse < 1e-9,
2127            "RPE should vanish under a global rigid transform, got t={} r={}",
2128            translation.rmse,
2129            rotation.rmse
2130        );
2131
2132        // Contrast: the unaligned absolute trajectory error is far from zero.
2133        let ate = estimated
2134            .translation_error_summary_against_with_alignment(&reference, TrajectoryAlignment::None)
2135            .rmse_translation_error
2136            .expect("ate rmse");
2137        assert!(
2138            ate > 1.0,
2139            "expected large raw ATE for the displaced estimate, got {ate}"
2140        );
2141    }
2142
2143    #[test]
2144    fn relative_pose_error_recovers_a_constant_per_step_drift() {
2145        // Reference advances one meter per step with no rotation. The estimate's
2146        // per-step relative motion carries a fixed extra transform `drift`, so
2147        // every residual equals `drift`: translation 0.1 m, rotation 5 deg.
2148        let step = SE3::new(UnitQuaternion::identity(), Vector3::new(1.0, 0.0, 0.0));
2149        let drift = SE3::new(
2150            UnitQuaternion::from_euler_angles(0.0, 0.0, 5.0_f64.to_radians()),
2151            Vector3::new(0.1, 0.0, 0.0),
2152        );
2153
2154        let mut reference_poses = vec![(0u64, SE3::identity())];
2155        let mut estimated_poses = vec![(0u64, SE3::identity())];
2156        for i in 1..7u64 {
2157            let previous_reference = reference_poses[(i - 1) as usize].1.clone();
2158            reference_poses.push((i, previous_reference.compose(&step)));
2159            let previous_estimate = estimated_poses[(i - 1) as usize].1.clone();
2160            estimated_poses.push((i, previous_estimate.compose(&step).compose(&drift)));
2161        }
2162        let reference = rpe_trajectory(&reference_poses);
2163        let estimated = rpe_trajectory(&estimated_poses);
2164
2165        let summary =
2166            estimated.relative_pose_error_against(&reference, &RelativePoseErrorConfig::default());
2167        let translation = summary.translation.expect("translation stats");
2168        let rotation = summary.rotation_deg.expect("rotation stats");
2169        // Tolerances absorb float accumulation through the multi-step compose
2170        // chain and quaternion angle extraction.
2171        assert!(
2172            (translation.mean - 0.1).abs() < 1e-6,
2173            "translation mean {}",
2174            translation.mean
2175        );
2176        assert!(
2177            translation.std < 1e-6,
2178            "translation std {}",
2179            translation.std
2180        );
2181        assert!(
2182            (rotation.mean - 5.0).abs() < 1e-6,
2183            "rotation mean {}",
2184            rotation.mean
2185        );
2186        assert!(rotation.std < 1e-6, "rotation std {}", rotation.std);
2187    }
2188
2189    #[test]
2190    fn relative_pose_error_has_no_pairs_when_delta_exceeds_overlap() {
2191        let poses: Vec<(FrameId, SE3)> = (0..3)
2192            .map(|i| {
2193                (
2194                    i as FrameId,
2195                    SE3::new(UnitQuaternion::identity(), Vector3::new(i as f64, 0.0, 0.0)),
2196                )
2197            })
2198            .collect();
2199        let trajectory = rpe_trajectory(&poses);
2200        let summary = trajectory.relative_pose_error_against(
2201            &trajectory,
2202            &RelativePoseErrorConfig {
2203                delta: 5,
2204                start_step: 1,
2205            },
2206        );
2207        assert_eq!(summary.pair_count, 0);
2208        assert!(summary.translation.is_none());
2209        assert!(summary.rotation_deg.is_none());
2210    }
2211
2212    fn fake_success_tracking_result(frame_id: u64) -> TrackingResult {
2213        fake_success_tracking_result_with_pose(
2214            frame_id,
2215            Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::zeros()),
2216        )
2217    }
2218
2219    fn fake_success_tracking_result_with_pose(frame_id: u64, pose: Pose) -> TrackingResult {
2220        use visloc_core::types::LocalizationSuccess;
2221        let localization = LocalizationResult::success(LocalizationSuccess {
2222            pose,
2223            candidate_landmark_count: 4,
2224            match_count: 4,
2225            correspondence_count: 4,
2226            inliers: vec![0, 1, 2, 3],
2227            inlier_query_indices: vec![0, 1, 2, 3],
2228            inlier_landmark_ids: vec![1, 2, 3, 4],
2229            inlier_confidences: vec![None; 4],
2230            inlier_reprojection_errors: vec![0.0; 4],
2231            mean_reprojection_error: 0.0,
2232            median_reprojection_error: 0.0,
2233            max_reprojection_error: 0.0,
2234        });
2235        TrackingResult {
2236            frame_id,
2237            state: TrackingState::Tracking,
2238            event: TrackingEvent::Tracked,
2239            successive_failures: 0,
2240            pose_prior: None,
2241            used_pose_prior: false,
2242            used_external_localization_prior: false,
2243            external_localization_prior_radius: None,
2244            tracking_failure_reason: None,
2245            map_landmark_count: 0,
2246            map_stats: MapProviderStats::default(),
2247            localization,
2248            covisibility_local_map_size: None,
2249        }
2250    }
2251
2252    fn fake_failure_tracking_result(frame_id: u64) -> TrackingResult {
2253        let localization = LocalizationResult::failure(
2254            visloc_core::types::LocalizationFailureReason::QualityGateFailed,
2255            0,
2256            0,
2257            0,
2258        );
2259        TrackingResult {
2260            frame_id,
2261            state: TrackingState::Tracking,
2262            event: TrackingEvent::TrackingFailed,
2263            successive_failures: 1,
2264            pose_prior: None,
2265            used_pose_prior: false,
2266            used_external_localization_prior: false,
2267            external_localization_prior_radius: None,
2268            tracking_failure_reason: Some(TrackingFailureReason::InsufficientInliers {
2269                inlier_count: 0,
2270                min_inliers: 10,
2271            }),
2272            map_landmark_count: 0,
2273            map_stats: MapProviderStats::default(),
2274            localization,
2275            covisibility_local_map_size: None,
2276        }
2277    }
2278
2279    #[test]
2280    fn adaptive_motion_starts_in_imu_mode() {
2281        let model = AdaptiveImuPoseMotionModel::with_defaults();
2282        assert_eq!(model.mode(), AdaptiveMotionMode::Imu);
2283        assert_eq!(model.switches_to_pose(), 0);
2284        assert_eq!(model.switches_to_imu(), 0);
2285    }
2286
2287    #[test]
2288    fn adaptive_motion_switches_to_pose_after_consecutive_failures() {
2289        let mut model = AdaptiveImuPoseMotionModel::new(
2290            ImuPredictiveMotionModel::new(ImuPredictiveMotionModelConfig::default()),
2291            ConstantPoseMotionModel,
2292            AdaptiveImuPoseMotionModelConfig {
2293                failures_to_switch_to_pose: 2,
2294                successes_to_switch_to_imu: 5,
2295                ..AdaptiveImuPoseMotionModelConfig::default()
2296            },
2297        );
2298        model.observe(&fake_failure_tracking_result(1));
2299        assert_eq!(model.mode(), AdaptiveMotionMode::Imu);
2300        model.observe(&fake_failure_tracking_result(2));
2301        assert_eq!(model.mode(), AdaptiveMotionMode::Pose);
2302        assert_eq!(model.switches_to_pose(), 1);
2303    }
2304
2305    #[test]
2306    fn pose_fallback_disables_pnp_warm_start_until_adaptive_imu_recovers() {
2307        assert!(!ConstantPoseMotionModel.allows_pnp_pose_prior_warm_start());
2308
2309        let mut model = AdaptiveImuPoseMotionModel::new(
2310            ImuPredictiveMotionModel::new(ImuPredictiveMotionModelConfig::default()),
2311            ConstantPoseMotionModel,
2312            AdaptiveImuPoseMotionModelConfig {
2313                failures_to_switch_to_pose: 1,
2314                successes_to_switch_to_imu: 2,
2315                ..AdaptiveImuPoseMotionModelConfig::default()
2316            },
2317        );
2318        assert!(model.allows_pnp_pose_prior_warm_start());
2319
2320        model.observe(&fake_failure_tracking_result(1));
2321        assert_eq!(model.mode(), AdaptiveMotionMode::Pose);
2322        assert!(!model.allows_pnp_pose_prior_warm_start());
2323
2324        model.observe(&fake_success_tracking_result(2));
2325        assert!(!model.allows_pnp_pose_prior_warm_start());
2326        model.observe(&fake_success_tracking_result(3));
2327        assert_eq!(model.mode(), AdaptiveMotionMode::Imu);
2328        assert!(model.allows_pnp_pose_prior_warm_start());
2329    }
2330
2331    #[test]
2332    fn adaptive_motion_switches_back_to_imu_after_consecutive_successes() {
2333        let mut model = AdaptiveImuPoseMotionModel::new(
2334            ImuPredictiveMotionModel::new(ImuPredictiveMotionModelConfig::default()),
2335            ConstantPoseMotionModel,
2336            AdaptiveImuPoseMotionModelConfig {
2337                failures_to_switch_to_pose: 1,
2338                successes_to_switch_to_imu: 3,
2339                ..AdaptiveImuPoseMotionModelConfig::default()
2340            },
2341        );
2342        model.observe(&fake_failure_tracking_result(1));
2343        assert_eq!(model.mode(), AdaptiveMotionMode::Pose);
2344        // Three consecutive successes flip back to IMU.
2345        model.observe(&fake_success_tracking_result(2));
2346        model.observe(&fake_success_tracking_result(3));
2347        assert_eq!(model.mode(), AdaptiveMotionMode::Pose);
2348        model.observe(&fake_success_tracking_result(4));
2349        assert_eq!(model.mode(), AdaptiveMotionMode::Imu);
2350        assert_eq!(model.switches_to_pose(), 1);
2351        assert_eq!(model.switches_to_imu(), 1);
2352    }
2353
2354    #[test]
2355    fn adaptive_motion_intermittent_failures_reset_pose_recovery_counter() {
2356        // While in Pose mode, a stray failure resets the
2357        // success-streak counter so the wrapper does not prematurely
2358        // switch back to IMU on a noisy regime.
2359        let mut model = AdaptiveImuPoseMotionModel::new(
2360            ImuPredictiveMotionModel::new(ImuPredictiveMotionModelConfig::default()),
2361            ConstantPoseMotionModel,
2362            AdaptiveImuPoseMotionModelConfig {
2363                failures_to_switch_to_pose: 1,
2364                successes_to_switch_to_imu: 3,
2365                ..AdaptiveImuPoseMotionModelConfig::default()
2366            },
2367        );
2368        model.observe(&fake_failure_tracking_result(1));
2369        assert_eq!(model.mode(), AdaptiveMotionMode::Pose);
2370        model.observe(&fake_success_tracking_result(2));
2371        model.observe(&fake_success_tracking_result(3));
2372        model.observe(&fake_failure_tracking_result(4));
2373        model.observe(&fake_success_tracking_result(5));
2374        model.observe(&fake_success_tracking_result(6));
2375        assert_eq!(model.mode(), AdaptiveMotionMode::Pose);
2376        model.observe(&fake_success_tracking_result(7));
2377        assert_eq!(model.mode(), AdaptiveMotionMode::Imu);
2378    }
2379
2380    #[test]
2381    fn adaptive_motion_reset_clears_counters_and_mode() {
2382        let mut model = AdaptiveImuPoseMotionModel::with_defaults();
2383        // Force a switch.
2384        for f in 1..=3 {
2385            model.observe(&fake_failure_tracking_result(f));
2386        }
2387        assert_eq!(model.mode(), AdaptiveMotionMode::Pose);
2388        model.reset();
2389        assert_eq!(model.mode(), AdaptiveMotionMode::Imu);
2390        assert_eq!(model.switches_to_pose(), 0);
2391        assert_eq!(model.switches_to_imu(), 0);
2392    }
2393
2394    // ---- Phase-24: IMU-velocity-refresh-on-switch-to-IMU ---------------
2395
2396    /// World-frame camera-centre pose helper for adaptive Phase-24
2397    /// tests. `from_world_to_camera` takes `translation = -R · centre`,
2398    /// so for an identity rotation we negate the supplied `centre`.
2399    fn pose_at_world_centre(centre: Vector3<f64>) -> Pose {
2400        Pose::from_world_to_camera(UnitQuaternion::identity(), -centre)
2401    }
2402
2403    #[test]
2404    fn adaptive_motion_refresh_imu_velocity_on_switch_recomputes_from_pose_diff() {
2405        // Refresh-on-switch enabled (the Phase-24 default). Drive a
2406        // failure to enter Pose mode, then two successes (each preceded
2407        // by an IMU sample so the pending-dt sum is well-defined). At
2408        // the second success we trip the switch-back threshold and the
2409        // refresh hook should rewrite IMU velocity_world to the visual
2410        // finite-difference (camera body moved +0.4m along world-x in
2411        // 0.1s ⇒ velocity_world ≈ (4, 0, 0)).
2412        let mut model = AdaptiveImuPoseMotionModel::new(
2413            ImuPredictiveMotionModel::new(ImuPredictiveMotionModelConfig::default()),
2414            ConstantPoseMotionModel,
2415            AdaptiveImuPoseMotionModelConfig {
2416                failures_to_switch_to_pose: 1,
2417                successes_to_switch_to_imu: 2,
2418                imu_velocity_refresh_policy: ImuVelocityRefreshPolicy::FiniteDifference,
2419            },
2420        );
2421        // Seed a non-zero stale velocity so we can prove the refresh
2422        // overwrote it.
2423        model
2424            .imu_mut()
2425            .set_velocity_world(Vector3::new(99.0, 0.0, 0.0));
2426        model.observe(&fake_failure_tracking_result(1));
2427        assert_eq!(model.mode(), AdaptiveMotionMode::Pose);
2428        // Push one IMU sample with dt=0.1, then a successful obs at the
2429        // origin → previous_successful_pose = origin, dt = 0.1.
2430        model
2431            .imu_mut()
2432            .push_imu_measurement(Vector3::zeros(), Vector3::zeros(), 0.1);
2433        model.observe(&fake_success_tracking_result_with_pose(
2434            2,
2435            pose_at_world_centre(Vector3::zeros()),
2436        ));
2437        // Push another IMU sample with dt=0.1, then a successful obs
2438        // displaced +0.4m along world-x. This is the second success →
2439        // mode switches back to IMU and the refresh hook fires.
2440        model
2441            .imu_mut()
2442            .push_imu_measurement(Vector3::zeros(), Vector3::zeros(), 0.1);
2443        model.observe(&fake_success_tracking_result_with_pose(
2444            3,
2445            pose_at_world_centre(Vector3::new(0.4, 0.0, 0.0)),
2446        ));
2447        assert_eq!(model.mode(), AdaptiveMotionMode::Imu);
2448        assert_eq!(model.switches_to_imu(), 1);
2449        assert_eq!(model.velocity_refreshes_on_switch_to_imu(), 1);
2450        let v = model.imu().velocity_world();
2451        assert!(
2452            (v.x - 4.0).abs() < 1.0e-9 && v.y.abs() < 1.0e-9 && v.z.abs() < 1.0e-9,
2453            "refresh hook should overwrite stale velocity_world with visual \
2454             finite-difference (0.4 m / 0.1 s = 4 m/s along x); got {v:?}",
2455        );
2456    }
2457
2458    #[test]
2459    fn adaptive_motion_refresh_disabled_leaves_imu_velocity_stale_on_switch() {
2460        // Same sequence as the previous test, but with the refresh
2461        // flag disabled. The seeded stale velocity_world must survive
2462        // the switch-back-to-IMU transition unchanged (this recovers
2463        // the Phase-23 #4 no-refresh behavior for A/B comparison).
2464        let mut model = AdaptiveImuPoseMotionModel::new(
2465            ImuPredictiveMotionModel::new(ImuPredictiveMotionModelConfig::default()),
2466            ConstantPoseMotionModel,
2467            AdaptiveImuPoseMotionModelConfig {
2468                failures_to_switch_to_pose: 1,
2469                successes_to_switch_to_imu: 2,
2470                imu_velocity_refresh_policy: ImuVelocityRefreshPolicy::None,
2471            },
2472        );
2473        model
2474            .imu_mut()
2475            .set_velocity_world(Vector3::new(99.0, 0.0, 0.0));
2476        model.observe(&fake_failure_tracking_result(1));
2477        model
2478            .imu_mut()
2479            .push_imu_measurement(Vector3::zeros(), Vector3::zeros(), 0.1);
2480        model.observe(&fake_success_tracking_result_with_pose(
2481            2,
2482            pose_at_world_centre(Vector3::zeros()),
2483        ));
2484        model
2485            .imu_mut()
2486            .push_imu_measurement(Vector3::zeros(), Vector3::zeros(), 0.1);
2487        model.observe(&fake_success_tracking_result_with_pose(
2488            3,
2489            pose_at_world_centre(Vector3::new(0.4, 0.0, 0.0)),
2490        ));
2491        assert_eq!(model.mode(), AdaptiveMotionMode::Imu);
2492        assert_eq!(model.switches_to_imu(), 1);
2493        assert_eq!(model.velocity_refreshes_on_switch_to_imu(), 0);
2494        let v = model.imu().velocity_world();
2495        assert_eq!(
2496            v,
2497            Vector3::new(99.0, 0.0, 0.0),
2498            "refresh disabled: stale velocity_world must survive the \
2499             switch-back unchanged; got {v:?}",
2500        );
2501    }
2502
2503    #[test]
2504    fn adaptive_motion_reset_clears_refresh_state_and_counters() {
2505        // reset() must clear the Phase-24 recent-pose tracking state
2506        // (previous/latest successful pose, dt between them, and the
2507        // refresh counter) on top of the existing reset semantics.
2508        let mut model = AdaptiveImuPoseMotionModel::new(
2509            ImuPredictiveMotionModel::new(ImuPredictiveMotionModelConfig::default()),
2510            ConstantPoseMotionModel,
2511            AdaptiveImuPoseMotionModelConfig {
2512                failures_to_switch_to_pose: 1,
2513                successes_to_switch_to_imu: 2,
2514                imu_velocity_refresh_policy: ImuVelocityRefreshPolicy::FiniteDifference,
2515            },
2516        );
2517        model.observe(&fake_failure_tracking_result(1));
2518        model
2519            .imu_mut()
2520            .push_imu_measurement(Vector3::zeros(), Vector3::zeros(), 0.1);
2521        model.observe(&fake_success_tracking_result_with_pose(
2522            2,
2523            pose_at_world_centre(Vector3::zeros()),
2524        ));
2525        model
2526            .imu_mut()
2527            .push_imu_measurement(Vector3::zeros(), Vector3::zeros(), 0.1);
2528        model.observe(&fake_success_tracking_result_with_pose(
2529            3,
2530            pose_at_world_centre(Vector3::new(0.4, 0.0, 0.0)),
2531        ));
2532        assert_eq!(model.velocity_refreshes_on_switch_to_imu(), 1);
2533        model.reset();
2534        assert_eq!(model.velocity_refreshes_on_switch_to_imu(), 0);
2535        // After reset, a fresh failure → switch sequence must NOT
2536        // trigger a refresh (no recent poses remembered).
2537        model.observe(&fake_failure_tracking_result(10));
2538        model
2539            .imu_mut()
2540            .push_imu_measurement(Vector3::zeros(), Vector3::zeros(), 0.1);
2541        model.observe(&fake_success_tracking_result_with_pose(
2542            11,
2543            pose_at_world_centre(Vector3::zeros()),
2544        ));
2545        model
2546            .imu_mut()
2547            .push_imu_measurement(Vector3::zeros(), Vector3::zeros(), 0.1);
2548        // This second success triggers a switch-back. At that moment
2549        // we only have ONE post-reset success on record before this
2550        // one — previous_successful_pose was set by frame 11 and
2551        // latest_successful_pose will be set by frame 12. Both
2552        // present + positive dt ⇒ refresh DOES fire. The point of
2553        // this assertion is that the per-instance counter restarts
2554        // from zero after reset(), not that refreshes stop.
2555        model.observe(&fake_success_tracking_result_with_pose(
2556            12,
2557            pose_at_world_centre(Vector3::new(0.2, 0.0, 0.0)),
2558        ));
2559        assert_eq!(model.mode(), AdaptiveMotionMode::Imu);
2560        assert_eq!(model.velocity_refreshes_on_switch_to_imu(), 1);
2561    }
2562
2563    // ---- Phase-25: ZeroReset + ThreePoseSmoother A/B variants ----------
2564
2565    #[test]
2566    fn adaptive_motion_refresh_zero_reset_zeroes_imu_velocity_on_switch() {
2567        // The ZeroReset policy must overwrite the IMU's
2568        // `velocity_world` with the zero vector at every switch-back,
2569        // independent of whether any visual poses are on record. The
2570        // counter must increment because the policy fired.
2571        let mut model = AdaptiveImuPoseMotionModel::new(
2572            ImuPredictiveMotionModel::new(ImuPredictiveMotionModelConfig::default()),
2573            ConstantPoseMotionModel,
2574            AdaptiveImuPoseMotionModelConfig {
2575                failures_to_switch_to_pose: 1,
2576                successes_to_switch_to_imu: 2,
2577                imu_velocity_refresh_policy: ImuVelocityRefreshPolicy::ZeroReset,
2578            },
2579        );
2580        model
2581            .imu_mut()
2582            .set_velocity_world(Vector3::new(99.0, 0.0, 0.0));
2583        model.observe(&fake_failure_tracking_result(1));
2584        model
2585            .imu_mut()
2586            .push_imu_measurement(Vector3::zeros(), Vector3::zeros(), 0.1);
2587        model.observe(&fake_success_tracking_result_with_pose(
2588            2,
2589            pose_at_world_centre(Vector3::zeros()),
2590        ));
2591        model
2592            .imu_mut()
2593            .push_imu_measurement(Vector3::zeros(), Vector3::zeros(), 0.1);
2594        model.observe(&fake_success_tracking_result_with_pose(
2595            3,
2596            pose_at_world_centre(Vector3::new(0.4, 0.0, 0.0)),
2597        ));
2598        assert_eq!(model.mode(), AdaptiveMotionMode::Imu);
2599        assert_eq!(model.switches_to_imu(), 1);
2600        assert_eq!(model.velocity_refreshes_on_switch_to_imu(), 1);
2601        let v = model.imu().velocity_world();
2602        assert_eq!(
2603            v,
2604            Vector3::zeros(),
2605            "ZeroReset policy must overwrite stale velocity_world with \
2606             zeros at switch; got {v:?}",
2607        );
2608    }
2609
2610    #[test]
2611    fn adaptive_motion_refresh_three_pose_smoother_averages_two_finite_diffs() {
2612        // Three successive successful observations along world-x at
2613        //   t0: pose @ x=0          dt = irrelevant (first success)
2614        //   t1: pose @ x=0.4   dt1 = 0.1   ⇒ v_prev   = 4 m/s
2615        //   t2: pose @ x=1.2   dt2 = 0.1   ⇒ v_latest = 8 m/s
2616        // ThreePoseSmoother averages them ⇒ writes (4+8)/2 = 6 m/s.
2617        let mut model = AdaptiveImuPoseMotionModel::new(
2618            ImuPredictiveMotionModel::new(ImuPredictiveMotionModelConfig::default()),
2619            ConstantPoseMotionModel,
2620            AdaptiveImuPoseMotionModelConfig {
2621                failures_to_switch_to_pose: 1,
2622                successes_to_switch_to_imu: 3,
2623                imu_velocity_refresh_policy: ImuVelocityRefreshPolicy::ThreePoseSmoother,
2624            },
2625        );
2626        model
2627            .imu_mut()
2628            .set_velocity_world(Vector3::new(99.0, 0.0, 0.0));
2629        model.observe(&fake_failure_tracking_result(1));
2630        assert_eq!(model.mode(), AdaptiveMotionMode::Pose);
2631        // 1st success: oldest=None, prev=None, latest=pose@0
2632        model
2633            .imu_mut()
2634            .push_imu_measurement(Vector3::zeros(), Vector3::zeros(), 0.1);
2635        model.observe(&fake_success_tracking_result_with_pose(
2636            2,
2637            pose_at_world_centre(Vector3::zeros()),
2638        ));
2639        // 2nd success: oldest=None, prev=pose@0, latest=pose@0.4
2640        // dt_latest=0.1, dt_prev=0.1 (carried from the prior tick — but
2641        // there was no previous pose so the smoother's oldest branch
2642        // does not trigger). Counter still 0 (no switch yet).
2643        model
2644            .imu_mut()
2645            .push_imu_measurement(Vector3::zeros(), Vector3::zeros(), 0.1);
2646        model.observe(&fake_success_tracking_result_with_pose(
2647            3,
2648            pose_at_world_centre(Vector3::new(0.4, 0.0, 0.0)),
2649        ));
2650        assert_eq!(model.mode(), AdaptiveMotionMode::Pose);
2651        // 3rd success: oldest=pose@0, prev=pose@0.4, latest=pose@1.2.
2652        // dt_prev=0.1 (was dt_latest one shift ago), dt_latest=0.1.
2653        // consecutive_successes reaches threshold → switch + smoother
2654        // fires with both 3-pose entries available.
2655        model
2656            .imu_mut()
2657            .push_imu_measurement(Vector3::zeros(), Vector3::zeros(), 0.1);
2658        model.observe(&fake_success_tracking_result_with_pose(
2659            4,
2660            pose_at_world_centre(Vector3::new(1.2, 0.0, 0.0)),
2661        ));
2662        assert_eq!(model.mode(), AdaptiveMotionMode::Imu);
2663        assert_eq!(model.switches_to_imu(), 1);
2664        assert_eq!(model.velocity_refreshes_on_switch_to_imu(), 1);
2665        let v = model.imu().velocity_world();
2666        assert!(
2667            (v.x - 6.0).abs() < 1.0e-9 && v.y.abs() < 1.0e-9 && v.z.abs() < 1.0e-9,
2668            "ThreePoseSmoother should average two finite-diffs \
2669             (4 m/s and 8 m/s along x ⇒ 6 m/s); got {v:?}",
2670        );
2671    }
2672
2673    #[test]
2674    fn adaptive_motion_refresh_three_pose_smoother_falls_back_when_only_two_poses() {
2675        // Same setup as the FiniteDifference test (only TWO successful
2676        // poses before the switch), but with the policy set to
2677        // ThreePoseSmoother. The fallback must compute a single
2678        // finite-difference (4 m/s along x) rather than no-op.
2679        let mut model = AdaptiveImuPoseMotionModel::new(
2680            ImuPredictiveMotionModel::new(ImuPredictiveMotionModelConfig::default()),
2681            ConstantPoseMotionModel,
2682            AdaptiveImuPoseMotionModelConfig {
2683                failures_to_switch_to_pose: 1,
2684                successes_to_switch_to_imu: 2,
2685                imu_velocity_refresh_policy: ImuVelocityRefreshPolicy::ThreePoseSmoother,
2686            },
2687        );
2688        model
2689            .imu_mut()
2690            .set_velocity_world(Vector3::new(99.0, 0.0, 0.0));
2691        model.observe(&fake_failure_tracking_result(1));
2692        model
2693            .imu_mut()
2694            .push_imu_measurement(Vector3::zeros(), Vector3::zeros(), 0.1);
2695        model.observe(&fake_success_tracking_result_with_pose(
2696            2,
2697            pose_at_world_centre(Vector3::zeros()),
2698        ));
2699        model
2700            .imu_mut()
2701            .push_imu_measurement(Vector3::zeros(), Vector3::zeros(), 0.1);
2702        model.observe(&fake_success_tracking_result_with_pose(
2703            3,
2704            pose_at_world_centre(Vector3::new(0.4, 0.0, 0.0)),
2705        ));
2706        assert_eq!(model.mode(), AdaptiveMotionMode::Imu);
2707        assert_eq!(model.velocity_refreshes_on_switch_to_imu(), 1);
2708        let v = model.imu().velocity_world();
2709        assert!(
2710            (v.x - 4.0).abs() < 1.0e-9 && v.y.abs() < 1.0e-9 && v.z.abs() < 1.0e-9,
2711            "ThreePoseSmoother fallback (only 2 poses) should match \
2712             single finite-difference; got {v:?}",
2713        );
2714    }
2715}