Skip to main content

PoseGraph

Struct PoseGraph 

Source
pub struct PoseGraph {
    pub poses: BTreeMap<u64, Pose>,
    pub edges: Vec<PoseGraphEdge>,
    pub priors: Vec<GaussianPrior>,
    pub anchor: Option<u64>,
}
Expand description

Sparse pose graph keyed by keyframe id. Stores per-node poses plus a flat list of sequential and loop-closure edges, and provides a single translation-only Gauss-Newton step that keeps node rotations fixed.

This is intentionally a skeleton: rotations are not optimized, the solver is a single linear least-squares step rather than an iterative SE3 solver, and there is no incremental incremental map update. Future milestones can extend the same data type with full SE3 Jacobians, robust kernels, or a production solver.

Fields§

§poses: BTreeMap<u64, Pose>

Keyframe id → pose. BTreeMap keeps the iteration order deterministic so the variable layout in the linear system is reproducible.

§edges: Vec<PoseGraphEdge>

Edges in insertion order.

§priors: Vec<GaussianPrior>

Dense Gaussian priors (marginalization factors). Empty for a plain graph, so the solver and cost are bit-identical until a Self::marginalize_pose folds a state into one.

§anchor: Option<u64>

Anchor keyframe id; its pose is held fixed during optimization.

Implementations§

Source§

impl PoseGraph

Source

pub fn new() -> PoseGraph

Source

pub fn add_pose(&mut self, keyframe_id: u64, pose: Pose)

Insert or replace a pose for keyframe_id.

Source

pub const fn anchor(&mut self, keyframe_id: u64)

Designate keyframe_id as the anchor whose pose stays fixed during translation optimization. Replaces any previously selected anchor.

Source

pub fn add_sequential_edge(&mut self, from: u64, to: u64, measurement: SE3)

Add a sequential odometry edge with weight 1.0.

Source

pub fn add_loop_closure_constraint( &mut self, constraint: &LoopClosureConstraint, )

Append a loop-closure constraint as a graph edge. The verifier-derived inlier count is reused as the edge weight (clamped to a minimum of 1.0) so loops with more inliers carry more pull on the solver.

Source

pub fn add_loop_closure_constraint_with_weight( &mut self, constraint: &LoopClosureConstraint, weight: f64, )

Append a loop-closure constraint with an explicit isotropic scalar weight. This is the controlled alternative to interpreting a verifier’s raw inlier count as inverse covariance: correspondence count and pose uncertainty do not share units, and a large count can otherwise make one loop hundreds of times stiffer than every sequential edge. Invalid weights are conservatively replaced by 1.0 so a malformed runtime configuration cannot inject NaNs into the graph.

Source

pub fn add_edge_with_information( &mut self, from: u64, to: u64, measurement: SE3, kind: PoseGraphEdgeKind, information: Matrix<f64, Const<6>, Const<6>, ArrayStorage<f64, 6, 6>>, )

Add an edge carrying a full 6×6 information matrix Ω, ordered [ρ; ω] (translation block first, then rotation — the SE3::log / .g2o EDGE_SE3:QUAT convention). The SE(3) solver minimizes the anisotropic rᵀ Ω r for this edge; the scalar weight is left at 1.0 and unused while information is Some.

Source

pub fn translation_cost(&self) -> f64

Sum of squared edge translation residuals in world coordinates. Rotation residuals are ignored — this is a translation-only metric that matches what Self::optimize_translations_once minimizes.

Source

pub fn optimize_translations_once( &mut self, ) -> Result<PoseGraphOptimizationStep, PoseGraphError>

Solve a single Gauss-Newton step on the translation residuals while holding rotations fixed. With linear-in-translation residuals the “single step” is the exact least-squares optimum of the underlying linear system, not a Newton iteration that needs to be repeated.

Equivalent to Self::optimize_translations_once_with called with LinearSolver::Dense.

Source

pub fn optimize_translations_once_with( &mut self, linear_solver: LinearSolver, ) -> Result<PoseGraphOptimizationStep, PoseGraphError>

