1use std::collections::BTreeMap;
19
20use nalgebra::{DMatrix, DVector, SMatrix};
21use visloc_core::geometry::{Sim3, Sim3Tangent};
22
23use crate::{
24 block_cholesky::{solve_spd_block_cached, BlockSymbolic},
25 solve_normal_equations, PoseGraphError,
26};
27
28const DOF: usize = 7;
30
31pub type Sim3Information = SMatrix<f64, 7, 7>;
33
34#[derive(Debug, Clone, PartialEq)]
41pub struct Sim3Edge {
42 pub from: u64,
43 pub to: u64,
44 pub measurement: Sim3,
45 pub weight: f64,
46 pub information: Option<Sim3Information>,
47}
48
49#[derive(Debug, Clone, PartialEq)]
51pub struct Sim3PoseGraphIterationStats {
52 pub iteration: usize,
53 pub cost_before: f64,
54 pub cost_after: f64,
55 pub max_step_norm: f64,
56 pub lambda: f64,
58 pub step_accepted: bool,
59}
60
61#[derive(Debug, Clone, PartialEq)]
63pub struct Sim3PoseGraphResult {
64 pub anchor_id: u64,
65 pub edge_count: usize,
66 pub variable_count: usize,
67 pub used_sparse_solver: bool,
69 pub initial_cost: f64,
70 pub final_cost: f64,
71 pub iterations: Vec<Sim3PoseGraphIterationStats>,
72 pub converged: bool,
73}
74
75#[derive(Debug, Clone, PartialEq)]
77pub struct Sim3PoseGraphConfig {
78 pub max_iterations: usize,
79 pub step_tolerance: f64,
81 pub cost_tolerance: f64,
83 pub initial_lambda: Option<f64>,
86 pub lambda_increase_factor: f64,
87 pub lambda_decrease_factor: f64,
88 pub max_lambda: f64,
89 pub min_lambda: f64,
90 pub sparse_solve_min_variables: usize,
93}
94
95impl Default for Sim3PoseGraphConfig {
96 fn default() -> Self {
97 Self {
98 max_iterations: 50,
99 step_tolerance: 1e-8,
100 cost_tolerance: 1e-12,
101 initial_lambda: Some(1e-3),
102 lambda_increase_factor: 10.0,
103 lambda_decrease_factor: 0.1,
104 max_lambda: 1e12,
105 min_lambda: 1e-9,
106 sparse_solve_min_variables: 32,
107 }
108 }
109}
110
111#[derive(Debug, Clone, Default, PartialEq)]
113pub struct Sim3PoseGraph {
114 pub poses: BTreeMap<u64, Sim3>,
117 pub edges: Vec<Sim3Edge>,
118 pub anchor: Option<u64>,
120}
121
122impl Sim3PoseGraph {
123 pub fn new() -> Self {
124 Self::default()
125 }
126
127 pub fn add_pose(&mut self, keyframe_id: u64, pose: Sim3) {
129 self.poses.insert(keyframe_id, pose);
130 }
131
132 pub const fn anchor(&mut self, keyframe_id: u64) {
134 self.anchor = Some(keyframe_id);
135 }
136
137 pub fn add_edge(&mut self, from: u64, to: u64, measurement: Sim3, weight: f64) {
139 self.edges.push(Sim3Edge {
140 from,
141 to,
142 measurement,
143 weight,
144 information: None,
145 });
146 }
147
148 pub fn add_edge_with_information(
150 &mut self,
151 from: u64,
152 to: u64,
153 measurement: Sim3,
154 information: Sim3Information,
155 ) {
156 self.edges.push(Sim3Edge {
157 from,
158 to,
159 measurement,
160 weight: 1.0,
161 information: Some(information),
162 });
163 }
164
165 pub fn cost(&self) -> f64 {
167 self.edges
168 .iter()
169 .filter_map(|edge| {
170 let pose_from = self.poses.get(&edge.from)?;
171 let pose_to = self.poses.get(&edge.to)?;
172 let r = edge_residual(&edge.measurement, pose_from, pose_to);
173 Some(match &edge.information {
174 Some(omega) => (r.transpose() * omega * r)[(0, 0)],
175 None => edge.weight * r.norm_squared(),
176 })
177 })
178 .sum()
179 }
180
181 pub fn optimize(
185 &mut self,
186 config: &Sim3PoseGraphConfig,
187 ) -> Result<Sim3PoseGraphResult, PoseGraphError> {
188 let anchor_id = self.anchor.ok_or(PoseGraphError::NoAnchor)?;
189 if !self.poses.contains_key(&anchor_id) {
190 return Err(PoseGraphError::MissingNode(anchor_id));
191 }
192 if self.edges.is_empty() {
193 return Err(PoseGraphError::NoEdges);
194 }
195 for edge in &self.edges {
196 if !self.poses.contains_key(&edge.from) {
197 return Err(PoseGraphError::MissingNode(edge.from));
198 }
199 if !self.poses.contains_key(&edge.to) {
200 return Err(PoseGraphError::MissingNode(edge.to));
201 }
202 }
203
204 let mut node_index: BTreeMap<u64, usize> = BTreeMap::new();
205 for &id in self.poses.keys() {
206 if id == anchor_id {
207 continue;
208 }
209 let next = node_index.len();
210 node_index.insert(id, next);
211 }
212 let variable_count = node_index.len();
213 if variable_count == 0 {
214 return Err(PoseGraphError::NoVariables);
215 }
216
217 let dim = variable_count * DOF;
218 let used_sparse_solver = variable_count >= config.sparse_solve_min_variables;
219 let initial_cost = self.cost();
220 let mut current_cost = initial_cost;
221 let mut lambda = config.initial_lambda.unwrap_or(0.0);
222 let mut iterations = Vec::with_capacity(config.max_iterations);
223 let mut converged = false;
224 let mut sparse_symbolic: Option<BlockSymbolic> = None;
225
226 for iteration in 0..config.max_iterations {
227 let mut h = (!used_sparse_solver).then(|| DMatrix::<f64>::zeros(dim, dim));
228 let mut h_triplets = used_sparse_solver.then(Vec::new);
229 let mut g = DVector::<f64>::zeros(dim);
230
231 for edge in &self.edges {
232 let pose_from = &self.poses[&edge.from];
233 let pose_to = &self.poses[&edge.to];
234 let r = edge_residual(&edge.measurement, pose_from, pose_to);
235 let omega = match &edge.information {
236 Some(omega) => *omega,
237 None => Sim3Information::identity() * edge.weight,
238 };
239
240 let i_from = node_index.get(&edge.from).copied();
241 let i_to = node_index.get(&edge.to).copied();
242
243 let j_from =
246 i_from.map(|_| numerical_jacobian(&edge.measurement, pose_from, pose_to, true));
247 let j_to =
248 i_to.map(|_| numerical_jacobian(&edge.measurement, pose_from, pose_to, false));
249
250 if let (Some(i), Some(jf)) = (i_from, &j_from) {
251 let ot = jf.transpose() * omega;
252 accumulate_normal_block(&mut h, &mut h_triplets, i * DOF, i * DOF, &(ot * jf));
253 accumulate_segment(&mut g, i * DOF, &(ot * r));
254 }
255 if let (Some(j), Some(jt)) = (i_to, &j_to) {
256 let ot = jt.transpose() * omega;
257 accumulate_normal_block(&mut h, &mut h_triplets, j * DOF, j * DOF, &(ot * jt));
258 accumulate_segment(&mut g, j * DOF, &(ot * r));
259 }
260 if let (Some(i), Some(jf), Some(j), Some(jt)) = (i_from, &j_from, i_to, &j_to) {
261 let cross = jf.transpose() * omega * jt;
262 accumulate_normal_block(&mut h, &mut h_triplets, i * DOF, j * DOF, &cross);
263 accumulate_normal_block(
264 &mut h,
265 &mut h_triplets,
266 j * DOF,
267 i * DOF,
268 &cross.transpose(),
269 );
270 }
271 }
272
273 let rhs_vector = -&g;
275 let delta = if let Some(triplets) = &h_triplets {
276 let rhs = DMatrix::from_column_slice(dim, 1, rhs_vector.as_slice());
277 let solution =
278 solve_spd_block_cached(&mut sparse_symbolic, triplets, dim, DOF, &rhs, lambda)
279 .map_err(|_| PoseGraphError::SingularSystem)?;
280 solution.column(0).into_owned()
281 } else {
282 let mut damped = h.expect("dense Hessian exists on the dense solver path");
283 for d in 0..dim {
284 damped[(d, d)] += lambda;
285 }
286 solve_normal_equations(&damped, &rhs_vector)?
287 };
288
289 let cost_before = current_cost;
290 let saved_poses = config.initial_lambda.is_some().then(|| self.poses.clone());
291
292 let mut max_step_norm: f64 = 0.0;
293 for (&id, &index) in &node_index {
294 let mut xi = Sim3Tangent::zeros();
295 for k in 0..DOF {
296 xi[k] = delta[index * DOF + k];
297 }
298 max_step_norm = max_step_norm.max(xi.norm());
299 let pose = self
300 .poses
301 .get_mut(&id)
302 .ok_or(PoseGraphError::MissingNode(id))?;
303 *pose = pose.compose(&Sim3::exp(&xi));
304 }
305
306 let cost_after = self.cost();
307 let step_accepted = config.initial_lambda.is_none() || cost_after < cost_before;
308
309 if !step_accepted {
310 if let Some(saved) = saved_poses {
311 self.poses = saved;
312 }
313 lambda = (lambda * config.lambda_increase_factor).min(config.max_lambda);
314 iterations.push(Sim3PoseGraphIterationStats {
315 iteration,
316 cost_before,
317 cost_after,
318 max_step_norm,
319 lambda,
320 step_accepted: false,
321 });
322 if lambda >= config.max_lambda {
323 break;
324 }
325 continue;
326 }
327
328 iterations.push(Sim3PoseGraphIterationStats {
329 iteration,
330 cost_before,
331 cost_after,
332 max_step_norm,
333 lambda,
334 step_accepted: true,
335 });
336 current_cost = cost_after;
337 if config.initial_lambda.is_some() {
338 lambda = (lambda * config.lambda_decrease_factor).max(config.min_lambda);
339 }
340
341 if max_step_norm < config.step_tolerance
342 || (cost_before - cost_after).abs() < config.cost_tolerance
343 {
344 converged = true;
345 break;
346 }
347 }
348
349 Ok(Sim3PoseGraphResult {
350 anchor_id,
351 edge_count: self.edges.len(),
352 variable_count,
353 used_sparse_solver,
354 initial_cost,
355 final_cost: current_cost,
356 iterations,
357 converged,
358 })
359 }
360}
361
362fn edge_residual(measurement: &Sim3, pose_from: &Sim3, pose_to: &Sim3) -> Sim3Tangent {
365 let predicted = pose_to.compose(&pose_from.inverse());
366 measurement.inverse().compose(&predicted).log()
367}
368
369fn numerical_jacobian(
372 measurement: &Sim3,
373 pose_from: &Sim3,
374 pose_to: &Sim3,
375 perturb_from: bool,
376) -> SMatrix<f64, 7, 7> {
377 const EPS: f64 = 1e-6;
378 let mut jacobian = SMatrix::<f64, 7, 7>::zeros();
379 for k in 0..DOF {
380 let mut plus = Sim3Tangent::zeros();
381 plus[k] = EPS;
382 let mut minus = Sim3Tangent::zeros();
383 minus[k] = -EPS;
384 let (rp, rm) = if perturb_from {
385 (
386 edge_residual(measurement, &pose_from.compose(&Sim3::exp(&plus)), pose_to),
387 edge_residual(measurement, &pose_from.compose(&Sim3::exp(&minus)), pose_to),
388 )
389 } else {
390 (
391 edge_residual(measurement, pose_from, &pose_to.compose(&Sim3::exp(&plus))),
392 edge_residual(measurement, pose_from, &pose_to.compose(&Sim3::exp(&minus))),
393 )
394 };
395 let column = (rp - rm) / (2.0 * EPS);
396 jacobian.set_column(k, &column);
397 }
398 jacobian
399}
400
401fn accumulate_block(h: &mut DMatrix<f64>, row: usize, col: usize, block: &SMatrix<f64, 7, 7>) {
402 for r in 0..DOF {
403 for c in 0..DOF {
404 h[(row + r, col + c)] += block[(r, c)];
405 }
406 }
407}
408
409fn accumulate_normal_block(
414 dense: &mut Option<DMatrix<f64>>,
415 sparse: &mut Option<Vec<(usize, usize, f64)>>,
416 row: usize,
417 col: usize,
418 block: &SMatrix<f64, 7, 7>,
419) {
420 if let Some(h) = dense {
421 accumulate_block(h, row, col, block);
422 return;
423 }
424 let triplets = sparse
425 .as_mut()
426 .expect("sparse triplets exist on the sparse solver path");
427 for r in 0..DOF {
428 for c in 0..DOF {
429 triplets.push((row + r, col + c, block[(r, c)]));
430 }
431 }
432}
433
434fn accumulate_segment(g: &mut DVector<f64>, offset: usize, segment: &Sim3Tangent) {
435 for r in 0..DOF {
436 g[offset + r] += segment[r];
437 }
438}
439
440#[cfg(test)]
441mod tests {
442 use super::*;
443 use nalgebra::{UnitQuaternion, Vector3};
444
445 fn ground_truth(node_count: u64) -> Vec<(u64, Sim3)> {
447 (0..node_count)
448 .map(|i| {
449 let angle = i as f64 / node_count as f64 * std::f64::consts::TAU;
450 let pose = Sim3::new(
451 UnitQuaternion::from_euler_angles(0.0, 0.0, angle),
452 Vector3::new(5.0 * angle.cos(), 5.0 * angle.sin(), 0.3 * i as f64),
453 1.0,
454 );
455 (i, pose)
456 })
457 .collect()
458 }
459
460 fn graph_with_true_measurements(truth: &[(u64, Sim3)]) -> Sim3PoseGraph {
463 let mut graph = Sim3PoseGraph::new();
464 for (id, pose) in truth {
465 graph.add_pose(*id, pose.clone());
466 }
467 let relative = |from: usize, to: usize| truth[to].1.compose(&truth[from].1.inverse());
468 for w in 1..truth.len() {
469 graph.add_edge(truth[w - 1].0, truth[w].0, relative(w - 1, w), 1.0);
470 }
471 let last = truth.len() - 1;
472 graph.add_edge(truth[last].0, truth[0].0, relative(last, 0), 10.0);
473 graph
474 }
475
476 #[test]
477 fn ground_truth_is_a_fixed_point() {
478 let truth = ground_truth(8);
479 let mut graph = graph_with_true_measurements(&truth);
480 graph.anchor(0);
481 let result = graph.optimize(&Sim3PoseGraphConfig::default()).unwrap();
482 assert!(
483 result.initial_cost < 1e-18,
484 "init cost {}",
485 result.initial_cost
486 );
487 for (id, pose) in &truth {
488 assert!((graph.poses[id].scale - pose.scale).abs() < 1e-9);
489 assert!((graph.poses[id].translation - pose.translation).norm() < 1e-9);
490 }
491 }
492
493 #[test]
494 fn corrects_accumulated_scale_drift() {
495 let truth = ground_truth(8);
496 let mut graph = graph_with_true_measurements(&truth);
497 graph.anchor(0);
498
499 for (id, pose) in &truth {
503 if *id == 0 {
504 continue;
505 }
506 let i = *id as f64;
507 let mut drift = Sim3Tangent::zeros();
508 drift[0] = 0.05 * i; drift[5] = 0.02 * i; drift[6] = 0.06 * i; graph.add_pose(*id, pose.compose(&Sim3::exp(&drift)));
512 }
513
514 let drifted_cost = graph.cost();
515 let worst_scale_error = truth
516 .iter()
517 .map(|(id, _)| (graph.poses[id].scale - 1.0).abs())
518 .fold(0.0_f64, f64::max);
519 assert!(
520 worst_scale_error > 0.4,
521 "expected large initial scale drift"
522 );
523
524 let result = graph.optimize(&Sim3PoseGraphConfig::default()).unwrap();
525
526 assert!(
527 result.final_cost < drifted_cost * 1e-6,
528 "final cost {}",
529 result.final_cost
530 );
531 assert!(
532 result.converged,
533 "expected convergence: {:?}",
534 result.iterations.len()
535 );
536 for (id, pose) in &truth {
539 assert!(
540 (graph.poses[id].scale - pose.scale).abs() < 1e-6,
541 "node {id} scale {} != 1",
542 graph.poses[id].scale
543 );
544 assert!(
545 (graph.poses[id].translation - pose.translation).norm() < 1e-5,
546 "node {id} translation off by {}",
547 (graph.poses[id].translation - pose.translation).norm()
548 );
549 }
550 }
551
552 #[test]
553 fn sparse_solver_matches_dense_reference() {
554 let truth = ground_truth(12);
555 let mut initial = graph_with_true_measurements(&truth);
556 initial.anchor(0);
557 for (id, pose) in &truth {
558 if *id == 0 {
559 continue;
560 }
561 let i = *id as f64;
562 let mut drift = Sim3Tangent::zeros();
563 drift[0] = 0.025 * i;
564 drift[4] = -0.006 * i;
565 drift[6] = 0.025 * i;
566 initial.add_pose(*id, pose.compose(&Sim3::exp(&drift)));
567 }
568
569 let mut dense = initial.clone();
570 let mut sparse = initial;
571 let dense_result = dense
572 .optimize(&Sim3PoseGraphConfig {
573 sparse_solve_min_variables: usize::MAX,
574 ..Sim3PoseGraphConfig::default()
575 })
576 .unwrap();
577 let sparse_result = sparse
578 .optimize(&Sim3PoseGraphConfig {
579 sparse_solve_min_variables: 1,
580 ..Sim3PoseGraphConfig::default()
581 })
582 .unwrap();
583
584 assert!(!dense_result.used_sparse_solver);
585 assert!(sparse_result.used_sparse_solver);
586 assert!(
587 (dense_result.final_cost - sparse_result.final_cost).abs() < 1e-12,
588 "dense cost {}, sparse cost {}",
589 dense_result.final_cost,
590 sparse_result.final_cost
591 );
592 for id in dense.poses.keys() {
593 let disagreement = sparse.poses[id]
594 .compose(&dense.poses[id].inverse())
595 .log()
596 .norm();
597 assert!(
598 disagreement < 1e-8,
599 "node {id}: dense/sparse disagreement {disagreement}"
600 );
601 }
602 }
603
604 #[test]
608 #[ignore]
609 fn bench_sparse_growth_to_euroc_length() {
610 use std::time::Instant;
611
612 let config = Sim3PoseGraphConfig {
613 max_iterations: 1,
614 sparse_solve_min_variables: 1,
615 ..Sim3PoseGraphConfig::default()
616 };
617 let mut samples = Vec::new();
618 for node_count in [300_u64, 900, 2700] {
619 let truth = ground_truth(node_count);
620 let mut graph = graph_with_true_measurements(&truth);
621 graph.anchor(0);
622 let started = Instant::now();
623 let result = graph.optimize(&config).unwrap();
624 let elapsed = started.elapsed();
625 assert!(result.used_sparse_solver);
626 samples.push((node_count, elapsed.as_secs_f64(), result.final_cost));
627 println!(
628 "Sim3 sparse: nodes={node_count}, edges={}, elapsed={:.3}s, final_cost={:.3e}",
629 result.edge_count,
630 elapsed.as_secs_f64(),
631 result.final_cost
632 );
633 }
634 for window in samples.windows(2) {
635 let node_growth = window[1].0 as f64 / window[0].0 as f64;
636 let time_growth = window[1].1 / window[0].1;
637 println!(
638 "growth {}->{}: nodes={node_growth:.2}x, time={time_growth:.2}x",
639 window[0].0, window[1].0
640 );
641 }
642 }
643
644 #[test]
645 fn errors_on_degenerate_graphs() {
646 let mut empty = Sim3PoseGraph::new();
647 empty.add_pose(0, Sim3::identity());
648 assert_eq!(
649 empty.optimize(&Sim3PoseGraphConfig::default()),
650 Err(PoseGraphError::NoAnchor)
651 );
652 empty.anchor(0);
653 assert_eq!(
654 empty.optimize(&Sim3PoseGraphConfig::default()),
655 Err(PoseGraphError::NoEdges)
656 );
657
658 let mut only_anchor = Sim3PoseGraph::new();
659 only_anchor.add_pose(0, Sim3::identity());
660 only_anchor.anchor(0);
661 only_anchor.add_edge(0, 0, Sim3::identity(), 1.0);
662 assert_eq!(
663 only_anchor.optimize(&Sim3PoseGraphConfig::default()),
664 Err(PoseGraphError::NoVariables)
665 );
666
667 let mut missing = Sim3PoseGraph::new();
668 missing.add_pose(0, Sim3::identity());
669 missing.anchor(0);
670 missing.add_edge(0, 9, Sim3::identity(), 1.0);
671 assert_eq!(
672 missing.optimize(&Sim3PoseGraphConfig::default()),
673 Err(PoseGraphError::MissingNode(9))
674 );
675 }
676}