visloc_slam/pose_graph.rs
1//! Sparse pose-graph optimizer: SE(3) edges, robust kernels (incl. GNC),
2//! chordal initialization, and the dense/sparse normal-equation solvers.
3
4use super::*;
5
6/// Kind of an edge inside a [`PoseGraph`].
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8pub enum PoseGraphEdgeKind {
9 /// Sequential odometry edge between consecutive keyframes.
10 Sequential,
11 /// Loop-closure edge backed by a verified [`LoopClosureConstraint`].
12 LoopClosure,
13}
14
15/// Edge in a sparse [`PoseGraph`]. Encodes a measured `previous_to_current`
16/// SE3 between two keyframes plus a positive weight used by translation-only
17/// least squares.
18///
19/// `information` optionally carries a full 6×6 information matrix `Ω`, i.e. the
20/// inverse measurement covariance, ordered `[ρ; ω]` (translation block first,
21/// then rotation) to match [`SE3::log`] and the `.g2o` `EDGE_SE3:QUAT`
22/// convention. When `Some`, the SE(3) solver minimizes the anisotropic
23/// Mahalanobis cost `rᵀ Ω r` for this edge and the scalar `weight` is ignored;
24/// when `None`, the edge falls back to the isotropic `weight · ‖r‖²` behavior.
25/// This lets the graph ingest external constraints (e.g. `.g2o`
26/// `EDGE_SE3:QUAT`) whose blocks couple rotation and translation, without
27/// changing the meaning of the internally-built sequential / loop-closure
28/// edges.
29#[derive(Debug, Clone, PartialEq)]
30pub struct PoseGraphEdge {
31 pub from: u64,
32 pub to: u64,
33 pub measurement: SE3,
34 pub kind: PoseGraphEdgeKind,
35 pub weight: f64,
36 pub information: Option<Matrix6<f64>>,
37}
38
39/// A dense Gaussian *prior* over a set of poses — the factor a fixed-lag /
40/// sliding-window smoother re-adds when it marginalizes states out of the graph
41/// (see [`crate::marginalization`] and [`PoseGraph::marginalize_pose`]).
42///
43/// It penalizes the quadratic `½ eᵀ Ω e + bᵀ e` where `e` stacks each pose's
44/// right-tangent error from its linearization point, `eᵢ = log(T₀ᵢ⁻¹ ∘ Tᵢ)` (so
45/// `∂eᵢ/∂δᵢ = I` under the solver's `T ← T ∘ exp(δ)` update). The prior therefore
46/// contributes `Ω` to `H` and `Ω·e + b` to `g` with an identity Jacobian. `Ω`
47/// (`information`) is the `6k × 6k` curvature and `b` (`gradient`) the linear
48/// term, both in the `[ρ; ω]` SE(3)-tangent basis the edges use; `linearization[i]`
49/// is `T₀ᵢ`, pose `ids[i]`'s estimate when the prior was formed. The linear term
50/// `b` is the gradient of the marginalized factors at `T₀` and is what keeps the
51/// linearization point a stationary point of the reduced problem — a pure
52/// quadratic (`b = 0`) would wrongly assert the prior's mean is `T₀`. A prior id
53/// that is the gauge-fixed anchor (or absent) contributes a zero tangent error
54/// and no variable block, dropping out cleanly.
55#[derive(Debug, Clone, PartialEq)]
56pub struct GaussianPrior {
57 /// The poses this prior constrains, indexing `information`'s `6×6` blocks,
58 /// `gradient`'s `6`-segments, and `linearization` in the same order.
59 pub ids: Vec<u64>,
60 /// The `6k × 6k` information (inverse-covariance / curvature) matrix `Ω` over
61 /// the stacked tangent error, `k = ids.len()`.
62 pub information: DMatrix<f64>,
63 /// The `6k` linear term `b` (the marginalized factors' gradient at `T₀`).
64 /// Zero for a pure quadratic prior pinned at its linearization point.
65 pub gradient: DVector<f64>,
66 /// Linearization point `T₀ᵢ` (world-to-camera) per id, the estimate at which
67 /// the prior was formed; the residual is measured relative to it.
68 pub linearization: Vec<SE3>,
69}
70
71/// Single Gauss-Newton step diagnostics.
72#[derive(Debug, Clone, PartialEq)]
73pub struct PoseGraphOptimizationStep {
74 pub anchor_id: u64,
75 pub edge_count: usize,
76 pub variable_count: usize,
77 pub cost_before: f64,
78 pub cost_after: f64,
79 pub mean_translation_correction: f64,
80 pub max_translation_correction: f64,
81}
82
83/// Robust kernel applied to each pose-graph edge's residual norm-squared.
84/// Down-weights edges whose squared residual exceeds the kernel threshold so
85/// outlier loop closures cannot dominate the least-squares solve.
86#[derive(Debug, Clone, Copy, PartialEq, Default)]
87pub enum RobustKernel {
88 /// Standard squared-error cost (`ρ(s) = s`).
89 #[default]
90 None,
91 /// Huber kernel: quadratic for `s ≤ δ²`, linear in `√s` beyond.
92 /// `delta` is the threshold on residual norm where the kernel switches
93 /// from quadratic to linear.
94 Huber { delta: f64 },
95 /// Cauchy / Lorentzian kernel: `ρ(s) = c² · log(1 + s / c²)`.
96 /// `c` is the soft-saturation scale on residual norm.
97 Cauchy { c: f64 },
98}
99
100impl RobustKernel {
101 /// Applied cost `ρ(s)` for `s = ||r||²`.
102 pub fn cost(&self, s: f64) -> f64 {
103 match *self {
104 RobustKernel::None => s,
105 RobustKernel::Huber { delta } => {
106 let delta_sq = delta * delta;
107 if s <= delta_sq {
108 s
109 } else {
110 2.0 * delta * s.sqrt() - delta_sq
111 }
112 }
113 RobustKernel::Cauchy { c } => {
114 let c_sq = c * c;
115 c_sq * (1.0 + s / c_sq).ln()
116 }
117 }
118 }
119
120 /// Influence weight `ρ'(s)` used as a multiplier on each edge's normal-equation
121 /// contribution (a.k.a. IRLS weight).
122 pub fn weight(&self, s: f64) -> f64 {
123 match *self {
124 RobustKernel::None => 1.0,
125 RobustKernel::Huber { delta } => {
126 let delta_sq = delta * delta;
127 if s <= delta_sq {
128 1.0
129 } else {
130 delta / s.sqrt()
131 }
132 }
133 RobustKernel::Cauchy { c } => {
134 let c_sq = c * c;
135 1.0 / (1.0 + s / c_sq)
136 }
137 }
138 }
139}
140
141/// Linear solver backend used by pose-graph optimizers when the normal
142/// equations `(H + λI) δ = -g` (or the translation-only analogue) are solved.
143///
144/// `Dense` materializes the full SPD matrix as a [`DMatrix`] and uses
145/// nalgebra's dense Cholesky (LU fallback). `Sparse` assembles the same
146/// system from edge triplets and solves it with the block Cholesky (the
147/// `block_cholesky` module) in a fill-reducing order. The two paths produce
148/// numerically equivalent solutions on connected, well-conditioned graphs but
149/// the sparse path scales to thousands of keyframes where the dense path
150/// becomes infeasible.
151#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
152pub enum LinearSolver {
153 /// Dense Cholesky / LU on a [`DMatrix`].
154 #[default]
155 Dense,
156 /// Sparse block Cholesky on a triplet-assembled system.
157 Sparse,
158}
159
160/// How the Levenberg-Marquardt damping `λ` enters the normal matrix `H`.
161#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
162pub enum DampingMode {
163 /// `H + λI` — add `λ` uniformly to every diagonal entry. Simple, but
164 /// scale-blind: the rotation and translation blocks of `H` differ by orders
165 /// of magnitude, so a single `λ` over-damps the well-conditioned directions
166 /// while under-damping the ill-conditioned ones. As `λ` grows on a hard graph
167 /// the step degenerates and the solve stalls at a poor optimum (observed on
168 /// sphere2500 / cubicle vs GTSAM).
169 #[default]
170 Identity,
171 /// `H + λ·diag(H)` — Marquardt's scale-invariant damping: each variable is
172 /// damped in proportion to its own curvature, so the trust region is an
173 /// ellipsoid matched to the local geometry rather than a sphere. This is the
174 /// default in mature LM solvers (GTSAM, Ceres) and reaches a markedly lower
175 /// optimum than `Identity` on graphs with mixed rotation/translation
176 /// curvature.
177 Diagonal,
178}
179
180/// Configuration for [`PoseGraph::optimize_se3_iterative`].
181#[derive(Debug, Clone, PartialEq)]
182pub struct PoseGraphSe3Config {
183 /// Hard cap on iterations (including rejected LM steps).
184 pub max_iterations: usize,
185 /// Convergence threshold on the largest per-node 6-vector update of the
186 /// most recent accepted step.
187 pub step_tolerance: f64,
188 /// Convergence threshold on the absolute cost change between two
189 /// successive accepted steps.
190 pub cost_tolerance: f64,
191 /// Robust kernel applied to each edge's squared residual norm.
192 pub robust_kernel: RobustKernel,
193 /// Initial Levenberg-Marquardt damping `λ`. `None` runs pure
194 /// Gauss-Newton (every step is accepted unconditionally). `Some(λ₀)`
195 /// enables LM: solve `(H + λI) δ = -g`, accept if cost decreases (and
196 /// scale `λ` down by `lambda_decrease_factor`), otherwise reject and
197 /// scale `λ` up by `lambda_increase_factor`.
198 pub initial_lambda: Option<f64>,
199 /// Multiplier applied to `λ` after a rejected LM step.
200 pub lambda_increase_factor: f64,
201 /// Multiplier applied to `λ` after an accepted LM step.
202 pub lambda_decrease_factor: f64,
203 /// How `λ` enters `H`. Defaults to [`DampingMode::Identity`] (`H + λI`, leaves
204 /// every solve bit-identical). Switch to [`DampingMode::Diagonal`]
205 /// (`H + λ·diag(H)`) for graphs with mixed rotation/translation curvature.
206 pub damping: DampingMode,
207 /// Upper bound on `λ`. When a step is rejected and `λ * factor > max_lambda`,
208 /// the optimizer gives up and returns `converged: false`.
209 pub max_lambda: f64,
210 /// Lower bound on `λ`. Decreases stop here so `λ` cannot collapse to zero.
211 pub min_lambda: f64,
212 /// Linear-solver backend. Defaults to dense Cholesky for parity with the
213 /// pre-sparse solver. Switch to [`LinearSolver::Sparse`] when the graph
214 /// has more than a few hundred nodes so the optimizer scales linearly in
215 /// non-zero edges instead of cubically in node count.
216 pub linear_solver: LinearSolver,
217 /// Seed the solve with a chordal rotation initialization
218 /// ([`PoseGraph::initialize_rotations_chordal`]) before the first
219 /// Gauss-Newton step. Defaults to `true`: it is strictly beneficial —
220 /// the rotation optimum is a fixed point of the relaxation, so on an
221 /// already-consistent graph it leaves the estimate essentially unchanged
222 /// (a cheap extra factorization), while on a hard, odometry-initialized 3D
223 /// graph it rescues the solve from a poor basin. The seeding is best-effort:
224 /// if its relaxed system is singular it is silently skipped and the solve
225 /// proceeds from the unmodified estimate, so enabling it can never turn a
226 /// previously-successful optimization into a failure.
227 pub chordal_init: bool,
228}
229
230impl Default for PoseGraphSe3Config {
231 fn default() -> Self {
232 Self {
233 max_iterations: 20,
234 step_tolerance: 1e-6,
235 cost_tolerance: 1e-9,
236 robust_kernel: RobustKernel::None,
237 initial_lambda: None,
238 lambda_increase_factor: 10.0,
239 lambda_decrease_factor: 0.1,
240 damping: DampingMode::Identity,
241 max_lambda: 1e12,
242 min_lambda: 1e-9,
243 linear_solver: LinearSolver::Dense,
244 chordal_init: true,
245 }
246 }
247}
248
249/// Per-iteration diagnostics for [`PoseGraph::optimize_se3_iterative`].
250#[derive(Debug, Clone, PartialEq)]
251pub struct PoseGraphSe3IterationStats {
252 pub iteration: usize,
253 pub cost_before: f64,
254 pub cost_after: f64,
255 pub max_step_norm: f64,
256 /// LM damping `λ` used for this iteration (`0.0` for pure Gauss-Newton).
257 pub lambda: f64,
258 /// `true` when the trial step was kept; only false for rejected LM steps.
259 pub step_accepted: bool,
260}
261
262/// Diagnostics from [`PoseGraph::initialize_rotations_chordal`].
263#[derive(Debug, Clone, PartialEq)]
264pub struct ChordalRotationInit {
265 pub anchor_id: u64,
266 pub edge_count: usize,
267 pub variable_count: usize,
268 /// Chordal rotation cost (see [`PoseGraph::chordal_rotation_cost`]) before
269 /// the relaxation was solved.
270 pub cost_before: f64,
271 /// Chordal rotation cost after replacing every node rotation with the
272 /// SVD-projected chordal solution.
273 pub cost_after: f64,
274 /// Largest per-node geodesic rotation change (degrees) applied by the init.
275 pub max_rotation_update_deg: f64,
276}
277
278/// Result of a full SE(3) Gauss-Newton run.
279#[derive(Debug, Clone, PartialEq)]
280pub struct PoseGraphSe3Result {
281 pub anchor_id: u64,
282 pub edge_count: usize,
283 pub variable_count: usize,
284 pub initial_cost: f64,
285 pub final_cost: f64,
286 pub iterations: Vec<PoseGraphSe3IterationStats>,
287 pub converged: bool,
288}
289
290/// Outcome of [`PoseGraph::optimize_se3_gnc`], the outlier-robust SE(3)
291/// pose-graph solve driven by Graduated Non-Convexity (see [`crate::gnc`]).
292///
293/// Beyond the usual cost/convergence summary it reports the **final per-edge
294/// GNC weight** (`edge_weights`, indexed by edge position, each in `[0, 1]`):
295/// an edge annealed to a weight near zero was rejected as an outlier, so this
296/// vector doubles as a loop-closure inlier/outlier classification.
297#[derive(Debug, Clone, PartialEq)]
298pub struct PoseGraphGncResult {
299 pub anchor_id: u64,
300 pub edge_count: usize,
301 pub variable_count: usize,
302 /// Plain (non-robust) least-squares cost at the seeded starting point.
303 pub initial_cost: f64,
304 /// Plain (non-robust) least-squares cost over all edges at the final
305 /// estimate. Outlier edges still contribute their (large) residual here;
306 /// use [`Self::inlier_cost`] for the cost over retained edges only.
307 pub final_cost: f64,
308 /// Plain least-squares cost summed over edges whose final weight is at or
309 /// above the inlier `threshold` passed to the solve — the cost GNC actually
310 /// drove down once outliers were rejected.
311 pub inlier_cost: f64,
312 /// The inlier scale `c` the solve actually used: the configured
313 /// [`gnc::GncConfig::c`] verbatim, or — under
314 /// [`gnc::GncConfig::auto_scale`] — the MAD estimate (floored at the
315 /// configured `c`).
316 pub inlier_scale: f64,
317 /// Number of outer `μ` levels executed.
318 pub outer_iterations: usize,
319 /// Whether the `μ` schedule reached the true robust cost (terminal `μ`).
320 pub converged: bool,
321 /// Final GNC weight per edge, indexed by edge position, in `[0, 1]`.
322 pub edge_weights: Vec<f64>,
323}
324
325impl PoseGraphGncResult {
326 /// Number of edges GNC kept as inliers: final weight `≥ threshold`.
327 pub fn inlier_count(&self, threshold: f64) -> usize {
328 self.edge_weights
329 .iter()
330 .filter(|&&w| w >= threshold)
331 .count()
332 }
333
334 /// Number of edges GNC rejected as outliers: final weight `< threshold`.
335 pub fn outlier_count(&self, threshold: f64) -> usize {
336 self.edge_count - self.inlier_count(threshold)
337 }
338}
339
340/// Errors returned by [`PoseGraph::optimize_translations_once`].
341#[derive(Debug, Clone, PartialEq, Eq)]
342pub enum PoseGraphError {
343 /// No anchor was specified before optimization.
344 NoAnchor,
345 /// An edge or anchor referenced a node that is missing from the graph.
346 MissingNode(u64),
347 /// The graph contains no edges, so there is nothing to optimize.
348 NoEdges,
349 /// The graph contains no non-anchor nodes (all variables are fixed).
350 NoVariables,
351 /// The Gauss-Newton normal equations were singular, e.g., because the
352 /// graph has disconnected components or rank-deficient constraints.
353 SingularSystem,
354}
355
356impl std::fmt::Display for PoseGraphError {
357 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
358 match self {
359 PoseGraphError::NoAnchor => write!(f, "pose graph has no anchor"),
360 PoseGraphError::MissingNode(id) => write!(f, "pose graph is missing node {id}"),
361 PoseGraphError::NoEdges => write!(f, "pose graph has no edges"),
362 PoseGraphError::NoVariables => write!(f, "pose graph has no non-anchor nodes"),
363 PoseGraphError::SingularSystem => {
364 write!(f, "pose graph translation Gauss-Newton system was singular")
365 }
366 }
367 }
368}
369
370impl std::error::Error for PoseGraphError {}
371
372/// Sparse pose graph keyed by keyframe id. Stores per-node poses plus a flat
373/// list of sequential and loop-closure edges, and provides a single
374/// translation-only Gauss-Newton step that keeps node rotations fixed.
375///
376/// This is intentionally a skeleton: rotations are not optimized, the solver
377/// is a single linear least-squares step rather than an iterative SE3 solver,
378/// and there is no incremental incremental map update. Future milestones can
379/// extend the same data type with full SE3 Jacobians, robust kernels, or a
380/// production solver.
381#[derive(Debug, Clone, Default, PartialEq)]
382pub struct PoseGraph {
383 /// Keyframe id → pose. `BTreeMap` keeps the iteration order deterministic
384 /// so the variable layout in the linear system is reproducible.
385 pub poses: BTreeMap<u64, Pose>,
386 /// Edges in insertion order.
387 pub edges: Vec<PoseGraphEdge>,
388 /// Dense Gaussian priors (marginalization factors). Empty for a plain graph,
389 /// so the solver and cost are bit-identical until a [`Self::marginalize_pose`]
390 /// folds a state into one.
391 pub priors: Vec<GaussianPrior>,
392 /// Anchor keyframe id; its pose is held fixed during optimization.
393 pub anchor: Option<u64>,
394}
395
396impl PoseGraph {
397 pub fn new() -> Self {
398 Self::default()
399 }
400
401 /// Insert or replace a pose for `keyframe_id`.
402 pub fn add_pose(&mut self, keyframe_id: u64, pose: Pose) {
403 self.poses.insert(keyframe_id, pose);
404 }
405
406 /// Designate `keyframe_id` as the anchor whose pose stays fixed during
407 /// translation optimization. Replaces any previously selected anchor.
408 pub const fn anchor(&mut self, keyframe_id: u64) {
409 self.anchor = Some(keyframe_id);
410 }
411
412 /// Add a sequential odometry edge with weight `1.0`.
413 pub fn add_sequential_edge(&mut self, from: u64, to: u64, measurement: SE3) {
414 self.edges.push(PoseGraphEdge {
415 from,
416 to,
417 measurement,
418 kind: PoseGraphEdgeKind::Sequential,
419 weight: 1.0,
420 information: None,
421 });
422 }
423
424 /// Append a loop-closure constraint as a graph edge. The verifier-derived
425 /// inlier count is reused as the edge weight (clamped to a minimum of
426 /// `1.0`) so loops with more inliers carry more pull on the solver.
427 pub fn add_loop_closure_constraint(&mut self, constraint: &LoopClosureConstraint) {
428 let weight = (constraint.inlier_count as f64).max(1.0);
429 self.add_loop_closure_constraint_with_weight(constraint, weight);
430 }
431
432 /// Append a loop-closure constraint with an explicit isotropic scalar
433 /// weight. This is the controlled alternative to interpreting a verifier's
434 /// raw inlier count as inverse covariance: correspondence count and pose
435 /// uncertainty do not share units, and a large count can otherwise make one
436 /// loop hundreds of times stiffer than every sequential edge. Invalid
437 /// weights are conservatively replaced by `1.0` so a malformed runtime
438 /// configuration cannot inject NaNs into the graph.
439 pub fn add_loop_closure_constraint_with_weight(
440 &mut self,
441 constraint: &LoopClosureConstraint,
442 weight: f64,
443 ) {
444 let weight = if weight.is_finite() && weight > 0.0 {
445 weight
446 } else {
447 1.0
448 };
449 self.edges.push(PoseGraphEdge {
450 from: constraint.from_keyframe_id,
451 to: constraint.to_keyframe_id,
452 measurement: constraint.relative_pose.clone(),
453 kind: PoseGraphEdgeKind::LoopClosure,
454 weight,
455 information: None,
456 });
457 }
458
459 /// Add an edge carrying a full 6×6 information matrix `Ω`, ordered `[ρ; ω]`
460 /// (translation block first, then rotation — the [`SE3::log`] / `.g2o`
461 /// `EDGE_SE3:QUAT` convention). The SE(3) solver minimizes the anisotropic
462 /// `rᵀ Ω r` for this edge; the scalar `weight` is left at `1.0` and unused
463 /// while `information` is `Some`.
464 pub fn add_edge_with_information(
465 &mut self,
466 from: u64,
467 to: u64,
468 measurement: SE3,
469 kind: PoseGraphEdgeKind,
470 information: Matrix6<f64>,
471 ) {
472 self.edges.push(PoseGraphEdge {
473 from,
474 to,
475 measurement,
476 kind,
477 weight: 1.0,
478 information: Some(information),
479 });
480 }
481
482 /// Sum of squared edge translation residuals in world coordinates.
483 /// Rotation residuals are ignored — this is a translation-only metric
484 /// that matches what [`Self::optimize_translations_once`] minimizes.
485 pub fn translation_cost(&self) -> f64 {
486 let mut total = 0.0;
487 for edge in &self.edges {
488 let (Some(from), Some(to)) = (self.poses.get(&edge.from), self.poses.get(&edge.to))
489 else {
490 continue;
491 };
492 let displacement = expected_world_displacement(to, &edge.measurement);
493 let actual = to.camera_center_world() - from.camera_center_world();
494 let residual = actual - displacement;
495 total += translation_initialization_weight(edge) * residual.norm_squared();
496 }
497 total
498 }
499
500 /// Solve a single Gauss-Newton step on the translation residuals while
501 /// holding rotations fixed. With linear-in-translation residuals the
502 /// "single step" is the exact least-squares optimum of the underlying
503 /// linear system, not a Newton iteration that needs to be repeated.
504 ///
505 /// Equivalent to [`Self::optimize_translations_once_with`] called with
506 /// [`LinearSolver::Dense`].
507 pub fn optimize_translations_once(
508 &mut self,
509 ) -> Result<PoseGraphOptimizationStep, PoseGraphError> {
510 self.optimize_translations_once_with(LinearSolver::Dense)
511 }
512
513 /// Variant of [`Self::optimize_translations_once`] that selects the
514 /// linear-solver backend. Use [`LinearSolver::Sparse`] for graphs with
515 /// hundreds-to-thousands of keyframes — the normal-equations matrix is
516 /// block-banded with at most four `3×3` blocks per edge, so the sparse
517 /// block Cholesky is much faster than the dense path and uses dramatically
518 /// less memory.
519 pub fn optimize_translations_once_with(
520 &mut self,
521 linear_solver: LinearSolver,
522 ) -> Result<PoseGraphOptimizationStep, PoseGraphError> {
523 let anchor_id = self.anchor.ok_or(PoseGraphError::NoAnchor)?;
524 let anchor_pose = self
525 .poses
526 .get(&anchor_id)
527 .ok_or(PoseGraphError::MissingNode(anchor_id))?
528 .clone();
529 let anchor_center = anchor_pose.camera_center_world();
530 if self.edges.is_empty() {
531 return Err(PoseGraphError::NoEdges);
532 }
533
534 let mut node_index: BTreeMap<u64, usize> = BTreeMap::new();
535 for &id in self.poses.keys() {
536 if id == anchor_id {
537 continue;
538 }
539 let next = node_index.len();
540 node_index.insert(id, next);
541 }
542 let variable_count = node_index.len();
543 if variable_count == 0 {
544 return Err(PoseGraphError::NoVariables);
545 }
546
547 for edge in &self.edges {
548 if !self.poses.contains_key(&edge.from) {
549 return Err(PoseGraphError::MissingNode(edge.from));
550 }
551 if !self.poses.contains_key(&edge.to) {
552 return Err(PoseGraphError::MissingNode(edge.to));
553 }
554 }
555
556 let cost_before = self.translation_cost();
557
558 // Assemble the normal equations `A^T A x = A^T b` directly. Each row
559 // of `A` (per edge) has at most two nonzero 3×3 identity-shaped
560 // blocks (`+sqrt(w) · I` at `to`, `-sqrt(w) · I` at `from`), so the
561 // contribution to `A^T A` per edge is block-structured: `w · I` at the
562 // `(to, to)` and `(from, from)` diagonal blocks and `-w · I` at
563 // both off-diagonal blocks. Anchor-incident edges only push to one
564 // diagonal and shift `A^T b` by the anchor center.
565 //
566 // This is only a seed for the full SE(3) solve, so a 6×6 information
567 // matrix is reduced to the rotationally invariant mean eigenvalue of
568 // its translation block (trace / 3). Crucially, this preserves any
569 // loop-only scalar applied to Ω; treating every information edge as
570 // scalar weight 1 would let a deliberately weak loop dominate the
571 // chordal seed before GNC starts.
572 let dim = variable_count * 3;
573 let mut h_dense = match linear_solver {
574 LinearSolver::Dense => Some(DMatrix::<f64>::zeros(dim, dim)),
575 LinearSolver::Sparse => None,
576 };
577 let mut triplets: Vec<(usize, usize, f64)> = match linear_solver {
578 LinearSolver::Dense => Vec::new(),
579 LinearSolver::Sparse => Vec::with_capacity(self.edges.len() * 36),
580 };
581 let mut atb = DVector::<f64>::zeros(dim);
582
583 for edge in &self.edges {
584 let to_pose = &self.poses[&edge.to];
585 let displacement = expected_world_displacement(to_pose, &edge.measurement);
586 let mut rhs = displacement;
587 let w2 = translation_initialization_weight(edge);
588
589 let i_to = node_index.get(&edge.to).copied();
590 let i_from = node_index.get(&edge.from).copied();
591 if i_to.is_none() {
592 rhs -= anchor_center.coords;
593 }
594 if i_from.is_none() {
595 rhs += anchor_center.coords;
596 }
597
598 if let Some(j) = i_to {
599 add_diag_block3(&mut h_dense, &mut triplets, j * 3, w2);
600 for k in 0..3 {
601 atb[j * 3 + k] += w2 * rhs[k];
602 }
603 }
604 if let Some(i) = i_from {
605 add_diag_block3(&mut h_dense, &mut triplets, i * 3, w2);
606 for k in 0..3 {
607 atb[i * 3 + k] -= w2 * rhs[k];
608 }
609 }
610 if let (Some(j), Some(i)) = (i_to, i_from) {
611 add_offdiag_block3(&mut h_dense, &mut triplets, j * 3, i * 3, -w2);
612 add_offdiag_block3(&mut h_dense, &mut triplets, i * 3, j * 3, -w2);
613 }
614 }
615
616 let solution = match linear_solver {
617 LinearSolver::Dense => {
618 let h = h_dense.expect("dense matrix initialized when LinearSolver::Dense");
619 solve_normal_equations(&h, &atb)?
620 }
621 LinearSolver::Sparse => {
622 let order = reordering::Reordering::fill_reducing(dim, 3, &triplets);
623 // One-shot solve (no LM loop), so the symbolic analysis is not reused.
624 solve_normal_equations_sparse(&triplets, dim, 3, &atb, 0.0, &order, &mut None)?
625 }
626 };
627
628 let mut total_correction = 0.0;
629 let mut max_correction: f64 = 0.0;
630 for (&id, &i) in &node_index {
631 let new_center = Point3::new(solution[i * 3], solution[i * 3 + 1], solution[i * 3 + 2]);
632 let pose = self
633 .poses
634 .get_mut(&id)
635 .ok_or(PoseGraphError::MissingNode(id))?;
636 let old_center = pose.camera_center_world();
637 let correction_norm = (new_center - old_center).norm();
638 total_correction += correction_norm;
639 if correction_norm > max_correction {
640 max_correction = correction_norm;
641 }
642 let rotation_matrix = pose
643 .world_to_camera
644 .rotation
645 .to_rotation_matrix()
646 .into_inner();
647 pose.world_to_camera.translation = -(rotation_matrix * new_center.coords);
648 }
649
650 let cost_after = self.translation_cost();
651 let mean_translation_correction = if variable_count > 0 {
652 total_correction / variable_count as f64
653 } else {
654 0.0
655 };
656
657 Ok(PoseGraphOptimizationStep {
658 anchor_id,
659 edge_count: self.edges.len(),
660 variable_count,
661 cost_before,
662 cost_after,
663 mean_translation_correction,
664 max_translation_correction: max_correction,
665 })
666 }
667
668 /// Sum of squared SE(3) residuals: r_e = log(meas_e⁻¹ · T_to · T_from⁻¹),
669 /// weighted by `edge.weight`. Unlike [`Self::translation_cost`], this
670 /// includes both the translation and rotation components of every edge.
671 pub fn se3_cost(&self) -> f64 {
672 self.robust_se3_cost(&RobustKernel::None)
673 }
674
675 /// Robust SE(3) cost: `Σ_e edge.weight · ρ(||r_e||²)` where `ρ` is the
676 /// supplied [`RobustKernel`]. With [`RobustKernel::None`] this matches
677 /// [`Self::se3_cost`].
678 pub fn robust_se3_cost(&self, kernel: &RobustKernel) -> f64 {
679 let mut total = 0.0;
680 for edge in &self.edges {
681 let (Some(from), Some(to)) = (self.poses.get(&edge.from), self.poses.get(&edge.to))
682 else {
683 continue;
684 };
685 let predicted = to.world_to_camera.compose(&from.world_to_camera.inverse());
686 let r = edge.measurement.inverse().compose(&predicted).log();
687 total += match &edge.information {
688 // Anisotropic: robust kernel operates on the Mahalanobis
689 // distance rᵀΩr; the scalar weight is folded into Ω.
690 Some(omega) => kernel.cost((r.transpose() * omega * r)[(0, 0)]),
691 // Isotropic: weight scales the kernel output, kernel sees ‖r‖².
692 None => edge.weight * kernel.cost(r.norm_squared()),
693 };
694 }
695 total + self.prior_cost()
696 }
697
698 /// Stacked right-tangent error of a prior's poses from their linearization:
699 /// `eᵢ = log(T₀ᵢ⁻¹ ∘ Tᵢ)`, one 6-vector per id, in `ids` order (`[ρ; ω]`
700 /// SE(3) tangent). A pose absent from the graph — or pinned at its
701 /// linearization, like the anchor — contributes a zero block. Length
702 /// `6 · ids.len()`.
703 fn prior_tangent_error(&self, prior: &GaussianPrior) -> DVector<f64> {
704 let mut e = DVector::<f64>::zeros(prior.ids.len() * 6);
705 for (i, (&id, t0)) in prior.ids.iter().zip(&prior.linearization).enumerate() {
706 if let Some(pose) = self.poses.get(&id) {
707 let err = t0.inverse().compose(&pose.world_to_camera).log();
708 for k in 0..6 {
709 e[i * 6 + k] = err[k];
710 }
711 }
712 }
713 e
714 }
715
716 /// Total Gaussian-prior cost `Σ (eᵀ Ω e + 2 bᵀ e)` (the marginalization
717 /// factors), on the same `2×` scale as the edge cost `rᵀΩr` so the LM accept
718 /// test sees one consistent objective (the dropped constant cancels in
719 /// `cost_after − cost_before`). Zero when the graph carries no priors.
720 fn prior_cost(&self) -> f64 {
721 self.priors
722 .iter()
723 .map(|prior| {
724 let e = self.prior_tangent_error(prior);
725 (e.transpose() * &prior.information * &e)[(0, 0)] + 2.0 * prior.gradient.dot(&e)
726 })
727 .sum()
728 }
729
730 /// Robust SE(3) cost with an optional per-edge multiplier (`gnc_weights`,
731 /// indexed by edge position). Identical to [`Self::robust_se3_cost`] when
732 /// `gnc_weights` is `None`; with weights it is the *weighted* objective
733 /// `Σ wᵢ · ρ(sᵢ)` that the Graduated Non-Convexity driver minimizes at a
734 /// fixed `μ` level (the Black-Rangarajan inner problem), where `wᵢ` is the
735 /// closed-form GNC weight and the kernel is [`RobustKernel::None`] (GNC
736 /// supersedes the M-estimator). See [`crate::gnc`] and
737 /// [`Self::optimize_se3_gnc`].
738 fn robust_se3_cost_weighted(&self, kernel: &RobustKernel, gnc_weights: Option<&[f64]>) -> f64 {
739 let mut total = 0.0;
740 for (idx, edge) in self.edges.iter().enumerate() {
741 let (Some(from), Some(to)) = (self.poses.get(&edge.from), self.poses.get(&edge.to))
742 else {
743 continue;
744 };
745 let predicted = to.world_to_camera.compose(&from.world_to_camera.inverse());
746 let r = edge.measurement.inverse().compose(&predicted).log();
747 let gw = gnc_weights.map_or(1.0, |w| w[idx]);
748 total += gw
749 * match &edge.information {
750 Some(omega) => kernel.cost((r.transpose() * omega * r)[(0, 0)]),
751 None => edge.weight * kernel.cost(r.norm_squared()),
752 };
753 }
754 total + self.prior_cost()
755 }
756
757 /// Per-edge (whitened) squared residual `sᵢ`, indexed by edge position —
758 /// the same quantity the [`RobustKernel`] sees: the Mahalanobis distance
759 /// `rᵀΩr` for an edge carrying a full information matrix, else
760 /// `edge.weight · ‖r‖²`. Including the scalar information is essential:
761 /// GNC classification must use the same whitened residual scale as its
762 /// weighted least-squares inner solve.
763 /// Edges referencing a missing node contribute `0.0` so the vector stays
764 /// aligned with [`Self::edges`]. Used by the GNC driver to reweight edges.
765 fn edge_squared_residuals(&self) -> Vec<f64> {
766 self.edges
767 .iter()
768 .map(|edge| {
769 let (Some(from), Some(to)) = (self.poses.get(&edge.from), self.poses.get(&edge.to))
770 else {
771 return 0.0;
772 };
773 let predicted = to.world_to_camera.compose(&from.world_to_camera.inverse());
774 let r = edge.measurement.inverse().compose(&predicted).log();
775 match &edge.information {
776 Some(omega) => (r.transpose() * omega * r)[(0, 0)],
777 None => edge.weight * r.norm_squared(),
778 }
779 })
780 .collect()
781 }
782
783 /// Assemble the Gauss-Newton normal equations `(H, g)` for the SE(3) pose
784 /// graph: the robust-weighted `H = Σ Jᵀ Ω J` and gradient `g = Σ Jᵀ Ω r`
785 /// over all edges, in the `node_index` variable layout (`dim = 6 · #vars`).
786 ///
787 /// Extracted from [`Self::optimize_se3_iterative`] so both the plain
788 /// optimizer and the GNC driver share one assembly. `gnc_weights` is an
789 /// optional per-edge multiplier (indexed by edge position): `None`
790 /// reproduces the plain assembly bit-for-bit; `Some(w)` scales each edge's
791 /// contribution by `wᵢ ∈ [0, 1]` for the GNC inner solve (see
792 /// [`crate::gnc`]). The isotropic path keeps the legacy semantics
793 /// (`weight` outside the kernel, kernel on `‖r‖²`); the anisotropic path
794 /// folds `Ω` into both `JᵀJ` and `Jᵀr` and lets the kernel see the
795 /// Mahalanobis distance `rᵀΩr`.
796 fn assemble_se3_system(
797 &self,
798 node_index: &BTreeMap<u64, usize>,
799 dim: usize,
800 kernel: &RobustKernel,
801 gnc_weights: Option<&[f64]>,
802 linear_solver: LinearSolver,
803 ) -> (NormalEquations6, DVector<f64>) {
804 let mut builder = NormalEquations6::new(dim, linear_solver, self.edges.len());
805 let mut g = DVector::<f64>::zeros(dim);
806
807 for (idx, edge) in self.edges.iter().enumerate() {
808 let t_from = &self.poses[&edge.from].world_to_camera;
809 let t_to = &self.poses[&edge.to].world_to_camera;
810 let predicted = t_to.compose(&t_from.inverse());
811 let r = edge.measurement.inverse().compose(&predicted).log();
812 let ad_from = t_from.adjoint();
813 let (weight, ata, atr) = match &edge.information {
814 Some(omega) => {
815 let robust_weight = kernel.weight((r.transpose() * omega * r)[(0, 0)]);
816 let oa = ad_from.transpose() * omega;
817 (robust_weight, oa * ad_from, oa * r)
818 }
819 None => {
820 let robust_weight = kernel.weight(r.norm_squared());
821 (
822 edge.weight * robust_weight,
823 ad_from.transpose() * ad_from,
824 ad_from.transpose() * r,
825 )
826 }
827 };
828 // GNC reweighting: a multiplier in [0, 1] (1.0 when not running
829 // GNC) that scales the whole edge contribution, rejecting outliers
830 // as `wᵢ → 0`.
831 let weight = weight * gnc_weights.map_or(1.0, |w| w[idx]);
832
833 let i_from = node_index.get(&edge.from).copied();
834 let i_to = node_index.get(&edge.to).copied();
835
836 if let Some(j) = i_to {
837 builder.add_block6(j * 6, j * 6, weight, &ata);
838 add_segment6(&mut g, j * 6, weight, &atr);
839 }
840 if let Some(i) = i_from {
841 builder.add_block6(i * 6, i * 6, weight, &ata);
842 add_segment6(&mut g, i * 6, -weight, &atr);
843 }
844 if let (Some(j), Some(i)) = (i_to, i_from) {
845 let cross = -ata;
846 let cross_t = cross.transpose();
847 builder.add_block6(j * 6, i * 6, weight, &cross);
848 builder.add_block6(i * 6, j * 6, weight, &cross_t);
849 }
850 }
851
852 // Gaussian (marginalization) priors: the factor `½ eᵀ Ω e` with
853 // `eᵢ = log(T₀ᵢ⁻¹ ∘ Tᵢ)` and identity Jacobian (`∂eᵢ/∂δᵢ = I`), so it
854 // contributes `Ω` to `H` and `Ω·e` to `g` on the variable blocks. A
855 // prior id that is the anchor (or absent) has `eᵢ ≈ 0` and no variable
856 // block, so it drops out — leaving the kept poses' coupling intact.
857 for prior in &self.priors {
858 let e = self.prior_tangent_error(prior);
859 let ge = &prior.information * &e + &prior.gradient; // Ω·e + b (length 6k)
860 for (pi, &id_i) in prior.ids.iter().enumerate() {
861 let Some(vi) = node_index.get(&id_i).copied() else {
862 continue;
863 };
864 add_segment6(
865 &mut g,
866 vi * 6,
867 1.0,
868 &Vector6::from_fn(|k, _| ge[pi * 6 + k]),
869 );
870 for (pj, &id_j) in prior.ids.iter().enumerate() {
871 let Some(vj) = node_index.get(&id_j).copied() else {
872 continue;
873 };
874 let block =
875 Matrix6::from_fn(|r, c| prior.information[(pi * 6 + r, pj * 6 + c)]);
876 builder.add_block6(vi * 6, vj * 6, 1.0, &block);
877 }
878 }
879 }
880
881 (builder, g)
882 }
883
884 /// Chordal (Frobenius-relaxed) cost of the current node rotations:
885 /// `Σ_e w_e · ‖R_to − R_meas_e · R_from‖_F²`, where `R_*` is the rotation
886 /// of each node's `world_to_camera` and `R_meas_e` the rotation of the
887 /// edge measurement. This is the objective minimized by
888 /// [`Self::initialize_rotations_chordal`]; unlike [`Self::se3_cost`] it
889 /// ignores translation and uses the chordal (embedded-Euclidean) metric on
890 /// SO(3) rather than the geodesic one, so it is a convex function of the
891 /// relaxed (unconstrained 3×3) rotation variables.
892 pub fn chordal_rotation_cost(&self) -> f64 {
893 let mut total = 0.0;
894 for edge in &self.edges {
895 let (Some(from), Some(to)) = (self.poses.get(&edge.from), self.poses.get(&edge.to))
896 else {
897 continue;
898 };
899 let r_from = from
900 .world_to_camera
901 .rotation
902 .to_rotation_matrix()
903 .into_inner();
904 let r_to = to
905 .world_to_camera
906 .rotation
907 .to_rotation_matrix()
908 .into_inner();
909 let r_meas = edge.measurement.rotation.to_rotation_matrix().into_inner();
910 total += chordal_rotation_weight(edge) * (r_to - r_meas * r_from).norm_squared();
911 }
912 total
913 }
914
915 /// Initialize node rotations by solving the *chordal relaxation* of the
916 /// rotation-only sub-problem (Carlone et al., "Initialization Techniques
917 /// for 3D SLAM", ICRA 2015). On hard 3D datasets the SE(3) cost surface is
918 /// strongly non-convex in rotation, so a full solve started from raw
919 /// odometry stalls in a poor basin; seeding it with the chordal solution
920 /// lands it near the global optimum.
921 ///
922 /// Each edge contributes the residual `R_to − R_meas · R_from` measured in
923 /// the embedded-Euclidean (Frobenius) metric. Relaxing every `R_i` from
924 /// `SO(3)` to an unconstrained `3×3` matrix makes the objective a single
925 /// linear least-squares problem; the per-node `9`-vector splits into three
926 /// independent `3`-vector systems (one per rotation column) that share the
927 /// *same* `3n × 3n` normal matrix — so this factors once and solves three
928 /// right-hand sides. Each relaxed `3×3` block is then projected back onto
929 /// `SO(3)` with an SVD (`R = U·diag(1,1,det(UVᵀ))·Vᵀ`).
930 ///
931 /// The anchor's rotation is held fixed (it fixes the global gauge). Each
932 /// node's camera *center* is preserved — only its orientation is replaced —
933 /// so this is safe to call standalone, though the intended flow is
934 /// chordal-rotation → [`Self::optimize_translations_once_with`] →
935 /// [`Self::optimize_se3_iterative`].
936 pub fn initialize_rotations_chordal(
937 &mut self,
938 linear_solver: LinearSolver,
939 ) -> Result<ChordalRotationInit, PoseGraphError> {
940 let anchor_id = self.anchor.ok_or(PoseGraphError::NoAnchor)?;
941 let anchor_pose = self
942 .poses
943 .get(&anchor_id)
944 .ok_or(PoseGraphError::MissingNode(anchor_id))?;
945 let r_anchor = anchor_pose
946 .world_to_camera
947 .rotation
948 .to_rotation_matrix()
949 .into_inner();
950 if self.edges.is_empty() {
951 return Err(PoseGraphError::NoEdges);
952 }
953 for edge in &self.edges {
954 if !self.poses.contains_key(&edge.from) {
955 return Err(PoseGraphError::MissingNode(edge.from));
956 }
957 if !self.poses.contains_key(&edge.to) {
958 return Err(PoseGraphError::MissingNode(edge.to));
959 }
960 }
961
962 let mut node_index: BTreeMap<u64, usize> = BTreeMap::new();
963 for &id in self.poses.keys() {
964 if id == anchor_id {
965 continue;
966 }
967 let next = node_index.len();
968 node_index.insert(id, next);
969 }
970 let variable_count = node_index.len();
971 if variable_count == 0 {
972 return Err(PoseGraphError::NoVariables);
973 }
974
975 let cost_before = self.chordal_rotation_cost();
976
977 // Assemble the shared 3n×3n normal matrix and three right-hand sides
978 // (the three columns of the stacked rotation matrices). The matrix is
979 // identical across columns because it depends only on the (orthonormal)
980 // measured rotations and the edge weights; each anchor-incident edge
981 // shifts one column's right-hand side by that column of R_anchor.
982 let dim = variable_count * 3;
983 let mut h_dense = match linear_solver {
984 LinearSolver::Dense => Some(DMatrix::<f64>::zeros(dim, dim)),
985 LinearSolver::Sparse => None,
986 };
987 let mut triplets: Vec<(usize, usize, f64)> = match linear_solver {
988 LinearSolver::Dense => Vec::new(),
989 LinearSolver::Sparse => Vec::with_capacity(self.edges.len() * 36),
990 };
991 let mut rhs = DMatrix::<f64>::zeros(dim, 3);
992
993 for edge in &self.edges {
994 let r_meas = edge.measurement.rotation.to_rotation_matrix().into_inner();
995 let w = chordal_rotation_weight(edge);
996
997 let i_to = node_index.get(&edge.to).copied();
998 let i_from = node_index.get(&edge.from).copied();
999
1000 if let Some(j) = i_to {
1001 add_diag_block3(&mut h_dense, &mut triplets, j * 3, w);
1002 }
1003 if let Some(i) = i_from {
1004 add_diag_block3(&mut h_dense, &mut triplets, i * 3, w);
1005 }
1006 match (i_to, i_from) {
1007 (Some(j), Some(i)) => {
1008 // Both endpoints free: off-diagonal coupling -w·R_meas.
1009 add_dense_block3(&mut h_dense, &mut triplets, j * 3, i * 3, &(-w * r_meas));
1010 add_dense_block3(
1011 &mut h_dense,
1012 &mut triplets,
1013 i * 3,
1014 j * 3,
1015 &(-w * r_meas.transpose()),
1016 );
1017 }
1018 (Some(j), None) => {
1019 // `from` is the anchor: g_to += w · R_meas · col(R_anchor).
1020 let contribution = w * r_meas * r_anchor;
1021 for c in 0..3 {
1022 for k in 0..3 {
1023 rhs[(j * 3 + k, c)] += contribution[(k, c)];
1024 }
1025 }
1026 }
1027 (None, Some(i)) => {
1028 // `to` is the anchor: g_from += w · R_measᵀ · col(R_anchor).
1029 let contribution = w * r_meas.transpose() * r_anchor;
1030 for c in 0..3 {
1031 for k in 0..3 {
1032 rhs[(i * 3 + k, c)] += contribution[(k, c)];
1033 }
1034 }
1035 }
1036 (None, None) => {}
1037 }
1038 }
1039
1040 let solution = match linear_solver {
1041 LinearSolver::Dense => {
1042 let h = h_dense.expect("dense matrix initialized when LinearSolver::Dense");
1043 let chol = h.cholesky().ok_or(PoseGraphError::SingularSystem)?;
1044 chol.solve(&rhs)
1045 }
1046 LinearSolver::Sparse => {
1047 let order = reordering::Reordering::fill_reducing(dim, 3, &triplets);
1048 solve_normal_equations_sparse_multi(&triplets, dim, 3, &rhs, &order)?
1049 }
1050 };
1051
1052 // Reshape each node's solved columns into a 3×3, project onto SO(3),
1053 // and replace the node's orientation while keeping its camera center.
1054 let mut max_rotation_update_rad: f64 = 0.0;
1055 for (&id, &i) in &node_index {
1056 let mut block = Matrix3::<f64>::zeros();
1057 for c in 0..3 {
1058 for k in 0..3 {
1059 block[(k, c)] = solution[(i * 3 + k, c)];
1060 }
1061 }
1062 let projected = project_to_so3(&block).ok_or(PoseGraphError::SingularSystem)?;
1063 let new_rotation =
1064 UnitQuaternion::from_rotation_matrix(&Rotation3::from_matrix_unchecked(projected));
1065
1066 let pose = self
1067 .poses
1068 .get_mut(&id)
1069 .ok_or(PoseGraphError::MissingNode(id))?;
1070 let center = pose.camera_center_world();
1071 let delta = new_rotation
1072 .rotation_to(&pose.world_to_camera.rotation)
1073 .angle();
1074 max_rotation_update_rad = max_rotation_update_rad.max(delta);
1075 pose.world_to_camera.rotation = new_rotation;
1076 // Re-derive translation from the preserved center: t = -R·center.
1077 pose.world_to_camera.translation = -(projected * center.coords);
1078 }
1079
1080 let cost_after = self.chordal_rotation_cost();
1081 Ok(ChordalRotationInit {
1082 anchor_id,
1083 edge_count: self.edges.len(),
1084 variable_count,
1085 cost_before,
1086 cost_after,
1087 max_rotation_update_deg: max_rotation_update_rad.to_degrees(),
1088 })
1089 }
1090
1091 /// Run a full SE(3) Gauss-Newton optimization with right-perturbation
1092 /// updates `T_i ← T_i · Exp(δ_i)`. Uses the first-order BCH approximation
1093 /// `J_r⁻¹(r) ≈ I`, so each edge contributes:
1094 ///
1095 /// - residual: `r_e = log(meas_e⁻¹ · T_to · T_from⁻¹)` (6-vector),
1096 /// - Jacobians: `∂r/∂δ_to = Ad(T_from)`, `∂r/∂δ_from = -Ad(T_from)`.
1097 ///
1098 /// The anchor pose is held fixed; all other poses are updated. Returns the
1099 /// per-iteration cost trace plus a `converged` flag derived from the
1100 /// configured tolerances.
1101 pub fn optimize_se3_iterative(
1102 &mut self,
1103 config: &PoseGraphSe3Config,
1104 ) -> Result<PoseGraphSe3Result, PoseGraphError> {
1105 let anchor_id = self.anchor.ok_or(PoseGraphError::NoAnchor)?;
1106 if !self.poses.contains_key(&anchor_id) {
1107 return Err(PoseGraphError::MissingNode(anchor_id));
1108 }
1109 if self.edges.is_empty() {
1110 return Err(PoseGraphError::NoEdges);
1111 }
1112 for edge in &self.edges {
1113 if !self.poses.contains_key(&edge.from) {
1114 return Err(PoseGraphError::MissingNode(edge.from));
1115 }
1116 if !self.poses.contains_key(&edge.to) {
1117 return Err(PoseGraphError::MissingNode(edge.to));
1118 }
1119 }
1120
1121 let mut node_index: BTreeMap<u64, usize> = BTreeMap::new();
1122 for &id in self.poses.keys() {
1123 if id == anchor_id {
1124 continue;
1125 }
1126 let next = node_index.len();
1127 node_index.insert(id, next);
1128 }
1129 let variable_count = node_index.len();
1130 if variable_count == 0 {
1131 return Err(PoseGraphError::NoVariables);
1132 }
1133
1134 let kernel = config.robust_kernel;
1135 // `initial_cost` records the true starting point — measured before any
1136 // seeding — so the reported reduction reflects the full improvement,
1137 // including the (often large) drop the chordal step front-loads.
1138 let initial_cost = self.robust_se3_cost(&kernel);
1139
1140 // Optional chordal rotation seeding: solve the relaxed rotation
1141 // sub-problem to a globally-consistent orientation and re-derive
1142 // translations before the non-convex SE(3) solve. Best-effort — a
1143 // singular relaxation is skipped, leaving the unmodified estimate, so
1144 // seeding can never turn a solvable problem into a failure. The
1145 // rotation re-derivation already restores translations from the
1146 // preserved camera centers, so the translation LS is a further refine
1147 // whose failure is also harmless.
1148 if config.chordal_init
1149 && self
1150 .initialize_rotations_chordal(config.linear_solver)
1151 .is_ok()
1152 {
1153 let _ = self.optimize_translations_once_with(config.linear_solver);
1154 }
1155
1156 let mut iterations: Vec<PoseGraphSe3IterationStats> =
1157 Vec::with_capacity(config.max_iterations);
1158 let mut converged = false;
1159 // The LM accept test compares against the *seeded* cost, so the loop
1160 // starts from the post-seed state rather than the pre-seed `initial_cost`.
1161 let mut current_cost = self.robust_se3_cost(&kernel);
1162 let mut lambda = config.initial_lambda.unwrap_or(0.0);
1163 let dim = variable_count * 6;
1164 // The fill-reducing ordering depends only on the (iteration-invariant)
1165 // sparsity pattern, so compute it lazily on the first sparse solve and
1166 // reuse it for the rest of the optimization.
1167 let mut order_cache: Option<reordering::Reordering> = None;
1168 // The normal-equations sparsity pattern is iteration-invariant, so the
1169 // block-Cholesky symbolic factorization is analyzed once and reused
1170 // alongside the fill-reducing order across all LM iterations.
1171 let mut symbolic_cache: Option<block_cholesky::BlockSymbolic> = None;
1172
1173 for iteration in 0..config.max_iterations {
1174 let (builder, g) =
1175 self.assemble_se3_system(&node_index, dim, &kernel, None, config.linear_solver);
1176
1177 // Marquardt damping scales by the (undamped) curvature, so capture the
1178 // diagonal of H before it is consumed by the solve.
1179 let diag = match config.damping {
1180 DampingMode::Diagonal => Some(builder.diagonal()),
1181 DampingMode::Identity => None,
1182 };
1183 let neg_g = -&g;
1184 let delta = builder.solve(
1185 lambda,
1186 diag.as_deref(),
1187 &neg_g,
1188 &mut order_cache,
1189 &mut symbolic_cache,
1190 )?;
1191
1192 // Tentatively apply the step so we can evaluate the new cost.
1193 let mut max_step_norm: f64 = 0.0;
1194 let cost_before = current_cost;
1195 let saved_poses = if config.initial_lambda.is_some() {
1196 Some(self.poses.clone())
1197 } else {
1198 None
1199 };
1200 for (&id, &i) in &node_index {
1201 let block = i * 6;
1202 let mut xi = Vector6::<f64>::zeros();
1203 for k in 0..6 {
1204 xi[k] = delta[block + k];
1205 }
1206 let step = xi.norm();
1207 if step > max_step_norm {
1208 max_step_norm = step;
1209 }
1210 let pose = self
1211 .poses
1212 .get_mut(&id)
1213 .ok_or(PoseGraphError::MissingNode(id))?;
1214 pose.world_to_camera = pose.world_to_camera.compose(&SE3::exp(&xi));
1215 }
1216
1217 let cost_after = self.robust_se3_cost(&kernel);
1218 let step_accepted = match config.initial_lambda {
1219 None => true,
1220 Some(_) => cost_after < cost_before,
1221 };
1222
1223 if !step_accepted {
1224 if let Some(saved) = saved_poses {
1225 self.poses = saved;
1226 }
1227 lambda = (lambda * config.lambda_increase_factor).min(config.max_lambda);
1228 iterations.push(PoseGraphSe3IterationStats {
1229 iteration,
1230 cost_before,
1231 cost_after,
1232 max_step_norm,
1233 lambda,
1234 step_accepted: false,
1235 });
1236 if lambda >= config.max_lambda {
1237 // λ saturated without finding a downhill step → bail.
1238 break;
1239 }
1240 continue;
1241 }
1242
1243 iterations.push(PoseGraphSe3IterationStats {
1244 iteration,
1245 cost_before,
1246 cost_after,
1247 max_step_norm,
1248 lambda,
1249 step_accepted: true,
1250 });
1251 current_cost = cost_after;
1252 if config.initial_lambda.is_some() {
1253 lambda = (lambda * config.lambda_decrease_factor).max(config.min_lambda);
1254 }
1255
1256 if max_step_norm < config.step_tolerance {
1257 converged = true;
1258 break;
1259 }
1260 if (cost_before - cost_after).abs() < config.cost_tolerance {
1261 converged = true;
1262 break;
1263 }
1264 }
1265
1266 Ok(PoseGraphSe3Result {
1267 anchor_id,
1268 edge_count: self.edges.len(),
1269 variable_count,
1270 initial_cost,
1271 final_cost: current_cost,
1272 iterations,
1273 converged,
1274 })
1275 }
1276
1277 /// Outlier-robust SE(3) pose-graph optimization via Graduated Non-Convexity
1278 /// (GNC; see [`crate::gnc`]). Use this instead of [`Self::optimize_se3_iterative`]
1279 /// when loop closures may be **wrong** (perceptual aliasing, place-recognition
1280 /// false positives): a single bad loop closure pulls a plain least-squares —
1281 /// or even a Huber/Cauchy IRLS — solve into a corrupted basin, whereas GNC
1282 /// anneals from a convex surrogate that trusts every edge to the true robust
1283 /// cost that rejects outliers, recovering the inlier trajectory.
1284 ///
1285 /// `config` supplies the same SE(3) LM settings as
1286 /// [`Self::optimize_se3_iterative`] (linear solver, `λ` schedule,
1287 /// tolerances, chordal seeding); its `robust_kernel` is ignored — GNC
1288 /// supersedes the M-estimator and the inner solve runs on the GNC-weighted
1289 /// least-squares cost. `gnc` selects the surrogate family, the inlier scale
1290 /// `c`, the `μ` annealing factor, the outer-level cap, and the number of
1291 /// inner LM iterations per level.
1292 ///
1293 /// Each outer level reweights every edge by its closed-form GNC weight at
1294 /// the current `μ`, runs a bounded weighted-LS solve, then sharpens `μ` one
1295 /// geometric step. The fill-reducing order and block-Cholesky symbolic
1296 /// factorization are `μ`-invariant and reused across all levels. The
1297 /// returned [`PoseGraphGncResult::edge_weights`] is the final per-edge
1298 /// inlier/outlier classification.
1299 pub fn optimize_se3_gnc(
1300 &mut self,
1301 config: &PoseGraphSe3Config,
1302 gnc: &gnc::GncConfig,
1303 ) -> Result<PoseGraphGncResult, PoseGraphError> {
1304 let anchor_id = self.anchor.ok_or(PoseGraphError::NoAnchor)?;
1305 if !self.poses.contains_key(&anchor_id) {
1306 return Err(PoseGraphError::MissingNode(anchor_id));
1307 }
1308 if self.edges.is_empty() {
1309 return Err(PoseGraphError::NoEdges);
1310 }
1311 for edge in &self.edges {
1312 if !self.poses.contains_key(&edge.from) {
1313 return Err(PoseGraphError::MissingNode(edge.from));
1314 }
1315 if !self.poses.contains_key(&edge.to) {
1316 return Err(PoseGraphError::MissingNode(edge.to));
1317 }
1318 }
1319
1320 let mut node_index: BTreeMap<u64, usize> = BTreeMap::new();
1321 for &id in self.poses.keys() {
1322 if id == anchor_id {
1323 continue;
1324 }
1325 let next = node_index.len();
1326 node_index.insert(id, next);
1327 }
1328 let variable_count = node_index.len();
1329 if variable_count == 0 {
1330 return Err(PoseGraphError::NoVariables);
1331 }
1332 let dim = variable_count * 6;
1333
1334 // GNC replaces the M-estimator, so the inner solve is plain weighted
1335 // least squares (kernel `None`); the GNC weights carry the robustness.
1336 let kernel = RobustKernel::None;
1337 // Report the pre-seed plain L2 cost so the reduction reflects the full
1338 // improvement, mirroring `optimize_se3_iterative`.
1339 let initial_cost = self.robust_se3_cost(&kernel);
1340
1341 // Optional chordal rotation seeding (best-effort). GNC's first surrogate
1342 // is convex (trusts every edge), so seeding from the all-edge rotation
1343 // least squares is consistent with it; as μ sharpens, outliers are
1344 // down-weighted and the estimate moves off any seed they corrupted.
1345 if config.chordal_init
1346 && self
1347 .initialize_rotations_chordal(config.linear_solver)
1348 .is_ok()
1349 {
1350 let _ = self.optimize_translations_once_with(config.linear_solver);
1351 }
1352
1353 // Convex first surrogate: initialize μ from the largest seeded residual.
1354 // The same seeded residuals optionally drive the MAD auto-estimate of
1355 // the inlier scale `c` (with `gnc.c` as a floor), so the inlier/outlier
1356 // boundary tracks this graph's noise level instead of a hand-set value.
1357 let squared_residuals = self.edge_squared_residuals();
1358 let s_max = squared_residuals.iter().copied().fold(0.0_f64, f64::max);
1359 let effective_gnc = match gnc.auto_scale {
1360 Some(k) => {
1361 let c = gnc::estimate_scale_mad(&squared_residuals, k)
1362 .map_or(gnc.c, |est| est.max(gnc.c));
1363 gnc::GncConfig { c, ..*gnc }
1364 }
1365 None => *gnc,
1366 };
1367 let mut inlier_scale = effective_gnc.c;
1368 let mut state = gnc::GncState::new(&effective_gnc, s_max);
1369 let mut gnc_weights = vec![1.0_f64; self.edges.len()];
1370
1371 // The sparsity pattern is μ-invariant, so the fill-reducing order and
1372 // block-Cholesky symbolic factorization are analyzed once and reused.
1373 let mut order_cache: Option<reordering::Reordering> = None;
1374 let mut symbolic_cache: Option<block_cholesky::BlockSymbolic> = None;
1375
1376 let mut converged = false;
1377 let mut outer_iterations = 0usize;
1378 let max_outer = gnc.max_outer.max(1);
1379
1380 for _ in 0..max_outer {
1381 outer_iterations += 1;
1382 // A level entered already-terminal is solving at the true robust
1383 // cost — run it, then stop (guarantees one solve at terminal μ).
1384 let terminal_level = state.is_terminal();
1385
1386 // Black-Rangarajan weight update at the current μ.
1387 let residuals = self.edge_squared_residuals();
1388 // Adaptive inlier scale: re-derive `c` from the current residuals
1389 // each level (configured `c` as a floor). Level 0 reproduces the
1390 // one-shot estimate; later levels tighten as outliers are
1391 // suppressed and inlier residuals shrink.
1392 if gnc.auto_scale_readapt {
1393 if let Some(k) = gnc.auto_scale {
1394 if let Some(est) = gnc::estimate_scale_mad(&residuals, k) {
1395 let c = est.max(gnc.c);
1396 state.set_inlier_scale(c);
1397 inlier_scale = c;
1398 }
1399 }
1400 }
1401 for (i, &s) in residuals.iter().enumerate() {
1402 gnc_weights[i] = state.weight(s);
1403 }
1404
1405 // Inner weighted-LS solve at fixed weights (a few LM steps).
1406 let mut lambda = config.initial_lambda.unwrap_or(0.0);
1407 let mut current_cost = self.robust_se3_cost_weighted(&kernel, Some(&gnc_weights));
1408 for _ in 0..gnc.inner_iterations.max(1) {
1409 let (builder, g) = self.assemble_se3_system(
1410 &node_index,
1411 dim,
1412 &kernel,
1413 Some(&gnc_weights),
1414 config.linear_solver,
1415 );
1416 // Marquardt damping scales by the (undamped) curvature, so capture
1417 // the diagonal of H before it is consumed by the solve.
1418 let diag = match config.damping {
1419 DampingMode::Diagonal => Some(builder.diagonal()),
1420 DampingMode::Identity => None,
1421 };
1422 let neg_g = -&g;
1423 let delta = builder.solve(
1424 lambda,
1425 diag.as_deref(),
1426 &neg_g,
1427 &mut order_cache,
1428 &mut symbolic_cache,
1429 )?;
1430
1431 let saved_poses = if config.initial_lambda.is_some() {
1432 Some(self.poses.clone())
1433 } else {
1434 None
1435 };
1436 let mut max_step_norm: f64 = 0.0;
1437 for (&id, &i) in &node_index {
1438 let block = i * 6;
1439 let mut xi = Vector6::<f64>::zeros();
1440 for k in 0..6 {
1441 xi[k] = delta[block + k];
1442 }
1443 max_step_norm = max_step_norm.max(xi.norm());
1444 let pose = self
1445 .poses
1446 .get_mut(&id)
1447 .ok_or(PoseGraphError::MissingNode(id))?;
1448 pose.world_to_camera = pose.world_to_camera.compose(&SE3::exp(&xi));
1449 }
1450
1451 let cost_after = self.robust_se3_cost_weighted(&kernel, Some(&gnc_weights));
1452 let accepted = match config.initial_lambda {
1453 None => true,
1454 Some(_) => cost_after < current_cost,
1455 };
1456 if !accepted {
1457 if let Some(saved) = saved_poses {
1458 self.poses = saved;
1459 }
1460 lambda = (lambda * config.lambda_increase_factor).min(config.max_lambda);
1461 if lambda >= config.max_lambda {
1462 break;
1463 }
1464 continue;
1465 }
1466 current_cost = cost_after;
1467 if config.initial_lambda.is_some() {
1468 lambda = (lambda * config.lambda_decrease_factor).max(config.min_lambda);
1469 }
1470 if max_step_norm < config.step_tolerance {
1471 break;
1472 }
1473 }
1474
1475 if terminal_level {
1476 converged = true;
1477 break;
1478 }
1479 state.anneal();
1480 }
1481
1482 // Final per-edge classification at the converged estimate and μ.
1483 let residuals = self.edge_squared_residuals();
1484 for (i, &s) in residuals.iter().enumerate() {
1485 gnc_weights[i] = state.weight(s);
1486 }
1487 let final_cost = self.robust_se3_cost(&kernel);
1488 // Plain L2 over retained inliers: binarize the weights at the inlier
1489 // cutoff and reuse the weighted cost.
1490 const INLIER_THRESHOLD: f64 = 0.5;
1491 let inlier_mask: Vec<f64> = gnc_weights
1492 .iter()
1493 .map(|&w| if w >= INLIER_THRESHOLD { 1.0 } else { 0.0 })
1494 .collect();
1495 let inlier_cost = self.robust_se3_cost_weighted(&kernel, Some(&inlier_mask));
1496
1497 Ok(PoseGraphGncResult {
1498 anchor_id,
1499 edge_count: self.edges.len(),
1500 variable_count,
1501 initial_cost,
1502 final_cost,
1503 inlier_cost,
1504 inlier_scale,
1505 outer_iterations,
1506 converged,
1507 edge_weights: gnc_weights,
1508 })
1509 }
1510
1511 /// Recover the marginal covariance of every non-anchor pose from the
1512 /// information matrix `Λ = JᵀΩJ` assembled at the *current* estimate (run a
1513 /// solve first so this is the covariance at the optimum). Uses the
1514 /// Takahashi sparse-inverse recursion ([`crate::covariance`]) so the dense
1515 /// `Λ⁻¹` is never formed. Each `Matrix6` is the covariance of that pose in
1516 /// its local SE(3) tangent (the `[ω | ρ]` ordering of
1517 /// [`SE3::log`](visloc_core::geometry::SE3::log)); the gauge-fixed anchor
1518 /// has no free covariance and is omitted from the result.
1519 ///
1520 /// Useful for loop-closure gating (gate a candidate on the relative
1521 /// uncertainty between its endpoints) and uncertainty-aware fusion. Errors
1522 /// mirror the solvers: [`PoseGraphError::NoAnchor`] / `NoEdges` /
1523 /// `NoVariables`, and [`PoseGraphError::SingularSystem`] when `Λ` is not
1524 /// positive-definite (a rank-deficient / disconnected graph).
1525 pub fn pose_marginal_covariances(&self) -> Result<BTreeMap<u64, Matrix6<f64>>, PoseGraphError> {
1526 let anchor_id = self.anchor.ok_or(PoseGraphError::NoAnchor)?;
1527 if !self.poses.contains_key(&anchor_id) {
1528 return Err(PoseGraphError::MissingNode(anchor_id));
1529 }
1530 if self.edges.is_empty() {
1531 return Err(PoseGraphError::NoEdges);
1532 }
1533 // Free-variable indexing (anchor excluded), identical to the solvers.
1534 let mut node_index: BTreeMap<u64, usize> = BTreeMap::new();
1535 for &id in self.poses.keys() {
1536 if id == anchor_id {
1537 continue;
1538 }
1539 let next = node_index.len();
1540 node_index.insert(id, next);
1541 }
1542 let variable_count = node_index.len();
1543 if variable_count == 0 {
1544 return Err(PoseGraphError::NoVariables);
1545 }
1546 let dim = variable_count * 6;
1547
1548 // Assemble the *sparse* information matrix at the current estimate (plain
1549 // L2 — kernel `None`, no GNC weights) as COO triplets, in the same
1550 // free-variable order as `node_index`.
1551 let (builder, _g) = self.assemble_se3_system(
1552 &node_index,
1553 dim,
1554 &RobustKernel::None,
1555 None,
1556 LinearSolver::Sparse,
1557 );
1558 let (triplets, dim) = match builder {
1559 NormalEquations6::Sparse { triplets, dim } => (triplets, dim),
1560 NormalEquations6::Dense(_) => unreachable!("forced the sparse backend above"),
1561 };
1562
1563 // Factor `Λ = L Lᵀ` at 6×6 block granularity in natural order (so block
1564 // column `idx` maps straight back to `node_index`), then recover the
1565 // per-pose marginal blocks with the block Takahashi recursion — `O(nnz)`,
1566 // no dense `Λ` or `Λ⁻¹` ([`crate::covariance::block_takahashi_diagonals`]).
1567 let (col_rows, col_vals, diag_inv) = block_cholesky::factor_blocks(&triplets, dim, 6)
1568 .map_err(|_| PoseGraphError::SingularSystem)?;
1569 let blocks = covariance::block_takahashi_diagonals(&col_rows, &col_vals, &diag_inv)
1570 .ok_or(PoseGraphError::SingularSystem)?;
1571 let mut out = BTreeMap::new();
1572 for (&id, &idx) in &node_index {
1573 let block = &blocks[idx];
1574 out.insert(id, Matrix6::from_fn(|r, c| block[(r, c)]));
1575 }
1576 Ok(out)
1577 }
1578
1579 /// Covariance of the *relative* pose `a → b` implied by the current estimate
1580 /// — the joint marginal of the two pose blocks reduced to their difference
1581 /// (`Σ_aa + Σ_bb − Σ_ab − Σ_abᵀ`, the first-order tangent approximation; see
1582 /// [`covariance::relative_covariance`]). A gauge-fixed anchor endpoint
1583 /// contributes a zero block (its frame is certain), so the relative
1584 /// covariance to the anchor is just the other pose's marginal.
1585 ///
1586 /// This is the prediction covariance a loop-closure innovation is gated
1587 /// against: a candidate asserting a relative pose far outside this
1588 /// uncertainty (a confident-but-wrong place recognition between two
1589 /// well-localized frames) is statistically implausible. Recovers only the
1590 /// two block-columns `Σ[:, a]` and `Σ[:, b]` it needs by solving
1591 /// `Λ Y = [E_a | E_b]` with the sparse block Cholesky (back-substitution,
1592 /// `O(nnz(L))` per column) — the dense `Λ⁻¹` is never formed, so it stays
1593 /// cheap enough for the online gate. Errors mirror
1594 /// [`Self::pose_marginal_covariances`]; also
1595 /// [`PoseGraphError::MissingNode`] when `a` or `b` is absent.
1596 pub fn relative_pose_covariance(&self, a: u64, b: u64) -> Result<Matrix6<f64>, PoseGraphError> {
1597 let anchor_id = self.anchor.ok_or(PoseGraphError::NoAnchor)?;
1598 if !self.poses.contains_key(&anchor_id) {
1599 return Err(PoseGraphError::MissingNode(anchor_id));
1600 }
1601 if !self.poses.contains_key(&a) {
1602 return Err(PoseGraphError::MissingNode(a));
1603 }
1604 if !self.poses.contains_key(&b) {
1605 return Err(PoseGraphError::MissingNode(b));
1606 }
1607 if self.edges.is_empty() {
1608 return Err(PoseGraphError::NoEdges);
1609 }
1610 let mut node_index: BTreeMap<u64, usize> = BTreeMap::new();
1611 for &id in self.poses.keys() {
1612 if id == anchor_id {
1613 continue;
1614 }
1615 let next = node_index.len();
1616 node_index.insert(id, next);
1617 }
1618 let variable_count = node_index.len();
1619 if variable_count == 0 {
1620 return Err(PoseGraphError::NoVariables);
1621 }
1622 let dim = variable_count * 6;
1623
1624 // Assemble the *sparse* normal equations (COO triplets) at the current
1625 // estimate, in the same free-variable order the solvers use.
1626 let (builder, _g) = self.assemble_se3_system(
1627 &node_index,
1628 dim,
1629 &RobustKernel::None,
1630 None,
1631 LinearSolver::Sparse,
1632 );
1633 let (triplets, dim) = match builder {
1634 NormalEquations6::Sparse { triplets, dim } => (triplets, dim),
1635 NormalEquations6::Dense(_) => unreachable!("forced the sparse backend above"),
1636 };
1637
1638 // Recover only the two block-columns of `Σ = Λ⁻¹` we actually need —
1639 // columns `a` and `b` — by solving `Λ Y = [E_a | E_b]` with the block
1640 // Cholesky (back-substitution is `O(nnz(L))` per right-hand side),
1641 // instead of forming the dense inverse. `Y[:, 0..6] = Σ[:, a]` and
1642 // `Y[:, 6..12] = Σ[:, b]`, so every block we need (`Σaa`, `Σbb`, `Σab`,
1643 // `Σba`) is a slice of `Y`. A gauge-fixed anchor endpoint is absent from
1644 // the free variables, so its selector columns stay zero → a zero
1645 // covariance block (its frame is certain), reproducing the dense path.
1646 let ia = node_index.get(&a).copied();
1647 let ib = node_index.get(&b).copied();
1648 let mut selector = DMatrix::<f64>::zeros(dim, 12);
1649 if let Some(idx) = ia {
1650 for k in 0..6 {
1651 selector[(idx * 6 + k, k)] = 1.0;
1652 }
1653 }
1654 if let Some(idx) = ib {
1655 for k in 0..6 {
1656 selector[(idx * 6 + k, 6 + k)] = 1.0;
1657 }
1658 }
1659 let order = reordering::Reordering::fill_reducing(dim, 6, &triplets);
1660 let sigma_cols = solve_normal_equations_sparse_multi(&triplets, dim, 6, &selector, &order)?;
1661
1662 // Read the four 6×6 blocks (anchor endpoint → zero block) and reduce to
1663 // the relative covariance `Σ_rel = Σaa + Σbb − Σab − Σba`.
1664 let read = |rows: Option<usize>, col0: usize| -> Matrix6<f64> {
1665 match rows {
1666 Some(idx) => Matrix6::from_fn(|r, c| sigma_cols[(idx * 6 + r, col0 + c)]),
1667 None => Matrix6::zeros(),
1668 }
1669 };
1670 let saa = read(ia, 0);
1671 let sba = read(ib, 0);
1672 let sab = read(ia, 6);
1673 let sbb = read(ib, 6);
1674 Ok(saa + sbb - sab - sba)
1675 }
1676
1677 /// Marginal *information* (inverse-covariance) of the pose set `keep_ids`:
1678 /// the joint Gaussian information `Λ'` over those poses after marginalizing
1679 /// every other non-anchor pose out of the full information matrix
1680 /// `Λ = JᵀΩJ` (Schur complement, [`crate::marginalization::marginalize`]).
1681 /// The blocks are ordered as `keep_ids`, each a 6-DOF SE(3) tangent block
1682 /// in the same right-perturbation basis the solver uses
1683 /// (`T ← T ∘ exp(δ)`), so `Λ'` is exactly the prior a fixed-lag / sliding-
1684 /// window smoother re-adds when it drops the marginalized states. The
1685 /// gauge-fixed anchor is held (excluded from the variables), so `Λ'`
1686 /// encodes the kept poses' information relative to it.
1687 ///
1688 /// This is the information-form dual of [`Self::pose_marginal_covariances`]:
1689 /// `marginal_information([id])⁻¹` equals pose `id`'s marginal covariance,
1690 /// and the two-pose block inverts to the pair's joint covariance. (Assembles
1691 /// `Λ` densely and Schur-complements it, `O(n³)` — a building block for the
1692 /// windowed smoother, not a per-edge inner loop; the smoother itself will
1693 /// marginalize only the *leaving* states' Markov blanket to stay sparse.)
1694 /// Errors mirror [`Self::pose_marginal_covariances`], plus
1695 /// [`PoseGraphError::MissingNode`] for an absent or anchor `keep` id, and
1696 /// [`PoseGraphError::NoVariables`] when `keep_ids` is empty.
1697 pub fn marginal_information(&self, keep_ids: &[u64]) -> Result<DMatrix<f64>, PoseGraphError> {
1698 let anchor_id = self.anchor.ok_or(PoseGraphError::NoAnchor)?;
1699 if !self.poses.contains_key(&anchor_id) {
1700 return Err(PoseGraphError::MissingNode(anchor_id));
1701 }
1702 if self.edges.is_empty() {
1703 return Err(PoseGraphError::NoEdges);
1704 }
1705 if keep_ids.is_empty() {
1706 return Err(PoseGraphError::NoVariables);
1707 }
1708 // Free-variable indexing (anchor excluded), identical to the solvers.
1709 let mut node_index: BTreeMap<u64, usize> = BTreeMap::new();
1710 for &id in self.poses.keys() {
1711 if id == anchor_id {
1712 continue;
1713 }
1714 let next = node_index.len();
1715 node_index.insert(id, next);
1716 }
1717 let variable_count = node_index.len();
1718 if variable_count == 0 {
1719 return Err(PoseGraphError::NoVariables);
1720 }
1721 let dim = variable_count * 6;
1722
1723 // Scalar dimensions of the kept poses (each pose → its 6 tangent dims),
1724 // in `keep_ids` order — an anchor or absent id is an error.
1725 let mut keep_dims: Vec<usize> = Vec::with_capacity(keep_ids.len() * 6);
1726 for &id in keep_ids {
1727 let idx = node_index
1728 .get(&id)
1729 .copied()
1730 .ok_or(PoseGraphError::MissingNode(id))?;
1731 for k in 0..6 {
1732 keep_dims.push(idx * 6 + k);
1733 }
1734 }
1735
1736 // Dense `Λ` at the current estimate (plain L2), then Schur-complement
1737 // the complement of `keep_dims` out. `η` is unused for the information
1738 // block, so pass zeros.
1739 let (builder, _g) = self.assemble_se3_system(
1740 &node_index,
1741 dim,
1742 &RobustKernel::None,
1743 None,
1744 LinearSolver::Dense,
1745 );
1746 let lambda = match builder {
1747 NormalEquations6::Dense(h) => h,
1748 NormalEquations6::Sparse { .. } => unreachable!("forced the dense backend above"),
1749 };
1750 let eta = DVector::<f64>::zeros(dim);
1751 let (lambda_prime, _eta_prime) = marginalization::marginalize(&lambda, &eta, &keep_dims)
1752 .ok_or(PoseGraphError::SingularSystem)?;
1753 Ok(lambda_prime)
1754 }
1755
1756 /// Marginalize pose `id` out of the graph, replacing it with a dense
1757 /// [`GaussianPrior`] over its Markov blanket — the bounded-cost step of a
1758 /// fixed-lag / sliding-window smoother. The blanket `B` is the set of
1759 /// non-anchor poses sharing an edge or an existing prior with `id`. The new
1760 /// prior is the Schur complement of `id` out of the sub-system built from
1761 /// **only the `id`-incident factors** (edges and priors), so the factors
1762 /// *not* incident to `id` stay in the graph and their information is never
1763 /// double-counted; the prior carries both the curvature `Λ'` and the linear
1764 /// term `b'` (the incident factors' gradient at the current estimate), so the
1765 /// current estimate remains a stationary point of the reduced problem.
1766 ///
1767 /// Linearizes at the *current* estimate, so run a solve first (marginalizing
1768 /// at a converged estimate is exact to first order). Removes `id`'s pose and
1769 /// every edge/prior incident to it. A pose whose only neighbour is the anchor
1770 /// (empty blanket) is simply dropped (its information was purely relative to
1771 /// the fixed gauge). Errors: [`PoseGraphError::NoAnchor`];
1772 /// [`PoseGraphError::MissingNode`] if `id` is absent or is the anchor (not a
1773 /// free variable); [`PoseGraphError::SingularSystem`] if `id`'s information
1774 /// block is rank-deficient (an unconstrained pose cannot be marginalized).
1775 pub fn marginalize_pose(&mut self, id: u64) -> Result<(), PoseGraphError> {
1776 self.marginalize_pose_impl(id, false)
1777 }
1778
1779 /// Like [`Self::marginalize_pose`], but **sparsify** the resulting blanket
1780 /// prior with the KL-optimal Chow-Liu tree
1781 /// ([`crate::sparsification::sparsify_chow_liu`]) instead of keeping the dense
1782 /// clique. The Schur complement couples every blanket pose to every other; the
1783 /// tree approximation keeps only the `N−1` strongest (highest mutual
1784 /// information) couplings, preserving each pose's marginal and the tree-edge
1785 /// pairwise marginals exactly, so a window that marginalizes repeatedly does
1786 /// not accumulate dense priors. Identical to the dense prior when the blanket
1787 /// has ≤ 2 poses (a 2-clique already *is* a tree). Same errors as
1788 /// [`Self::marginalize_pose`].
1789 pub fn marginalize_pose_sparsified(&mut self, id: u64) -> Result<(), PoseGraphError> {
1790 self.marginalize_pose_impl(id, true)
1791 }
1792
1793 fn marginalize_pose_impl(&mut self, id: u64, sparsify: bool) -> Result<(), PoseGraphError> {
1794 let anchor_id = self.anchor.ok_or(PoseGraphError::NoAnchor)?;
1795 if id == anchor_id || !self.poses.contains_key(&id) {
1796 return Err(PoseGraphError::MissingNode(id));
1797 }
1798
1799 // Markov blanket: non-anchor poses sharing an edge or a prior with `id`.
1800 let mut blanket: HashSet<u64> = HashSet::new();
1801 for e in &self.edges {
1802 if e.from == id && e.to != anchor_id {
1803 blanket.insert(e.to);
1804 }
1805 if e.to == id && e.from != anchor_id {
1806 blanket.insert(e.from);
1807 }
1808 }
1809 for p in &self.priors {
1810 if p.ids.contains(&id) {
1811 for &pid in &p.ids {
1812 if pid != id && pid != anchor_id {
1813 blanket.insert(pid);
1814 }
1815 }
1816 }
1817 }
1818 blanket.remove(&id);
1819 let mut b: Vec<u64> = blanket.into_iter().collect();
1820 b.sort_unstable();
1821
1822 // Sub-system over {anchor, id} ∪ B carrying ONLY the id-incident factors,
1823 // assembled at the current estimate; `id` indexed first (its 6 dims are
1824 // the ones marginalized), B after (the kept dims).
1825 let mut sub = PoseGraph::new();
1826 sub.add_pose(anchor_id, self.poses[&anchor_id].clone());
1827 sub.anchor(anchor_id);
1828 sub.add_pose(id, self.poses[&id].clone());
1829 for &bid in &b {
1830 sub.add_pose(bid, self.poses[&bid].clone());
1831 }
1832 for e in &self.edges {
1833 if e.from == id || e.to == id {
1834 sub.edges.push(e.clone());
1835 }
1836 }
1837 for p in &self.priors {
1838 if p.ids.contains(&id) {
1839 sub.priors.push(p.clone());
1840 }
1841 }
1842 let mut node_index: BTreeMap<u64, usize> = BTreeMap::new();
1843 node_index.insert(id, 0);
1844 for (k, &bid) in b.iter().enumerate() {
1845 node_index.insert(bid, k + 1);
1846 }
1847 let dim = (1 + b.len()) * 6;
1848 let (builder, g_sub) = sub.assemble_se3_system(
1849 &node_index,
1850 dim,
1851 &RobustKernel::None,
1852 None,
1853 LinearSolver::Dense,
1854 );
1855 let h_sub = match builder {
1856 NormalEquations6::Dense(h) => h,
1857 NormalEquations6::Sparse { .. } => unreachable!("forced the dense backend above"),
1858 };
1859
1860 // Drop `id` and its incident factors before re-attaching the prior.
1861 self.poses.remove(&id);
1862 self.edges.retain(|e| e.from != id && e.to != id);
1863 self.priors.retain(|p| !p.ids.contains(&id));
1864
1865 if b.is_empty() {
1866 // The state only touched the fixed anchor — nothing to preserve.
1867 return Ok(());
1868 }
1869
1870 // Keep B's dims (indices 6..), marginalize `id`'s dims (0..6).
1871 let keep_dims: Vec<usize> = (0..b.len())
1872 .flat_map(|k| (0..6).map(move |d| (k + 1) * 6 + d))
1873 .collect();
1874 let (lambda_prime, b_prime) = marginalization::marginalize(&h_sub, &g_sub, &keep_dims)
1875 .ok_or(PoseGraphError::SingularSystem)?;
1876 // Optionally sparsify the dense blanket clique to its Chow-Liu tree. The
1877 // prior is in the right-perturbation tangent basis at `linearization`;
1878 // sparsification is a pure transform of (Λ', b') that preserves the
1879 // minimizer e* = −Λ'⁻¹b' (so the linearization is unchanged). Falls back to
1880 // the dense prior if the tree build fails (a well-formed SPD prior won't).
1881 let (information, gradient) = if sparsify {
1882 match crate::sparsification::sparsify_chow_liu(&lambda_prime, &b_prime, 6) {
1883 Some(sp) => (sp.lambda, sp.eta),
1884 None => (lambda_prime, b_prime),
1885 }
1886 } else {
1887 (lambda_prime, b_prime)
1888 };
1889 let linearization: Vec<SE3> = b
1890 .iter()
1891 .map(|bid| self.poses[bid].world_to_camera.clone())
1892 .collect();
1893 self.priors.push(GaussianPrior {
1894 ids: b,
1895 information,
1896 gradient,
1897 linearization,
1898 });
1899 Ok(())
1900 }
1901
1902 /// Sliding-window / fixed-lag driver: [`Self::marginalize_pose`] the oldest
1903 /// non-anchor poses (lowest ids) until at most `window_size` poses remain
1904 /// (the gauge-fixed anchor always among them), keeping the graph — and so the
1905 /// per-solve cost — bounded as keyframes accumulate. Returns the ids
1906 /// marginalized, in removal order (oldest first).
1907 ///
1908 /// Marginalize at a converged estimate (run a solve first): each step is
1909 /// then exact, and because the optimum stays stationary after each removal
1910 /// the chained marginalizations compose without drift — a windowed re-solve
1911 /// reproduces the batch estimate on the retained poses (a test asserts this).
1912 /// No-op when already within the window. Stops early if only the anchor is
1913 /// left. `window_size` is clamped to at least `1` (the anchor). Errors mirror
1914 /// [`Self::marginalize_pose`].
1915 pub fn marginalize_oldest(&mut self, window_size: usize) -> Result<Vec<u64>, PoseGraphError> {
1916 self.marginalize_oldest_impl(window_size, false)
1917 }
1918
1919 /// Like [`Self::marginalize_oldest`], but **sparsify** each blanket prior with
1920 /// its Chow-Liu tree ([`Self::marginalize_pose_sparsified`]) so a long-running
1921 /// window does not accumulate dense priors as it slides — the bounded *and*
1922 /// sparse fixed-lag smoother. Same removal order and errors.
1923 pub fn marginalize_oldest_sparsified(
1924 &mut self,
1925 window_size: usize,
1926 ) -> Result<Vec<u64>, PoseGraphError> {
1927 self.marginalize_oldest_impl(window_size, true)
1928 }
1929
1930 fn marginalize_oldest_impl(
1931 &mut self,
1932 window_size: usize,
1933 sparsify: bool,
1934 ) -> Result<Vec<u64>, PoseGraphError> {
1935 let anchor_id = self.anchor.ok_or(PoseGraphError::NoAnchor)?;
1936 let target = window_size.max(1);
1937 let mut removed = Vec::new();
1938 while self.poses.len() > target {
1939 // Oldest non-anchor pose: the lowest id that is not the anchor
1940 // (`poses` is a `BTreeMap`, so `keys()` ascends).
1941 let Some(&oldest) = self.poses.keys().find(|&&id| id != anchor_id) else {
1942 break; // only the anchor remains
1943 };
1944 self.marginalize_pose_impl(oldest, sparsify)?;
1945 removed.push(oldest);
1946 }
1947 Ok(removed)
1948 }
1949
1950 /// Merge another session's pose graph into this one, welding the two
1951 /// trajectories at a cross-session `bridge` constraint — the core of
1952 /// multi-session / multi-map SLAM (an ORB-SLAM3-Atlas-style weld). `other`'s
1953 /// nodes are relabeled by `id_offset` (which must exceed this graph's largest
1954 /// id so the two id spaces stay disjoint) and rigidly transformed into this
1955 /// graph's world frame, then its edges are spliced in and the `bridge` is
1956 /// added as a loop-closure edge. A joint [`Self::optimize_se3_iterative`]
1957 /// afterwards re-welds the seam.
1958 ///
1959 /// `bridge.from_keyframe_id` is a node of `self`; `bridge.to_keyframe_id` is a
1960 /// node of `other` (its *original*, pre-offset id); `bridge.relative_pose` is
1961 /// the measured relative pose `a → b` (the same `relative_world_to_camera`
1962 /// convention as every edge), e.g. from a cross-session place-recognition
1963 /// match. The alignment is computed so `other`'s bridge node lands exactly at
1964 /// the bridge prediction: each `other` pose `Tₙ` becomes `Tₙ ∘ (T_b⁻¹ ∘ z ∘
1965 /// T_a)`, a right-multiply under which every relative edge measurement is
1966 /// invariant (so `other`'s edges carry over unchanged, only relabeled).
1967 ///
1968 /// This graph's anchor is kept as the merged gauge. Errors:
1969 /// [`PoseGraphError::NoAnchor`] if either graph lacks an anchor;
1970 /// [`PoseGraphError::MissingNode`] if a bridge endpoint is absent or a
1971 /// relabeled id would collide with an existing node. `other` must carry no
1972 /// [`GaussianPrior`]s (a fresh session); priors are not transformed.
1973 pub fn merge_session(
1974 &mut self,
1975 other: &PoseGraph,
1976 id_offset: u64,
1977 bridge: &LoopClosureConstraint,
1978 ) -> Result<(), PoseGraphError> {
1979 self.anchor.ok_or(PoseGraphError::NoAnchor)?;
1980 other.anchor.ok_or(PoseGraphError::NoAnchor)?;
1981 let a = bridge.from_keyframe_id;
1982 let b = bridge.to_keyframe_id;
1983 let t_a = self
1984 .poses
1985 .get(&a)
1986 .ok_or(PoseGraphError::MissingNode(a))?
1987 .world_to_camera
1988 .clone();
1989 let t_b = other
1990 .poses
1991 .get(&b)
1992 .ok_or(PoseGraphError::MissingNode(b))?
1993 .world_to_camera
1994 .clone();
1995
1996 // Right-multiply alignment: Tₙ_new = Tₙ ∘ (T_b⁻¹ ∘ z ∘ T_a). For the
1997 // bridge node b this gives z ∘ T_a, i.e. exactly the bridge prediction.
1998 let rhs = t_b.inverse().compose(&bridge.relative_pose.compose(&t_a));
1999
2000 // Splice the relabeled, transformed nodes (id collision is an error).
2001 for (&id, pose) in &other.poses {
2002 let new_id = id + id_offset;
2003 if self.poses.contains_key(&new_id) {
2004 return Err(PoseGraphError::MissingNode(new_id));
2005 }
2006 self.poses.insert(
2007 new_id,
2008 Pose {
2009 world_to_camera: pose.world_to_camera.compose(&rhs),
2010 },
2011 );
2012 }
2013 // Edge measurements are invariant under the right-multiply, so carry them
2014 // over verbatim, only relabeling endpoints.
2015 for edge in &other.edges {
2016 self.edges.push(PoseGraphEdge {
2017 from: edge.from + id_offset,
2018 to: edge.to + id_offset,
2019 measurement: edge.measurement.clone(),
2020 kind: edge.kind,
2021 weight: edge.weight,
2022 information: edge.information,
2023 });
2024 }
2025 // The weld: a loop-closure edge a → (b + offset) carrying the bridge.
2026 self.edges.push(PoseGraphEdge {
2027 from: a,
2028 to: b + id_offset,
2029 measurement: bridge.relative_pose.clone(),
2030 kind: PoseGraphEdgeKind::LoopClosure,
2031 weight: (bridge.inlier_count as f64).max(1.0),
2032 information: None,
2033 });
2034 Ok(())
2035 }
2036
2037 /// Screen a set of candidate cross-session bridges for mutual consistency
2038 /// before merging, returning the indices (into `candidates`) of the maximum
2039 /// mutually-consistent subset — PCM ([`crate::pcm::maximum_consistent_set`])
2040 /// applied across two sessions, the front-end guard against a wrong
2041 /// cross-session place-recognition match.
2042 ///
2043 /// `candidates[i].from_keyframe_id` is a node of `self`,
2044 /// `candidates[i].to_keyframe_id` a node of `other` (its original, pre-offset
2045 /// id), `relative_pose` the measured `a → b`. Consistency is the PCM cycle
2046 /// `a_k →z_k→ b_k →(other odometry)→ b_l →z_l⁻¹→ a_l →(self odometry)→ a_k ≈
2047 /// I`, evaluated over a *combined* odometry map (this graph's poses ∪
2048 /// `other`'s relabeled by `id_offset`); each leg is a frame-invariant relative
2049 /// pose, so the cycle is well-defined even though the two sessions live in
2050 /// different world frames.
2051 ///
2052 /// Use `cfg.require_individual = false`: the individual odometry self-check is
2053 /// meaningless across sessions (a self node and an other node have no
2054 /// single-session relative pose), so screening rests on pairwise consistency
2055 /// and needs ≥ 2 candidates to bite. A lone candidate is always kept.
2056 pub fn consistent_session_bridges(
2057 &self,
2058 other: &PoseGraph,
2059 id_offset: u64,
2060 candidates: &[LoopClosureConstraint],
2061 cfg: &pcm::PcmConfig,
2062 ) -> Vec<usize> {
2063 if candidates.len() <= 1 {
2064 return (0..candidates.len()).collect();
2065 }
2066 let mut odometry: BTreeMap<u64, SE3> = BTreeMap::new();
2067 for (&id, p) in &self.poses {
2068 odometry.insert(id, p.world_to_camera.clone());
2069 }
2070 for (&id, p) in &other.poses {
2071 odometry.insert(id + id_offset, p.world_to_camera.clone());
2072 }
2073 let measurements: Vec<pcm::LoopMeasurement> = candidates
2074 .iter()
2075 .map(|c| pcm::LoopMeasurement {
2076 from: c.from_keyframe_id,
2077 to: c.to_keyframe_id + id_offset,
2078 relative: c.relative_pose.clone(),
2079 })
2080 .collect();
2081 pcm::maximum_consistent_set(&measurements, &odometry, cfg)
2082 }
2083
2084 /// Serialize this pose graph to a plain-text format. The format is
2085 /// line-oriented and human-readable so it doubles as a debug dump:
2086 ///
2087 /// ```text
2088 /// # visloc-rs PoseGraph v1
2089 /// P <id> <qw> <qx> <qy> <qz> <tx> <ty> <tz>
2090 /// ...
2091 /// A <id>
2092 /// E <from> <to> <kind:0|1> <weight> <qw> <qx> <qy> <qz> <tx> <ty> <tz>
2093 /// ...
2094 /// ```
2095 ///
2096 /// `kind = 0` is `Sequential`, `kind = 1` is `LoopClosure`. Lines
2097 /// starting with `#` and blank lines are ignored on read. Round-trips
2098 /// through [`Self::load_text`] without precision loss within `f64`'s
2099 /// `{:.17e}` representation.
2100 pub fn save_text(&self, path: impl AsRef<std::path::Path>) -> std::io::Result<()> {
2101 let mut text = String::from("# visloc-rs PoseGraph v1\n");
2102 for (id, pose) in self.poses.iter() {
2103 let q = pose.world_to_camera.rotation.into_inner();
2104 let t = &pose.world_to_camera.translation;
2105 text.push_str(&format!(
2106 "P {id} {qw:.17e} {qx:.17e} {qy:.17e} {qz:.17e} {tx:.17e} {ty:.17e} {tz:.17e}\n",
2107 qw = q.w,
2108 qx = q.i,
2109 qy = q.j,
2110 qz = q.k,
2111 tx = t.x,
2112 ty = t.y,
2113 tz = t.z,
2114 ));
2115 }
2116 if let Some(anchor) = self.anchor {
2117 text.push_str(&format!("A {anchor}\n"));
2118 }
2119 for edge in &self.edges {
2120 let kind: u8 = match edge.kind {
2121 PoseGraphEdgeKind::Sequential => 0,
2122 PoseGraphEdgeKind::LoopClosure => 1,
2123 };
2124 let q = edge.measurement.rotation.into_inner();
2125 let t = &edge.measurement.translation;
2126 text.push_str(&format!(
2127 "E {from} {to} {kind} {weight:.17e} {qw:.17e} {qx:.17e} {qy:.17e} {qz:.17e} {tx:.17e} {ty:.17e} {tz:.17e}\n",
2128 from = edge.from, to = edge.to, weight = edge.weight,
2129 qw = q.w, qx = q.i, qy = q.j, qz = q.k, tx = t.x, ty = t.y, tz = t.z,
2130 ));
2131 }
2132 std::fs::write(path, text)
2133 }
2134
2135 /// Inverse of [`Self::save_text`]. Returns `PoseGraphParseError`
2136 /// on syntactic problems (unknown line tag, missing column, bad
2137 /// number, unrecognised kind tag).
2138 pub fn load_text(path: impl AsRef<std::path::Path>) -> Result<Self, PoseGraphParseError> {
2139 let text = std::fs::read_to_string(path).map_err(PoseGraphParseError::Io)?;
2140 let mut graph = PoseGraph::new();
2141 for (lineno, raw) in text.lines().enumerate() {
2142 let line = raw.trim();
2143 if line.is_empty() || line.starts_with('#') {
2144 continue;
2145 }
2146 let mut tok = line.split_ascii_whitespace();
2147 let tag = tok.next().ok_or_else(|| PoseGraphParseError::Syntax {
2148 line: lineno + 1,
2149 reason: "empty line tag".to_string(),
2150 })?;
2151 match tag {
2152 "P" => {
2153 let id = parse_field::<u64>(tok.next(), lineno, "id")?;
2154 let qw = parse_field::<f64>(tok.next(), lineno, "qw")?;
2155 let qx = parse_field::<f64>(tok.next(), lineno, "qx")?;
2156 let qy = parse_field::<f64>(tok.next(), lineno, "qy")?;
2157 let qz = parse_field::<f64>(tok.next(), lineno, "qz")?;
2158 let tx = parse_field::<f64>(tok.next(), lineno, "tx")?;
2159 let ty = parse_field::<f64>(tok.next(), lineno, "ty")?;
2160 let tz = parse_field::<f64>(tok.next(), lineno, "tz")?;
2161 let rot = UnitQuaternion::from_quaternion(Quaternion::new(qw, qx, qy, qz));
2162 let pose = Pose::from_world_to_camera(rot, Vector3::new(tx, ty, tz));
2163 graph.poses.insert(id, pose);
2164 }
2165 "A" => {
2166 let id = parse_field::<u64>(tok.next(), lineno, "anchor id")?;
2167 graph.anchor = Some(id);
2168 }
2169 "E" => {
2170 let from = parse_field::<u64>(tok.next(), lineno, "from")?;
2171 let to = parse_field::<u64>(tok.next(), lineno, "to")?;
2172 let kind_tag = parse_field::<u8>(tok.next(), lineno, "kind")?;
2173 let kind = match kind_tag {
2174 0 => PoseGraphEdgeKind::Sequential,
2175 1 => PoseGraphEdgeKind::LoopClosure,
2176 other => {
2177 return Err(PoseGraphParseError::Syntax {
2178 line: lineno + 1,
2179 reason: format!("unrecognised edge kind tag {other}"),
2180 });
2181 }
2182 };
2183 let weight = parse_field::<f64>(tok.next(), lineno, "weight")?;
2184 let qw = parse_field::<f64>(tok.next(), lineno, "qw")?;
2185 let qx = parse_field::<f64>(tok.next(), lineno, "qx")?;
2186 let qy = parse_field::<f64>(tok.next(), lineno, "qy")?;
2187 let qz = parse_field::<f64>(tok.next(), lineno, "qz")?;
2188 let tx = parse_field::<f64>(tok.next(), lineno, "tx")?;
2189 let ty = parse_field::<f64>(tok.next(), lineno, "ty")?;
2190 let tz = parse_field::<f64>(tok.next(), lineno, "tz")?;
2191 let rot = UnitQuaternion::from_quaternion(Quaternion::new(qw, qx, qy, qz));
2192 graph.edges.push(PoseGraphEdge {
2193 from,
2194 to,
2195 measurement: SE3::new(rot, Vector3::new(tx, ty, tz)),
2196 kind,
2197 weight,
2198 information: None,
2199 });
2200 }
2201 other => {
2202 return Err(PoseGraphParseError::Syntax {
2203 line: lineno + 1,
2204 reason: format!("unknown line tag '{other}'"),
2205 });
2206 }
2207 }
2208 }
2209 Ok(graph)
2210 }
2211}
2212
2213#[derive(Debug)]
2214pub enum PoseGraphParseError {
2215 Io(std::io::Error),
2216 Syntax { line: usize, reason: String },
2217}
2218
2219impl std::fmt::Display for PoseGraphParseError {
2220 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2221 match self {
2222 PoseGraphParseError::Io(e) => write!(f, "I/O error reading pose graph: {e}"),
2223 PoseGraphParseError::Syntax { line, reason } => {
2224 write!(f, "pose graph parse error at line {line}: {reason}")
2225 }
2226 }
2227 }
2228}
2229
2230impl std::error::Error for PoseGraphParseError {
2231 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
2232 match self {
2233 PoseGraphParseError::Io(e) => Some(e),
2234 PoseGraphParseError::Syntax { .. } => None,
2235 }
2236 }
2237}
2238
2239fn parse_field<T: std::str::FromStr>(
2240 field: Option<&str>,
2241 lineno: usize,
2242 name: &str,
2243) -> Result<T, PoseGraphParseError>
2244where
2245 T::Err: std::fmt::Display,
2246{
2247 let s = field.ok_or_else(|| PoseGraphParseError::Syntax {
2248 line: lineno + 1,
2249 reason: format!("missing field '{name}'"),
2250 })?;
2251 s.parse::<T>().map_err(|e| PoseGraphParseError::Syntax {
2252 line: lineno + 1,
2253 reason: format!("bad {name}: {e}"),
2254 })
2255}
2256
2257/// Solve `H · x = b` preferring Cholesky (SPD path) and falling back to LU
2258/// for ill-conditioned or rank-deficient systems.
2259pub(crate) fn solve_normal_equations(
2260 h: &DMatrix<f64>,
2261 b: &DVector<f64>,
2262) -> Result<DVector<f64>, PoseGraphError> {
2263 if let Some(chol) = h.clone().cholesky() {
2264 return Ok(chol.solve(b));
2265 }
2266 h.clone()
2267 .lu()
2268 .solve(b)
2269 .ok_or(PoseGraphError::SingularSystem)
2270}
2271
2272/// Sparse Cholesky solve of `(H + λI) · x = b` where `H` is supplied as
2273/// COO triplets and assumed SPD by construction (it is a sum of `wᵀw` block
2274/// outer products from edge Jacobians). Triplets may contain duplicates;
2275/// they are summed during the COO → CSC conversion.
2276///
2277/// The system is solved in the fill-reducing variable order carried by `order`
2278/// (see the `reordering` module), applied as a symmetric permutation. That keeps
2279/// the Cholesky factor near-banded and prevents the catastrophic fill-in that
2280/// makes poorly-ordered or intrinsically wide 3D pose graphs (e.g.
2281/// `torus`/`sphere`) intractable. The permutation is purely structural and
2282/// deterministic, so the returned solution is unchanged up to floating-point
2283/// summation order. The ordering depends only on the sparsity pattern, so
2284/// callers compute it once and reuse it across iterations.
2285///
2286/// The factorization itself is the block Cholesky (see [`block_cholesky`]):
2287/// `block_size` is the variable-block dimension (6 for SE(3) poses), and the
2288/// permuted system keeps those blocks contiguous, so the factor runs on dense
2289/// `B×B` kernels instead of scalar columns.
2290///
2291/// Returns [`PoseGraphError::SingularSystem`] when the factorization fails
2292/// (e.g., disconnected graph). The damping term `λ` is added to the diagonal
2293/// before factoring, matching the dense LM path's `H + λI` formulation.
2294fn solve_normal_equations_sparse(
2295 triplets: &[(usize, usize, f64)],
2296 dim: usize,
2297 block_size: usize,
2298 b: &DVector<f64>,
2299 lambda: f64,
2300 order: &reordering::Reordering,
2301 symbolic_cache: &mut Option<block_cholesky::BlockSymbolic>,
2302) -> Result<DVector<f64>, PoseGraphError> {
2303 let permuted = order.permute_triplets(triplets);
2304 let rhs_permuted = order.permute_rhs(b);
2305 let rhs = DMatrix::from_column_slice(dim, 1, rhs_permuted.as_slice());
2306 // The permuted sparsity pattern is identical across LM iterations, so the
2307 // block-Cholesky symbolic analysis (and the COO→block assembly) is cached
2308 // and only the numeric refactorization runs after the first solve.
2309 let solution = block_cholesky::solve_spd_block_cached(
2310 symbolic_cache,
2311 &permuted,
2312 dim,
2313 block_size,
2314 &rhs,
2315 lambda,
2316 )
2317 .map_err(|_| PoseGraphError::SingularSystem)?;
2318 let solution_permuted = DVector::from_column_slice(solution.as_slice());
2319 Ok(order.restore_solution(&solution_permuted))
2320}
2321
2322/// Multi-right-hand-side variant of [`solve_normal_equations_sparse`]: factor
2323/// the SPD matrix once and solve every column of `rhs` against it. The chordal
2324/// rotation initializer assembles one normal matrix shared by all three
2325/// rotation columns (`block_size` 3), so a single block factorization amortizes
2326/// over the three solves. The fill-reducing `order` is applied as a symmetric
2327/// permutation exactly as in the single-RHS path; each column is permuted in,
2328/// solved, and restored.
2329fn solve_normal_equations_sparse_multi(
2330 triplets: &[(usize, usize, f64)],
2331 dim: usize,
2332 block_size: usize,
2333 rhs: &DMatrix<f64>,
2334 order: &reordering::Reordering,
2335) -> Result<DMatrix<f64>, PoseGraphError> {
2336 let permuted = order.permute_triplets(triplets);
2337
2338 // Permute every right-hand side into the reordered space, factor once via
2339 // the block Cholesky, and restore each solved column.
2340 let cols = rhs.ncols();
2341 let mut rhs_permuted = DMatrix::<f64>::zeros(dim, cols);
2342 for c in 0..cols {
2343 let column = DVector::from_column_slice(rhs.column(c).as_slice());
2344 rhs_permuted.set_column(c, &order.permute_rhs(&column));
2345 }
2346 let solved = block_cholesky::solve_spd_block(&permuted, dim, block_size, &rhs_permuted, 0.0)
2347 .map_err(|_| PoseGraphError::SingularSystem)?;
2348
2349 let mut out = DMatrix::<f64>::zeros(dim, cols);
2350 for c in 0..cols {
2351 let solved_permuted = DVector::from_column_slice(solved.column(c).as_slice());
2352 out.set_column(c, &order.restore_solution(&solved_permuted));
2353 }
2354 Ok(out)
2355}
2356
2357fn add_block6(h: &mut DMatrix<f64>, row: usize, col: usize, weight: f64, block: &Matrix6<f64>) {
2358 for r in 0..6 {
2359 for c in 0..6 {
2360 h[(row + r, col + c)] += weight * block[(r, c)];
2361 }
2362 }
2363}
2364
2365fn add_segment6(g: &mut DVector<f64>, start: usize, weight: f64, v: &Vector6<f64>) {
2366 for k in 0..6 {
2367 g[start + k] += weight * v[k];
2368 }
2369}
2370
2371/// Add `value · I_3` to the `(start, start)` diagonal block of either a
2372/// dense `H` matrix or a triplet vector. Used by the translation-only
2373/// optimizer where the per-edge contribution to `A^T A` is a scaled
2374/// identity on the diagonal blocks.
2375fn add_diag_block3(
2376 h_dense: &mut Option<DMatrix<f64>>,
2377 triplets: &mut Vec<(usize, usize, f64)>,
2378 start: usize,
2379 value: f64,
2380) {
2381 if let Some(h) = h_dense {
2382 for k in 0..3 {
2383 h[(start + k, start + k)] += value;
2384 }
2385 } else {
2386 for k in 0..3 {
2387 triplets.push((start + k, start + k, value));
2388 }
2389 }
2390}
2391
2392/// Add `value · I_3` to the `(row_start, col_start)` off-diagonal block
2393/// (off-diagonal in the block-of-3 sense — also used when row != col).
2394fn add_offdiag_block3(
2395 h_dense: &mut Option<DMatrix<f64>>,
2396 triplets: &mut Vec<(usize, usize, f64)>,
2397 row_start: usize,
2398 col_start: usize,
2399 value: f64,
2400) {
2401 if let Some(h) = h_dense {
2402 for k in 0..3 {
2403 h[(row_start + k, col_start + k)] += value;
2404 }
2405 } else {
2406 for k in 0..3 {
2407 triplets.push((row_start + k, col_start + k, value));
2408 }
2409 }
2410}
2411
2412/// Add a full (possibly dense) 3×3 `block` at the `(row_start, col_start)`
2413/// position of either a dense `H` or a triplet vector. Used by the chordal
2414/// rotation initializer, whose off-diagonal coupling `-w·R_meas` is a dense
2415/// rotation matrix rather than a scaled identity. Zero entries are skipped in
2416/// the sparse path so the rotation matrices contribute only their nonzeros.
2417fn add_dense_block3(
2418 h_dense: &mut Option<DMatrix<f64>>,
2419 triplets: &mut Vec<(usize, usize, f64)>,
2420 row_start: usize,
2421 col_start: usize,
2422 block: &Matrix3<f64>,
2423) {
2424 if let Some(h) = h_dense {
2425 for r in 0..3 {
2426 for c in 0..3 {
2427 h[(row_start + r, col_start + c)] += block[(r, c)];
2428 }
2429 }
2430 } else {
2431 for r in 0..3 {
2432 for c in 0..3 {
2433 let v = block[(r, c)];
2434 if v != 0.0 {
2435 triplets.push((row_start + r, col_start + c, v));
2436 }
2437 }
2438 }
2439 }
2440}
2441
2442/// Scalar edge weight used by the chordal rotation initializer. For an
2443/// isotropic edge this is just `edge.weight`; for an edge carrying a full 6×6
2444/// information matrix `Ω` (ordered `[ρ; ω]`) it is the mean of the rotational
2445/// diagonal `(Ω₃₃ + Ω₄₄ + Ω₅₅)/3`, i.e. the confidence g2o assigned to the
2446/// rotation block. Negative or non-finite results are clamped to a tiny
2447/// positive weight so the relaxed normal matrix stays positive definite.
2448fn chordal_rotation_weight(edge: &PoseGraphEdge) -> f64 {
2449 let w = match &edge.information {
2450 Some(omega) => (omega[(3, 3)] + omega[(4, 4)] + omega[(5, 5)]) / 3.0,
2451 None => edge.weight,
2452 };
2453 if w.is_finite() && w > 0.0 {
2454 w
2455 } else {
2456 1e-9
2457 }
2458}
2459
2460/// Scalar confidence used by the translation-only chordal seed. The full
2461/// optimizer consumes all of `Ω`; this seed uses the trace of the translation
2462/// block because trace is invariant under a change of 3-D coordinate basis and
2463/// retains uniform information scaling exactly.
2464fn translation_initialization_weight(edge: &PoseGraphEdge) -> f64 {
2465 let w = match &edge.information {
2466 Some(omega) => (omega[(0, 0)] + omega[(1, 1)] + omega[(2, 2)]) / 3.0,
2467 None => edge.weight,
2468 };
2469 if w.is_finite() && w > 0.0 {
2470 w
2471 } else {
2472 1e-9
2473 }
2474}
2475
2476/// Project a 3×3 matrix onto the nearest rotation in `SO(3)` (Frobenius sense)
2477/// via its SVD: `R = U·diag(1, 1, det(UVᵀ))·Vᵀ`. The determinant correction
2478/// guarantees `det(R) = +1` (a proper rotation, never a reflection). Returns
2479/// `None` only when the SVD fails to converge.
2480fn project_to_so3(m: &Matrix3<f64>) -> Option<Matrix3<f64>> {
2481 let svd = m.svd(true, true);
2482 let u = svd.u?;
2483 let v_t = svd.v_t?;
2484 let mut r = u * v_t;
2485 if r.determinant() < 0.0 {
2486 // Flip the sign of the smallest singular direction (the last column of
2487 // U) to turn the reflection into a proper rotation.
2488 let mut u_fixed = u;
2489 for k in 0..3 {
2490 u_fixed[(k, 2)] = -u_fixed[(k, 2)];
2491 }
2492 r = u_fixed * v_t;
2493 }
2494 Some(r)
2495}
2496
2497/// Storage for the SE(3) Gauss-Newton normal-equations matrix `H` that
2498/// dispatches to either a dense [`DMatrix`] or a COO triplet vector backing
2499/// a sparse Cholesky solve. The right-hand side `g` is assembled separately
2500/// (see callers) so this builder stays focused on `H`.
2501enum NormalEquations6 {
2502 Dense(DMatrix<f64>),
2503 Sparse {
2504 triplets: Vec<(usize, usize, f64)>,
2505 dim: usize,
2506 },
2507}
2508
2509impl NormalEquations6 {
2510 fn new(dim: usize, solver: LinearSolver, edge_hint: usize) -> Self {
2511 match solver {
2512 LinearSolver::Dense => Self::Dense(DMatrix::zeros(dim, dim)),
2513 // Each edge contributes up to four 6×6 blocks = 4·36 = 144 entries.
2514 LinearSolver::Sparse => Self::Sparse {
2515 triplets: Vec::with_capacity(edge_hint * 144),
2516 dim,
2517 },
2518 }
2519 }
2520
2521 fn add_block6(&mut self, row: usize, col: usize, weight: f64, block: &Matrix6<f64>) {
2522 match self {
2523 Self::Dense(h) => add_block6(h, row, col, weight, block),
2524 Self::Sparse { triplets, .. } => {
2525 for r in 0..6 {
2526 for c in 0..6 {
2527 triplets.push((row + r, col + c, weight * block[(r, c)]));
2528 }
2529 }
2530 }
2531 }
2532 }
2533
2534 /// Solve the assembled system. For the sparse backend the fill-reducing
2535 /// ordering is computed once into `order_cache` (the sparsity pattern is
2536 /// identical across LM iterations) and reused on subsequent calls.
2537 /// The diagonal of `H` (length `dim`), in the natural (unpermuted) variable
2538 /// order. Used to build the Marquardt damping `λ·diag(H)` and the gain-ratio
2539 /// predicted reduction.
2540 fn diagonal(&self) -> Vec<f64> {
2541 match self {
2542 Self::Dense(h) => (0..h.nrows()).map(|k| h[(k, k)]).collect(),
2543 Self::Sparse { triplets, dim } => {
2544 let mut diag = vec![0.0; *dim];
2545 for &(r, c, v) in triplets {
2546 if r == c {
2547 diag[r] += v;
2548 }
2549 }
2550 diag
2551 }
2552 }
2553 }
2554
2555 /// Solve `(H + D) δ = -g` where the damping `D` is either `λI`
2556 /// (`diag_scale = None`) or `λ·diag(H)` (`diag_scale = Some(diag)`, the
2557 /// per-variable curvature from [`Self::diagonal`]). With `diag_scale = None`
2558 /// and a given `lambda` this is bit-identical to the original solve.
2559 fn solve(
2560 self,
2561 lambda: f64,
2562 diag_scale: Option<&[f64]>,
2563 neg_g: &DVector<f64>,
2564 order_cache: &mut Option<reordering::Reordering>,
2565 symbolic_cache: &mut Option<block_cholesky::BlockSymbolic>,
2566 ) -> Result<DVector<f64>, PoseGraphError> {
2567 match self {
2568 Self::Dense(mut h) => {
2569 let dim = h.nrows();
2570 match diag_scale {
2571 // Marquardt: H + λ·diag(H). Read the original diagonal from
2572 // `diag` (captured before this in-place update) so the scaling
2573 // is by the undamped curvature.
2574 Some(diag) => {
2575 for k in 0..dim {
2576 h[(k, k)] += lambda * diag[k];
2577 }
2578 }
2579 None if lambda > 0.0 => {
2580 for k in 0..dim {
2581 h[(k, k)] += lambda;
2582 }
2583 }
2584 None => {}
2585 }
2586 solve_normal_equations(&h, neg_g)
2587 }
2588 Self::Sparse { mut triplets, dim } => {
2589 // For Marquardt damping, fold λ·diag(H) into the triplets as extra
2590 // diagonal entries and let the factorizer run undamped (λ = 0); the
2591 // sparsity pattern is unchanged (diagonal blocks are always
2592 // present), so the cached symbolic analysis still applies.
2593 let factor_lambda = match diag_scale {
2594 Some(diag) => {
2595 triplets.reserve(dim);
2596 for (k, &d) in diag.iter().enumerate().take(dim) {
2597 triplets.push((k, k, lambda * d));
2598 }
2599 0.0
2600 }
2601 None => lambda,
2602 };
2603 let order = order_cache.get_or_insert_with(|| {
2604 reordering::Reordering::fill_reducing(dim, 6, &triplets)
2605 });
2606 solve_normal_equations_sparse(
2607 &triplets,
2608 dim,
2609 6,
2610 neg_g,
2611 factor_lambda,
2612 order,
2613 symbolic_cache,
2614 )
2615 }
2616 }
2617 }
2618}
2619
2620/// Compute the relative SE3 `previous_to_current` such that
2621/// `to_pose.world_to_camera == relative * from_pose.world_to_camera`. This is
2622/// the same convention used by [`PoseGraphEdge::measurement`].
2623pub fn relative_world_to_camera(from_pose: &Pose, to_pose: &Pose) -> SE3 {
2624 to_pose
2625 .world_to_camera
2626 .compose(&from_pose.world_to_camera.inverse())
2627}
2628/// Translation-only constraint on camera centers in world coordinates implied
2629/// by `measurement` together with `to_pose`'s rotation: `c_to - c_from`
2630/// equals this displacement.
2631fn expected_world_displacement(to_pose: &Pose, measurement: &SE3) -> nalgebra::Vector3<f64> {
2632 let rotation_matrix = to_pose
2633 .world_to_camera
2634 .rotation
2635 .to_rotation_matrix()
2636 .into_inner();
2637 -(rotation_matrix.transpose() * measurement.translation)
2638}