Variant of Self::optimize_translations_once that selects the linear-solver backend. Use LinearSolver::Sparse for graphs with hundreds-to-thousands of keyframes — the normal-equations matrix is block-banded with at most four 3×3 blocks per edge, so the sparse block Cholesky is much faster than the dense path and uses dramatically less memory.

Source

pub fn se3_cost(&self) -> f64

Sum of squared SE(3) residuals: r_e = log(meas_e⁻¹ · T_to · T_from⁻¹), weighted by edge.weight. Unlike Self::translation_cost, this includes both the translation and rotation components of every edge.

Source

pub fn robust_se3_cost(&self, kernel: &RobustKernel) -> f64

Robust SE(3) cost: Σ_e edge.weight · ρ(||r_e||²) where ρ is the supplied RobustKernel. With RobustKernel::None this matches Self::se3_cost.

Source

pub fn chordal_rotation_cost(&self) -> f64

Chordal (Frobenius-relaxed) cost of the current node rotations: Σ_e w_e · ‖R_to − R_meas_e · R_from‖_F², where R_* is the rotation of each node’s world_to_camera and R_meas_e the rotation of the edge measurement. This is the objective minimized by Self::initialize_rotations_chordal; unlike Self::se3_cost it ignores translation and uses the chordal (embedded-Euclidean) metric on SO(3) rather than the geodesic one, so it is a convex function of the relaxed (unconstrained 3×3) rotation variables.

Source

pub fn initialize_rotations_chordal( &mut self, linear_solver: LinearSolver, ) -> Result<ChordalRotationInit, PoseGraphError>

Initialize node rotations by solving the chordal relaxation of the rotation-only sub-problem (Carlone et al., “Initialization Techniques for 3D SLAM”, ICRA 2015). On hard 3D datasets the SE(3) cost surface is strongly non-convex in rotation, so a full solve started from raw odometry stalls in a poor basin; seeding it with the chordal solution lands it near the global optimum.

Each edge contributes the residual R_to − R_meas · R_from measured in the embedded-Euclidean (Frobenius) metric. Relaxing every R_i from SO(3) to an unconstrained 3×3 matrix makes the objective a single linear least-squares problem; the per-node 9-vector splits into three independent 3-vector systems (one per rotation column) that share the same 3n × 3n normal matrix — so this factors once and solves three right-hand sides. Each relaxed 3×3 block is then projected back onto SO(3) with an SVD (R = U·diag(1,1,det(UVᵀ))·Vᵀ).

The anchor’s rotation is held fixed (it fixes the global gauge). Each node’s camera center is preserved — only its orientation is replaced — so this is safe to call standalone, though the intended flow is chordal-rotation → Self::optimize_translations_once_with → Self::optimize_se3_iterative.

Source

pub fn optimize_se3_iterative( &mut self, config: &PoseGraphSe3Config, ) -> Result<PoseGraphSe3Result, PoseGraphError>

Run a full SE(3) Gauss-Newton optimization with right-perturbation updates T_i ← T_i · Exp(δ_i). Uses the first-order BCH approximation J_r⁻¹(r) ≈ I, so each edge contributes:

  • residual: r_e = log(meas_e⁻¹ · T_to · T_from⁻¹) (6-vector),
  • Jacobians: ∂r/∂δ_to = Ad(T_from), ∂r/∂δ_from = -Ad(T_from).

The anchor pose is held fixed; all other poses are updated. Returns the per-iteration cost trace plus a converged flag derived from the configured tolerances.

Source

pub fn optimize_se3_gnc( &mut self, config: &PoseGraphSe3Config, gnc: &GncConfig, ) -> Result<PoseGraphGncResult, PoseGraphError>

Outlier-robust SE(3) pose-graph optimization via Graduated Non-Convexity (GNC; see crate::gnc). Use this instead of Self::optimize_se3_iterative when loop closures may be wrong (perceptual aliasing, place-recognition false positives): a single bad loop closure pulls a plain least-squares — or even a Huber/Cauchy IRLS — solve into a corrupted basin, whereas GNC anneals from a convex surrogate that trusts every edge to the true robust cost that rejects outliers, recovering the inlier trajectory.

config supplies the same SE(3) LM settings as Self::optimize_se3_iterative (linear solver, λ schedule, tolerances, chordal seeding); its robust_kernel is ignored — GNC supersedes the M-estimator and the inner solve runs on the GNC-weighted least-squares cost. gnc selects the surrogate family, the inlier scale c, the μ annealing factor, the outer-level cap, and the number of inner LM iterations per level.

Each outer level reweights every edge by its closed-form GNC weight at the current μ, runs a bounded weighted-LS solve, then sharpens μ one geometric step. The fill-reducing order and block-Cholesky symbolic factorization are μ-invariant and reused across all levels. The returned PoseGraphGncResult::edge_weights is the final per-edge inlier/outlier classification.

Source

pub fn pose_marginal_covariances( &self, ) -> Result<BTreeMap<u64, Matrix<f64, Const<6>, Const<6>, ArrayStorage<f64, 6, 6>>>, PoseGraphError>

Recover the marginal covariance of every non-anchor pose from the information matrix Λ = JᵀΩJ assembled at the current estimate (run a solve first so this is the covariance at the optimum). Uses the Takahashi sparse-inverse recursion (crate::covariance) so the dense Λ⁻¹ is never formed. Each Matrix6 is the covariance of that pose in its local SE(3) tangent (the [ω | ρ] ordering of SE3::log); the gauge-fixed anchor has no free covariance and is omitted from the result.

Useful for loop-closure gating (gate a candidate on the relative uncertainty between its endpoints) and uncertainty-aware fusion. Errors mirror the solvers: PoseGraphError::NoAnchor / NoEdges / NoVariables, and PoseGraphError::SingularSystem when Λ is not positive-definite (a rank-deficient / disconnected graph).

Source

pub fn relative_pose_covariance( &self, a: u64, b: u64, ) -> Result<Matrix<f64, Const<6>, Const<6>, ArrayStorage<f64, 6, 6>>, PoseGraphError>

Covariance of the relative pose a → b implied by the current estimate — the joint marginal of the two pose blocks reduced to their difference (Σ_aa + Σ_bb − Σ_ab − Σ_abᵀ, the first-order tangent approximation; see covariance::relative_covariance). A gauge-fixed anchor endpoint contributes a zero block (its frame is certain), so the relative covariance to the anchor is just the other pose’s marginal.

This is the prediction covariance a loop-closure innovation is gated against: a candidate asserting a relative pose far outside this uncertainty (a confident-but-wrong place recognition between two well-localized frames) is statistically implausible. Recovers only the two block-columns Σ[:, a] and Σ[:, b] it needs by solving Λ Y = [E_a | E_b] with the sparse block Cholesky (back-substitution, O(nnz(L)) per column) — the dense Λ⁻¹ is never formed, so it stays cheap enough for the online gate. Errors mirror Self::pose_marginal_covariances; also PoseGraphError::MissingNode when a or b is absent.

Source

pub fn marginal_information( &self, keep_ids: &[u64], ) -> Result<Matrix<f64, Dyn, Dyn, VecStorage<f64, Dyn, Dyn>>, PoseGraphError>

Marginal information (inverse-covariance) of the pose set keep_ids: the joint Gaussian information Λ' over those poses after marginalizing every other non-anchor pose out of the full information matrix Λ = JᵀΩJ (Schur complement, crate::marginalization::marginalize). The blocks are ordered as keep_ids, each a 6-DOF SE(3) tangent block in the same right-perturbation basis the solver uses (T ← T ∘ exp(δ)), so Λ' is exactly the prior a fixed-lag / sliding- window smoother re-adds when it drops the marginalized states. The gauge-fixed anchor is held (excluded from the variables), so Λ' encodes the kept poses’ information relative to it.

This is the information-form dual of Self::pose_marginal_covariances: marginal_information([id])⁻¹ equals pose id‘s marginal covariance, and the two-pose block inverts to the pair’s joint covariance. (Assembles Λ densely and Schur-complements it, O(n³) — a building block for the windowed smoother, not a per-edge inner loop; the smoother itself will marginalize only the leaving states’ Markov blanket to stay sparse.) Errors mirror Self::pose_marginal_covariances, plus PoseGraphError::MissingNode for an absent or anchor keep id, and PoseGraphError::NoVariables when keep_ids is empty.

Source

pub fn marginalize_pose(&mut self, id: u64) -> Result<(), PoseGraphError>

Marginalize pose id out of the graph, replacing it with a dense GaussianPrior over its Markov blanket — the bounded-cost step of a fixed-lag / sliding-window smoother. The blanket B is the set of non-anchor poses sharing an edge or an existing prior with id. The new prior is the Schur complement of id out of the sub-system built from only the id-incident factors (edges and priors), so the factors not incident to id stay in the graph and their information is never double-counted; the prior carries both the curvature Λ' and the linear term b' (the incident factors’ gradient at the current estimate), so the current estimate remains a stationary point of the reduced problem.

Linearizes at the current estimate, so run a solve first (marginalizing at a converged estimate is exact to first order). Removes id’s pose and every edge/prior incident to it. A pose whose only neighbour is the anchor (empty blanket) is simply dropped (its information was purely relative to the fixed gauge). Errors: PoseGraphError::NoAnchor; PoseGraphError::MissingNode if id is absent or is the anchor (not a free variable); PoseGraphError::SingularSystem if id’s information block is rank-deficient (an unconstrained pose cannot be marginalized).

Source

pub fn marginalize_pose_sparsified( &mut self, id: u64, ) -> Result<(), PoseGraphError>

Like Self::marginalize_pose, but sparsify the resulting blanket prior with the KL-optimal Chow-Liu tree (crate::sparsification::sparsify_chow_liu) instead of keeping the dense clique. The Schur complement couples every blanket pose to every other; the tree approximation keeps only the N−1 strongest (highest mutual information) couplings, preserving each pose’s marginal and the tree-edge pairwise marginals exactly, so a window that marginalizes repeatedly does not accumulate dense priors. Identical to the dense prior when the blanket has ≤ 2 poses (a 2-clique already is a tree). Same errors as Self::marginalize_pose.

Source

pub fn marginalize_oldest( &mut self, window_size: usize, ) -> Result<Vec<u64>, PoseGraphError>

Sliding-window / fixed-lag driver: Self::marginalize_pose the oldest non-anchor poses (lowest ids) until at most window_size poses remain (the gauge-fixed anchor always among them), keeping the graph — and so the per-solve cost — bounded as keyframes accumulate. Returns the ids marginalized, in removal order (oldest first).

Marginalize at a converged estimate (run a solve first): each step is then exact, and because the optimum stays stationary after each removal the chained marginalizations compose without drift — a windowed re-solve reproduces the batch estimate on the retained poses (a test asserts this). No-op when already within the window. Stops early if only the anchor is left. window_size is clamped to at least 1 (the anchor). Errors mirror Self::marginalize_pose.

Source

pub fn marginalize_oldest_sparsified( &mut self, window_size: usize, ) -> Result<Vec<u64>, PoseGraphError>

Like Self::marginalize_oldest, but sparsify each blanket prior with its Chow-Liu tree (Self::marginalize_pose_sparsified) so a long-running window does not accumulate dense priors as it slides — the bounded and sparse fixed-lag smoother. Same removal order and errors.

Source

pub fn merge_session( &mut self, other: &PoseGraph, id_offset: u64, bridge: &LoopClosureConstraint, ) -> Result<(), PoseGraphError>

Merge another session’s pose graph into this one, welding the two trajectories at a cross-session bridge constraint — the core of multi-session / multi-map SLAM (an ORB-SLAM3-Atlas-style weld). other’s nodes are relabeled by id_offset (which must exceed this graph’s largest id so the two id spaces stay disjoint) and rigidly transformed into this graph’s world frame, then its edges are spliced in and the bridge is added as a loop-closure edge. A joint Self::optimize_se3_iterative afterwards re-welds the seam.

bridge.from_keyframe_id is a node of self; bridge.to_keyframe_id is a node of other (its original, pre-offset id); bridge.relative_pose is the measured relative pose a → b (the same relative_world_to_camera convention as every edge), e.g. from a cross-session place-recognition match. The alignment is computed so other’s bridge node lands exactly at the bridge prediction: each other pose Tₙ becomes Tₙ ∘ (T_b⁻¹ ∘ z ∘ T_a), a right-multiply under which every relative edge measurement is invariant (so other’s edges carry over unchanged, only relabeled).

This graph’s anchor is kept as the merged gauge. Errors: PoseGraphError::NoAnchor if either graph lacks an anchor; PoseGraphError::MissingNode if a bridge endpoint is absent or a relabeled id would collide with an existing node. other must carry no GaussianPriors (a fresh session); priors are not transformed.

Source

pub fn consistent_session_bridges( &self, other: &PoseGraph, id_offset: u64, candidates: &[LoopClosureConstraint], cfg: &PcmConfig, ) -> Vec<usize>

Screen a set of candidate cross-session bridges for mutual consistency before merging, returning the indices (into candidates) of the maximum mutually-consistent subset — PCM (crate::pcm::maximum_consistent_set) applied across two sessions, the front-end guard against a wrong cross-session place-recognition match.

candidates[i].from_keyframe_id is a node of self, candidates[i].to_keyframe_id a node of other (its original, pre-offset id), relative_pose the measured a → b. Consistency is the PCM cycle a_k →z_k→ b_k →(other odometry)→ b_l →z_l⁻¹→ a_l →(self odometry)→ a_k ≈ I, evaluated over a combined odometry map (this graph’s poses ∪ other’s relabeled by id_offset); each leg is a frame-invariant relative pose, so the cycle is well-defined even though the two sessions live in different world frames.

Use cfg.require_individual = false: the individual odometry self-check is meaningless across sessions (a self node and an other node have no single-session relative pose), so screening rests on pairwise consistency and needs ≥ 2 candidates to bite. A lone candidate is always kept.

Source

pub fn save_text(&self, path: impl AsRef<Path>) -> Result<(), Error>

Serialize this pose graph to a plain-text format. The format is line-oriented and human-readable so it doubles as a debug dump:

# visloc-rs PoseGraph v1
P <id> <qw> <qx> <qy> <qz> <tx> <ty> <tz>
...
A <id>
E <from> <to> <kind:0|1> <weight> <qw> <qx> <qy> <qz> <tx> <ty> <tz>
...

kind = 0 is Sequential, kind = 1 is LoopClosure. Lines starting with # and blank lines are ignored on read. Round-trips through Self::load_text without precision loss within f64’s {:.17e} representation.

Source

pub fn load_text( path: impl AsRef<Path>, ) -> Result<PoseGraph, PoseGraphParseError>

Inverse of Self::save_text. Returns PoseGraphParseError on syntactic problems (unknown line tag, missing column, bad number, unrecognised kind tag).

Trait Implementations§

Source§

impl Clone for PoseGraph

Source§

fn clone(&self) -> PoseGraph

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for PoseGraph

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl Default for PoseGraph

Source§

fn default() -> PoseGraph

Returns the “default value” for a type. Read more
Source§

impl PartialEq for PoseGraph

Source§

fn eq(&self, other: &PoseGraph) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl StructuralPartialEq for PoseGraph

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> Scalar for T
where T: 'static + Clone + PartialEq + Debug,

Source§

impl<SS, SP> SupersetOf<SS> for SP
where SS: SubsetOf<SP>,

Source§

fn to_subset(&self) -> Option<SS>

The inverse inclusion map: attempts to construct self from the equivalent element of its superset. Read more
Source§

fn is_in_subset(&self) -> bool

Checks if self is actually part of its subset T (and can be converted to it).
Source§

fn to_subset_unchecked(&self) -> SS

Use with care! Same as self.to_subset but without any property checks. Always succeeds.
Source§

fn from_subset(element: &SS) -> SP

The inclusion map: converts self to the equivalent element of its superset.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V