Skip to main content

visloc_slam/
online_slam.rs

1//! Online SLAM orchestration: configuration, relocalization / loop-closure
2//! refinement state, IMU coupling, and the [`OnlineSlamPipeline`] itself.
3
4use super::loop_pose_information::estimate_loop_pose_information;
5pub use super::loop_pose_information::{
6    LoopPoseInformationConfig, LoopPoseInformationDiagnostic, LoopPoseInformationFailure,
7    LoopPoseInformationFailureCounts,
8};
9use super::*;
10use crate::imu_preintegration::ImuNoiseModel;
11use std::time::Instant;
12
13#[derive(Debug, Clone, PartialEq)]
14pub struct OnlineSlamConfig {
15    pub apply_map_updates: bool,
16    pub loop_closure: LoopClosureConfig,
17    /// Optional IMU pre-integration hookup. When `Some`, the pipeline accepts
18    /// inter-frame IMU samples via [`OnlineSlamPipeline::push_imu_measurement`]
19    /// and emits an [`ImuPreintegrationFactor`] connecting each adjacent
20    /// keyframe pair on [`OnlineSlamResult::imu_factor`]. The factor is a
21    /// hint for downstream pose-graph / BA consumers; the tracker and local
22    /// mapper themselves remain appearance-driven. `None` (the default)
23    /// keeps the pipeline IMU-free and side-effect-free for existing callers.
24    pub imu: Option<OnlineSlamImuConfig>,
25    /// Optional sliding-window local VI-BA refinement triggered every
26    /// `local_vi_ba.trigger_every` IMU factors. When `Some`, the
27    /// [`crate::OnlineSlamLocalBaState`] table tracks per-keyframe
28    /// `(velocity, bias)` slots and refines the trailing
29    /// [`crate::OnlineSlamLocalBaConfig::window_size`] keyframes' poses +
30    /// landmarks + velocities + biases against the staged
31    /// [`ImuPreintegrationFactor`] history. Requires `imu = Some(_)`;
32    /// when `imu` is `None` (no IMU factors are ever emitted), the local
33    /// VI-BA stage simply never fires. `None` (default) keeps the
34    /// pipeline appearance-only on the critical path.
35    pub local_vi_ba: Option<OnlineSlamLocalBaConfig>,
36    /// Optional visual-only covisibility local BA stage triggered after
37    /// a new keyframe has been applied to the map. Unlike
38    /// [`OnlineSlamLocalBaConfig`], this stage does not require IMU
39    /// factors; it selects high-covisibility neighbor keyframes and
40    /// fixed boundary keyframes around the active keyframe, then runs
41    /// [`crate::refine_visual_map_with_covisibility_ba`]. `None`
42    /// (default) preserves the existing online pipeline behavior.
43    pub covisibility_local_ba: Option<OnlineSlamCovisibilityLocalBaConfig>,
44    /// Optional DROID-style sparse keyframe factor lifecycle. The stage
45    /// proposes temporal, proximity, and stereo edges on each committed
46    /// keyframe, retains inactive edges for broader recovery, and exposes
47    /// optimizer-facing correction/information/damping records. `None`
48    /// preserves the existing pipeline path without graph bookkeeping.
49    pub sparse_factor_graph: Option<SparseFactorGraphConfig>,
50    /// Optional auto-bootstrap stage that runs a
51    /// [`crate::VisualInertialInitializer`] over the pipeline's incoming
52    /// IMU stream and atomically promotes the recovered
53    /// `(R_w←b, b_g, b_a)` into the running pre-integrator + first
54    /// keyframe on the first frame where both (a) `try_initialize` has
55    /// succeeded and (b) a new keyframe was just registered. Requires
56    /// `imu = Some(_)`; the configuration is rejected on
57    /// [`OnlineSlamPipeline::new`] otherwise. `None` (default) keeps the
58    /// pipeline's bias / rotation seeds at whatever the caller passed on
59    /// [`OnlineSlamImuConfig`].
60    pub vi_init: Option<OnlineSlamViInitConfig>,
61    /// Optional motion-based VI init stage that normally fires after `vi_init`
62    /// succeeds and the body has moved enough to give the IMU translational
63    /// excitation. An explicit fallback may instead start from configured IMU
64    /// biases after static initialization gives up. Holds the known-scale
65    /// visual body-pose trajectory fixed while refining per-keyframe velocity
66    /// and a shared `(b_g, b_a)` against IMU pre-integration factors (the
67    /// inertial-only initialization stage; see
68    /// [`crate::vi_motion_initializer`] for the contract). Requires both
69    /// `imu = Some(_)` and `vi_init = Some(_)`; otherwise the config is
70    /// rejected on [`OnlineSlamPipeline::new`]. `None` (default) keeps
71    /// the pipeline at the static-only flavour.
72    pub vi_motion_init: Option<OnlineSlamMotionViInitConfig>,
73    /// When `true`, IMU factors staged on newly-registered keyframes
74    /// flow downstream (into the local-VI-BA factor history and onto
75    /// `OnlineSlamResult.imu_factor`) even while the auto-bootstrap
76    /// stage is still active. The factors carry the caller's
77    /// placeholder bias linearisation; the BA's own Gauss-Newton
78    /// iterations are expected to absorb the resulting initial-cost
79    /// bump. The legacy contract (this flag `false`, the default)
80    /// silently discards every pre-promotion factor and reports the
81    /// count on `discarded_stale_factor_count` for audit, matching
82    /// the conservative "never feed BA a known-bad linearisation"
83    /// posture. Empirically on real EuRoC the strict path leaves
84    /// local-VI-BA with at most one trigger before the visual tracker
85    /// dies on the takeoff transient (see
86    /// `docs/motion_based_vi_alignment.md` §Phase-12); flipping the
87    /// flag recovers the 6–7 pre-promotion factors and lets the
88    /// Phase-9 mirror update the IMU motion model more frequently.
89    pub keep_pre_promotion_imu_factors: bool,
90    /// Optional online loop-closure refinement stage. When `Some`, the
91    /// pipeline mirrors registered keyframe poses into a running
92    /// [`PoseGraph`], runs an [`EssentialMatrixLoopClosureVerifier`] over
93    /// every candidate `detect_loop_closure_candidates` produces, and
94    /// fires [`PoseGraph::optimize_se3_iterative`] whenever
95    /// `trigger_every_new_constraints` fresh verified loop edges have
96    /// accumulated since the last solve. On a successful solve the
97    /// optimised keyframe poses are written back into
98    /// `self.map.keyframes`. `None` (the default) keeps loop-closure
99    /// candidates as the existing diagnostic-only output on
100    /// [`OnlineSlamResult::loop_closure_candidates`] and never modifies
101    /// the map.
102    pub pose_graph_refinement: Option<OnlineSlamLoopClosureRefinementConfig>,
103    /// Optional relocalization-on-tracker-death stage. When `Some`,
104    /// every `process_frame` call whose primary tracker attempt failed
105    /// (`tracking.localization.success == false`) re-runs PnP against
106    /// the full visual map via the stage's owned
107    /// [`LocalizationPipeline`]; if the recovered solution clears the
108    /// stage's acceptance gate, the pipeline overrides the tracker's
109    /// state via [`Tracker::accept_relocalization_result`] and treats
110    /// the frame as a successful `TrackingEvent::Relocalized` event.
111    /// `None` (default) keeps the legacy behaviour where a failed
112    /// `track_frame` call leaves the tracker dead until manual reset.
113    pub relocalization: Option<OnlineSlamRelocalizationConfig>,
114}
115
116impl OnlineSlamConfig {
117    /// Validate cross-field invariants the type system cannot express.
118    /// Called from [`OnlineSlamPipeline::new`]; surfaces the same error
119    /// type to callers that want to validate before constructing a
120    /// pipeline (e.g. CLI front-ends).
121    pub fn validate(&self) -> Result<(), OnlineSlamConfigError> {
122        if let Some(vi_init) = &self.vi_init {
123            let Some(imu) = &self.imu else {
124                return Err(OnlineSlamConfigError::ViInitRequiresImu);
125            };
126            if (vi_init.initializer.gravity_world - imu.gravity_world).norm() > 1.0e-12 {
127                return Err(OnlineSlamConfigError::GravityMismatch {
128                    imu_gravity_world: imu.gravity_world,
129                    vi_init_gravity_world: vi_init.initializer.gravity_world,
130                });
131            }
132        }
133        if let Some(motion) = &self.vi_motion_init {
134            if self.imu.is_none() {
135                return Err(OnlineSlamConfigError::MotionViInitRequiresImu);
136            }
137            if self.vi_init.is_none() {
138                return Err(OnlineSlamConfigError::MotionViInitRequiresStaticViInit);
139            }
140            if (motion.allow_after_static_give_up
141                || motion.allow_from_configured_bias_before_static)
142                && self.vi_init.as_ref().is_some_and(|static_config| {
143                    static_config.on_persistent_rejection != ViInitFallback::KeepExistingSeed
144                })
145            {
146                return Err(OnlineSlamConfigError::MotionViInitAfterGiveUpRequiresKeepExistingSeed);
147            }
148            if let Some(imu) = &self.imu {
149                if (motion.initializer.gravity_world - imu.gravity_world).norm() > 1.0e-12 {
150                    return Err(OnlineSlamConfigError::MotionGravityMismatch {
151                        imu_gravity_world: imu.gravity_world,
152                        motion_gravity_world: motion.initializer.gravity_world,
153                    });
154                }
155            }
156            if self.vi_init.as_ref().is_some_and(|static_config| {
157                motion.initializer.body_to_camera != static_config.body_to_camera
158            }) {
159                return Err(OnlineSlamConfigError::MotionExtrinsicMismatch);
160            }
161        }
162        if self.local_vi_ba.as_ref().is_some_and(|local| {
163            self.vi_init
164                .as_ref()
165                .is_some_and(|static_config| local.body_to_camera != static_config.body_to_camera)
166        }) {
167            return Err(OnlineSlamConfigError::LocalViBaExtrinsicMismatch);
168        }
169        if self.local_vi_ba.as_ref().is_some_and(|local| {
170            let invalid = |(gyro, accel): (f64, f64)| {
171                !gyro.is_finite() || gyro <= 0.0 || !accel.is_finite() || accel <= 0.0
172            };
173            local.bias_random_walk_weights.is_some_and(invalid)
174                || local.bias_random_walk_noise_densities.is_some_and(invalid)
175        }) {
176            return Err(OnlineSlamConfigError::InvalidLocalViBaBiasRandomWalkWeights);
177        }
178        if self
179            .sparse_factor_graph
180            .as_ref()
181            .is_some_and(|config| !config.is_valid())
182        {
183            return Err(OnlineSlamConfigError::InvalidSparseFactorGraphConfig);
184        }
185        Ok(())
186    }
187}
188
189impl Default for OnlineSlamConfig {
190    fn default() -> Self {
191        Self {
192            apply_map_updates: true,
193            loop_closure: LoopClosureConfig::default(),
194            imu: None,
195            local_vi_ba: None,
196            covisibility_local_ba: None,
197            sparse_factor_graph: None,
198            vi_init: None,
199            vi_motion_init: None,
200            keep_pre_promotion_imu_factors: false,
201            pose_graph_refinement: None,
202            relocalization: None,
203        }
204    }
205}
206
207/// Per-session configuration for visual-only covisibility local BA inside
208/// [`OnlineSlamPipeline`].
209#[derive(Debug, Clone, PartialEq)]
210pub struct OnlineSlamCovisibilityLocalBaConfig {
211    /// Minimum number of keyframes in the map before the stage may run.
212    /// Clamped to at least `1`. The default skips the first keyframe so
213    /// startup does not report a predictable "no local landmarks" solve.
214    pub min_keyframes: usize,
215    /// Optional upper map-size bound for the local BA stage. Useful for
216    /// limiting it to early map maturation before global loop refinement
217    /// becomes the primary correction mechanism.
218    pub max_keyframes: Option<usize>,
219    /// Optional sequence-independent activation gate driven by the latest
220    /// motion-VI initializer raw residual rejection. When configured, visual
221    /// BA runs only while motion initialization is pending and all three raw
222    /// residuals are within these coarse conditioning bounds. It stops as
223    /// soon as motion-VI promotion succeeds.
224    pub motion_vi_raw_residual_activation: Option<MotionViRawResidualActivationConfig>,
225    /// Optional bootstrap-support activation gate. The stage runs only when
226    /// the earliest keyframe observes no more than this many landmarks.
227    /// This is evaluated from map evidence, never a sequence identifier.
228    pub max_seed_landmarks_for_activation: Option<usize>,
229    /// Run after every N newly-applied keyframes. Clamped to at least
230    /// `1`; `1` runs on every eligible new keyframe.
231    pub trigger_every_new_keyframes: usize,
232    /// Optional post-solve quality gate. When `Some(r)`, BA runs on a
233    /// cloned map first; if post-BA outlier observations exceed `r` of the
234    /// selected observation count, the clone is discarded and the live map is
235    /// left unchanged. `None` preserves the legacy direct write-back path.
236    pub max_outlier_observation_ratio: Option<f64>,
237    /// Optional post-solve behind-camera degeneracy gate. When `Some(r)`, BA
238    /// runs on a cloned map first; if the fraction of solved optimized
239    /// landmarks that project behind (or onto) an observing optimized camera
240    /// exceeds `r`, the clone is discarded and the live map is left unchanged.
241    /// Targets degenerate/under-constrained solves that would otherwise
242    /// corrupt the map on write-back. `None` (default) leaves this gate off.
243    /// See [`crate::behind_camera_optimized_landmark_ratio`].
244    pub max_behind_camera_landmark_ratio: Option<f64>,
245    /// Optional post-solve fixed-anchor adequacy gate expressed as a ratio.
246    /// When `Some(r)`, the write-back is rejected unless
247    /// `fixed_keyframe_count >= ceil(optimized_keyframe_count * r)`. This is
248    /// the ratio form of the fixed-boundary requirement (the absolute-floor
249    /// form lives on
250    /// [`CovisibilityLocalBaConfig::boundary_support_min_fixed_keyframes`]).
251    /// Evaluated on the selected window after the solve, so diagnostics still
252    /// record what would have been optimized. `None` (default) leaves it off.
253    /// See [`crate::fixed_to_optimized_ratio_satisfied`].
254    pub min_fixed_to_optimized_ratio: Option<f64>,
255    /// Optional maximum camera-centre displacement accepted from one solve.
256    /// Activates clone-and-check transactional write-back when set.
257    pub max_pose_translation_correction_m: Option<f64>,
258    /// Optional maximum rotation change accepted from one solve, in radians.
259    /// Activates clone-and-check transactional write-back when set.
260    pub max_pose_rotation_correction_rad: Option<f64>,
261    /// Window selection, optimizer, robust loss, and outlier handling
262    /// settings for the actual covisibility BA solve.
263    pub ba: CovisibilityLocalBaConfig,
264}
265
266#[derive(Debug, Clone, Copy, PartialEq)]
267pub struct MotionViRawResidualActivationConfig {
268    pub max_rotation_residual_rms_rad: f64,
269    pub max_velocity_residual_rms_mps: f64,
270    pub max_position_residual_rms_meters: f64,
271}
272
273impl Default for OnlineSlamCovisibilityLocalBaConfig {
274    fn default() -> Self {
275        Self {
276            min_keyframes: 2,
277            max_keyframes: None,
278            motion_vi_raw_residual_activation: None,
279            max_seed_landmarks_for_activation: None,
280            trigger_every_new_keyframes: 1,
281            max_outlier_observation_ratio: None,
282            max_behind_camera_landmark_ratio: None,
283            min_fixed_to_optimized_ratio: None,
284            max_pose_translation_correction_m: None,
285            max_pose_rotation_correction_rad: None,
286            ba: CovisibilityLocalBaConfig::default(),
287        }
288    }
289}
290
291/// Per-frame outcome of the visual-only covisibility local BA stage.
292/// Exposed on [`OnlineSlamResult::covisibility_local_ba`]; `Some` only
293/// when the stage was configured, a new keyframe was applied, and the
294/// trigger interval fired.
295#[derive(Debug, Clone, PartialEq)]
296pub struct OnlineSlamCovisibilityLocalBaStats {
297    pub active_keyframe_id: u64,
298    pub map_keyframe_count: usize,
299    /// Active sparse-factor neighbors admitted as variable BA candidates.
300    /// `None` means the sparse graph stage was disabled.
301    pub factor_graph_neighbor_count: Option<usize>,
302    pub elapsed_ms: f64,
303    pub success: bool,
304    pub error: Option<CovisibilityLocalBaError>,
305    pub selection: Option<CovisibilityLocalBaSelection>,
306    pub ba_result: Option<BaResult>,
307    pub mean_reprojection_before_px: Option<f64>,
308    pub mean_reprojection_after_px: Option<f64>,
309    pub max_pose_translation_correction_m: Option<f64>,
310    pub max_pose_rotation_correction_rad: Option<f64>,
311    pub updated_keyframe_count: usize,
312    pub updated_landmark_count: usize,
313    pub outlier_observation_count: usize,
314    pub observation_count: usize,
315    pub outlier_observation_ratio: Option<f64>,
316    pub quality_gate_rejected: bool,
317    pub pose_correction_gate_rejected: bool,
318    pub removed_observation_count: usize,
319}
320
321/// Per-session configuration for the relocalization-on-tracker-death
322/// stage owned by [`OnlineSlamPipeline`]. When attached via
323/// [`OnlineSlamConfig::relocalization`], the pipeline owns a
324/// [`LocalizationPipeline`] and runs it against the full visual map on
325/// every frame whose primary `track_frame` call returned
326/// `localization.success == false`. The recovered solution is accepted
327/// when it clears every gate below; on acceptance, the tracker's history
328/// is overwritten via [`Tracker::accept_relocalization_result`] and the
329/// frame proceeds through the rest of `process_frame` as if primary
330/// tracking had succeeded.
331#[derive(Debug, Clone, PartialEq)]
332pub struct OnlineSlamRelocalizationConfig {
333    /// Minimum inlier count the recovered PnP solution must report. A
334    /// higher bar than the regular tracker's `min_inliers` makes sense
335    /// here because relocalization runs against the full map with no
336    /// motion prior, so false positives are costlier.
337    pub min_inliers: usize,
338    /// Minimum inlier ratio (inliers / correspondences) for acceptance.
339    pub min_inlier_ratio: f64,
340    /// Optional maximum mean reprojection error. `None` disables the
341    /// gate; `Some(px)` rejects solutions with mean reprojection error
342    /// strictly greater than `px`.
343    pub max_mean_reprojection_error: Option<f64>,
344    /// When `Some(radius_m)`, the recovery PnP is run with the
345    /// tracker's per-frame motion prior fed into the localizer's
346    /// pose-prior warm-start path
347    /// ([`FrameLocalizer::localize_frame_with_pose_prior_warm_start_and_descriptor_store`])
348    /// instead of the no-prior global PnP. The radius restricts the
349    /// candidate landmark set to those within `radius_m` of the
350    /// prior's camera centre. Empirically on EuRoC, the no-prior path
351    /// accepts < 0.3 % of recovery attempts because cross-attitude
352    /// HOG descriptor mismatch dominates; threading the prior in
353    /// short-circuits the matcher to the local landmark set + seeds
354    /// RANSAC with the predicted pose, both of which lift recovery
355    /// quality. `None` (default) preserves the no-prior global path
356    /// for callers who explicitly want full-map relocalization.
357    pub pose_prior_candidate_radius_meters: Option<f64>,
358    /// Phase-26 #4a active-frontier submap selection. When
359    /// `Some(window_keyframes)`, the recovery PnP's descriptor store
360    /// is restricted to landmarks observed by any of the most recent
361    /// `window_keyframes` keyframes in the map (i.e., the "active
362    /// frontier" of the current map). `None` (default) preserves the
363    /// Phase-23 #1 full-map behaviour. Empirically on EuRoC (Phase-26
364    /// #2), the full-map recovery PnP accepts wrong-scale solutions
365    /// because the candidate landmark set spans the whole map and
366    /// admits geometrically self-consistent recoveries far from the
367    /// true pose; the active-frontier window targets that failure
368    /// mode by excluding stale landmarks from consideration.
369    pub recent_keyframe_window: Option<usize>,
370    /// Optional covisibility-local recovery descriptor store. When
371    /// `Some(config)`, recovery PnP restricts descriptor matching to
372    /// landmarks observed by the last successful keyframe (or the most
373    /// recent keyframe before it) plus its high-covisibility neighbors.
374    /// This targets full-map ambiguity without requiring a place-
375    /// recognition backend. If the local set cannot be built or is too
376    /// small, recovery falls back to the existing full-map / recent-
377    /// window policy.
378    pub covisibility_local_map: Option<OnlineSlamRelocalizationCovisibilityConfig>,
379    /// Optional appearance-retrieval recovery descriptor store. When
380    /// `Some(config)`, recovery PnP first ranks existing keyframes by
381    /// cosine similarity between the failed frame's mean local descriptor
382    /// and each keyframe's mean local descriptor, then restricts matching
383    /// to landmarks observed by the top retrieved keyframes. This is a
384    /// lightweight place-recognition seed for relocalization; stronger
385    /// learned global descriptors can replace the mean-descriptor signal
386    /// behind the same policy later. `None` (default) keeps the existing
387    /// full-map / recent-window / covisibility policy.
388    pub appearance_retrieval_map: Option<OnlineSlamRelocalizationAppearanceConfig>,
389    /// Phase-26 #4b post-acceptance IMU sanity check. When
390    /// `Some(max_translation_m)`, recoveries that otherwise pass the
391    /// inlier-count / inlier-ratio / reprojection-error gates are
392    /// further rejected if the recovered camera centre is more than
393    /// `max_translation_m` away from the tracker's per-frame motion
394    /// prior's camera centre. `None` (default) preserves the
395    /// Phase-23 #1 no-IMU-sanity-check behaviour. The motivation
396    /// (Phase-26 #2 V1_01 false-positive diagnosis): the recovery
397    /// PnP can land at a wrong-scale solution that is geometrically
398    /// self-consistent but inconsistent with the IMU's belief about
399    /// where the camera is; a coarse translation gate filters out
400    /// those drift-incompatible recoveries cheaply.
401    pub max_translation_from_imu_prediction_meters: Option<f64>,
402    /// Minimum frame-id gap between expensive recovery PnP attempts.
403    /// `1` preserves the original behaviour of trying on every failed
404    /// frame. Larger values throttle global relocalization on long
405    /// sequences where repeated full-map recovery dominates runtime.
406    /// Values below `1` are treated as `1`.
407    pub attempt_interval_frames: u64,
408    /// Optional cap on consecutive failed relocalization attempts while
409    /// the primary tracker remains lost. When `Some(max)`, the
410    /// relocalizer stops running after `max` failed attempts until
411    /// primary tracking or relocalization succeeds again. `None`
412    /// preserves the legacy unbounded retry behaviour.
413    pub max_consecutive_failed_attempts: Option<u64>,
414    /// Optional pose-continuity gate against the last successfully
415    /// tracked/relocalized pose. When `Some(max_m_per_frame)`,
416    /// recoveries that pass the PnP gates are further rejected if the
417    /// camera-centre translation from the last successful pose divided
418    /// by the frame-id gap is greater than `max_m_per_frame`. `None`
419    /// (default) preserves the legacy behaviour. This timestamp-free
420    /// gate is intended for demos / datasets where frame ids are dense
421    /// enough to make "meters per frame" a useful continuity proxy.
422    pub max_translation_per_frame_from_last_success_meters: Option<f64>,
423    /// Optional lower bound on the median-depth ratio between the
424    /// recovered pose and the last successful pose, measured on the
425    /// recovery PnP inlier landmarks:
426    /// `median(depth_recovered(inliers)) / median(depth_last_success(inliers))`.
427    /// `None` disables the lower-bound gate.
428    pub min_inlier_depth_median_ratio_to_last_success: Option<f64>,
429    /// Optional upper bound on the same median-depth ratio. `None`
430    /// disables the upper-bound gate. This is a scale-aware recovery
431    /// sanity check: a PnP solution can be smooth in translation while
432    /// placing the matched map landmarks at an implausibly different
433    /// depth scale.
434    pub max_inlier_depth_median_ratio_to_last_success: Option<f64>,
435    /// Number of consecutive recovery hypotheses that must pass the
436    /// gates before the tracker state is overwritten. `1` preserves
437    /// the legacy immediate-accept behaviour; larger values turn the
438    /// relocalizer into a short confirmation window.
439    pub confirmation_required_recoveries: usize,
440    /// Optional continuity gate between consecutive recovery
441    /// hypotheses in the confirmation window. When `Some(max)`, the
442    /// camera-centre translation from the previous pending recovery to
443    /// the current recovery, divided by frame-id gap, must be <= `max`
444    /// or the confirmation chain restarts at the current recovery.
445    pub confirmation_max_translation_per_frame_meters: Option<f64>,
446}
447
448impl Default for OnlineSlamRelocalizationConfig {
449    fn default() -> Self {
450        Self {
451            min_inliers: 20,
452            min_inlier_ratio: 0.3,
453            max_mean_reprojection_error: Some(8.0),
454            pose_prior_candidate_radius_meters: None,
455            recent_keyframe_window: None,
456            covisibility_local_map: None,
457            appearance_retrieval_map: None,
458            max_translation_from_imu_prediction_meters: None,
459            attempt_interval_frames: 1,
460            max_consecutive_failed_attempts: None,
461            max_translation_per_frame_from_last_success_meters: None,
462            min_inlier_depth_median_ratio_to_last_success: None,
463            max_inlier_depth_median_ratio_to_last_success: None,
464            confirmation_required_recoveries: 1,
465            confirmation_max_translation_per_frame_meters: None,
466        }
467    }
468}
469
470#[derive(Debug, Clone, PartialEq, Eq)]
471pub struct OnlineSlamRelocalizationCovisibilityConfig {
472    /// Cap on number of co-visible neighbor keyframes to include. The
473    /// reference keyframe itself is always included. `None` means no
474    /// cap.
475    pub max_neighbor_keyframes: Option<usize>,
476    /// Minimum shared landmarks required for a neighbor keyframe to
477    /// enter the local descriptor store.
478    pub min_shared_landmarks: usize,
479    /// If the selected descriptor store has fewer descriptors than
480    /// this, fall back to the broader recovery descriptor store.
481    pub min_local_map_landmarks: usize,
482    /// When the covisibility-local store is available but its recovery
483    /// result fails the configured acceptance gates, retry the same
484    /// recovery attempt with the broader full-map / recent-window
485    /// descriptor store. This keeps the local store as a precision
486    /// first pass while preserving recall on frames where the local
487    /// neighbourhood is too narrow.
488    pub fallback_to_broader_store_on_failure: bool,
489    /// Minimum frame-id gap between broader descriptor-store retries
490    /// after a covisibility-local first pass. Values below `1` are
491    /// treated as `1`. This bounds the cost of local-first recovery on
492    /// long dead-tracking stretches.
493    pub broader_store_retry_interval_frames: u64,
494    /// When true, also run the broader descriptor store even if the
495    /// covisibility-local result passed the acceptance gates, then keep
496    /// the accepted result with the stronger inlier/reprojection score.
497    /// Off by default because it roughly doubles recovery-PnP cost.
498    pub compare_broader_store_on_success: bool,
499}
500
501impl Default for OnlineSlamRelocalizationCovisibilityConfig {
502    fn default() -> Self {
503        Self {
504            max_neighbor_keyframes: Some(10),
505            min_shared_landmarks: 15,
506            min_local_map_landmarks: 30,
507            fallback_to_broader_store_on_failure: true,
508            broader_store_retry_interval_frames: 10,
509            compare_broader_store_on_success: false,
510        }
511    }
512}
513
514#[derive(Debug, Clone, PartialEq)]
515pub struct OnlineSlamRelocalizationAppearanceConfig {
516    /// Keep at most this many appearance-nearest keyframes as recovery
517    /// map seeds. Values below `1` are treated as `1`.
518    pub max_keyframes: usize,
519    /// Optional cap for ranked appearance candidates reported through
520    /// [`OnlineSlamRelocalizationStats::appearance_candidates`].
521    /// `None` preserves the recovery-store cap (`max_keyframes`). Set
522    /// this higher than `max_keyframes` to evaluate top-K retrieval
523    /// recall without increasing recovery-PnP cost.
524    pub candidate_log_limit: Option<usize>,
525    /// Minimum cosine similarity between the failed frame's mean local
526    /// descriptor and a keyframe's mean local descriptor.
527    pub min_similarity: f32,
528    /// Exclude keyframes whose frame-id gap to the failed frame is
529    /// smaller than this. This avoids using only near-temporal frames as
530    /// a fake "retrieval" signal. `0` disables the exclusion.
531    pub exclude_recent_frame_gap: u64,
532    /// If the retrieved keyframes observe fewer descriptors than this,
533    /// fall back to the broader recovery descriptor store.
534    pub min_local_map_landmarks: usize,
535    /// Retry the broader full-map / recent-window descriptor store when
536    /// the appearance-retrieval first pass fails the acceptance gates.
537    pub fallback_to_broader_store_on_failure: bool,
538    /// Minimum frame-id gap between broader descriptor-store retries
539    /// after an appearance-retrieval first pass. Values below `1` are
540    /// treated as `1`.
541    pub broader_store_retry_interval_frames: u64,
542    /// When true, also run the broader descriptor store even if the
543    /// appearance-retrieval result passed the gates, then keep the
544    /// accepted result with the stronger inlier/reprojection score.
545    pub compare_broader_store_on_success: bool,
546}
547
548impl Default for OnlineSlamRelocalizationAppearanceConfig {
549    fn default() -> Self {
550        Self {
551            max_keyframes: 5,
552            candidate_log_limit: None,
553            min_similarity: 0.2,
554            exclude_recent_frame_gap: 30,
555            min_local_map_landmarks: 30,
556            fallback_to_broader_store_on_failure: true,
557            broader_store_retry_interval_frames: 10,
558            compare_broader_store_on_success: false,
559        }
560    }
561}
562
563#[derive(Debug, Clone, PartialEq)]
564pub struct OnlineSlamRelocalizationPendingConfirmation {
565    pub frame_id: u64,
566    pub pose: Pose,
567    pub count: usize,
568}
569
570/// Running state for the relocalization-on-tracker-death stage. Lives
571/// on [`OnlineSlamPipeline`] when [`OnlineSlamConfig::relocalization`]
572/// is `Some`. Owns a dedicated [`LocalizationPipeline`] with default
573/// thresholds so the relocalization attempt is independent of the
574/// tracker's own (typically much stricter, motion-prior-dependent)
575/// localization pipeline.
576#[derive(Debug, Clone)]
577pub struct OnlineSlamRelocalizationState {
578    pub config: OnlineSlamRelocalizationConfig,
579    pub localizer: LocalizationPipeline,
580    pub trigger_count: u64,
581    pub success_count: u64,
582    pub consecutive_failed_attempts: u64,
583    pub budget_skip_count: u64,
584    pub last_attempt_frame_id: Option<u64>,
585    pub last_broader_descriptor_store_retry_frame_id: Option<u64>,
586    pub last_success_frame_id: Option<u64>,
587    pub pending_confirmation: Option<OnlineSlamRelocalizationPendingConfirmation>,
588}
589
590impl PartialEq for OnlineSlamRelocalizationState {
591    fn eq(&self, other: &Self) -> bool {
592        // The owned `LocalizationPipeline` does not implement `PartialEq`
593        // (it carries closures + RANSAC RNG state). Compare only the
594        // observable counters + config, matching the convention used by
595        // [`OnlineSlamImuState`] / [`OnlineSlamLocalBaState`].
596        self.config == other.config
597            && self.trigger_count == other.trigger_count
598            && self.success_count == other.success_count
599            && self.consecutive_failed_attempts == other.consecutive_failed_attempts
600            && self.budget_skip_count == other.budget_skip_count
601            && self.last_attempt_frame_id == other.last_attempt_frame_id
602            && self.last_broader_descriptor_store_retry_frame_id
603                == other.last_broader_descriptor_store_retry_frame_id
604            && self.last_success_frame_id == other.last_success_frame_id
605            && self.pending_confirmation == other.pending_confirmation
606    }
607}
608
609impl OnlineSlamRelocalizationState {
610    fn new(config: OnlineSlamRelocalizationConfig) -> Self {
611        Self {
612            config,
613            localizer: LocalizationPipeline::default(),
614            trigger_count: 0,
615            success_count: 0,
616            consecutive_failed_attempts: 0,
617            budget_skip_count: 0,
618            last_attempt_frame_id: None,
619            last_broader_descriptor_store_retry_frame_id: None,
620            last_success_frame_id: None,
621            pending_confirmation: None,
622        }
623    }
624
625    const fn reset(&mut self) {
626        self.trigger_count = 0;
627        self.success_count = 0;
628        self.consecutive_failed_attempts = 0;
629        self.budget_skip_count = 0;
630        self.last_attempt_frame_id = None;
631        self.last_broader_descriptor_store_retry_frame_id = None;
632        self.last_success_frame_id = None;
633        self.pending_confirmation = None;
634    }
635}
636
637/// One appearance-retrieval keyframe candidate considered by the
638/// relocalization recovery path.
639#[derive(Debug, Clone, Copy, PartialEq)]
640pub struct OnlineSlamRelocalizationAppearanceCandidate {
641    pub keyframe_id: u64,
642    pub similarity: f32,
643}
644
645/// Per-frame outcome of the relocalization-on-tracker-death stage.
646/// Exposed on [`OnlineSlamResult::relocalization`]; `Some` only on
647/// frames where the stage actually attempted a recovery (i.e. the
648/// primary tracker returned `success == false` AND the stage was
649/// enabled).
650#[derive(Debug, Clone, PartialEq, Default)]
651pub struct OnlineSlamRelocalizationStats {
652    /// `true` iff the stage ran its localizer this frame.
653    pub attempted: bool,
654    /// `true` iff the recovery localizer produced a successful PnP
655    /// result before the relocalization-specific acceptance gates were
656    /// applied.
657    pub localization_success: bool,
658    /// `true` iff the recovered solution cleared every gate AND the
659    /// tracker accepted it via `accept_relocalization_result`.
660    pub succeeded: bool,
661    /// Inlier count reported by the recovery PnP solve. `0` when the
662    /// localizer returned no solution at all (e.g. zero correspondences).
663    pub inlier_count: usize,
664    /// Inlier ratio reported by the recovery PnP solve.
665    pub inlier_ratio: f64,
666    /// Total correspondence count the recovery PnP solve consumed.
667    pub correspondence_count: usize,
668    /// Mean reprojection error reported by the recovery PnP solve.
669    pub mean_reprojection_error: Option<f64>,
670    /// Camera-centre translation between the last successful tracked
671    /// pose and the recovered pose, if both are available.
672    pub translation_from_last_success_meters: Option<f64>,
673    /// `translation_from_last_success_meters` divided by the frame-id
674    /// gap to the last successful frame, if both are available. This is
675    /// populated even when the optional continuity gate is disabled so
676    /// runners can inspect candidate recoveries before choosing a cap.
677    pub translation_per_frame_from_last_success_meters: Option<f64>,
678    /// Median positive depth of recovery-PnP inlier landmarks under
679    /// the recovered pose.
680    pub inlier_depth_median_meters: Option<f64>,
681    /// Median positive depth of the same inlier landmarks under the
682    /// last successful tracker pose.
683    pub last_success_inlier_depth_median_meters: Option<f64>,
684    /// `inlier_depth_median_meters / last_success_inlier_depth_median_meters`.
685    /// Populated even when the optional depth-ratio gate is disabled.
686    pub inlier_depth_median_ratio_to_last_success: Option<f64>,
687    /// True when the recovered solution cleared the configured PnP,
688    /// IMU, continuity, and depth-ratio gates before the optional
689    /// confirmation window was applied.
690    pub passed_acceptance_gates: bool,
691    /// Current consecutive confirmation count after processing this
692    /// recovery candidate. Zero when the acceptance gates failed.
693    pub confirmation_count: usize,
694    /// Required confirmation count configured for this attempt. Values
695    /// below one are reported as one.
696    pub confirmation_required_count: usize,
697    /// Camera-centre translation per frame between the previous
698    /// pending recovery and this candidate, if a previous pending
699    /// recovery existed.
700    pub confirmation_translation_per_frame_from_previous_meters: Option<f64>,
701    /// Number of descriptors available to the recovery localizer after
702    /// applying any full-map / active-frontier / covisibility-local
703    /// store selection.
704    pub descriptor_store_landmark_count: usize,
705    /// Number of descriptors in the covisibility-local recovery store
706    /// when that store was built.
707    pub covisibility_local_descriptor_store_landmark_count: Option<usize>,
708    /// Number of descriptors in the appearance-retrieval recovery store
709    /// when that store was built and used as the first pass.
710    pub appearance_descriptor_store_landmark_count: Option<usize>,
711    /// Number of descriptors in the broader full-map / recent-window
712    /// recovery store when a broader retry was attempted.
713    pub broader_descriptor_store_landmark_count: Option<usize>,
714    /// True when the recovery attempt tried the covisibility-local
715    /// descriptor store before any optional broader retry.
716    pub tried_covisibility_local_descriptor_store: bool,
717    /// True when the selected recovery result came from the
718    /// covisibility-local descriptor store.
719    pub used_covisibility_local_descriptor_store: bool,
720    /// True when the recovery attempt tried the appearance-retrieval
721    /// descriptor store before any optional broader retry.
722    pub tried_appearance_descriptor_store: bool,
723    /// True when the selected recovery result came from the
724    /// appearance-retrieval descriptor store.
725    pub used_appearance_descriptor_store: bool,
726    /// True when the broader full-map / recent-window descriptor store
727    /// was attempted after a narrow first pass.
728    pub tried_broader_descriptor_store_fallback: bool,
729    /// True when a broader retry would otherwise have run but was
730    /// skipped by `broader_store_retry_interval_frames`.
731    pub broader_descriptor_store_retry_skipped_by_interval: bool,
732    /// True when the selected recovery result came from a broader retry
733    /// rather than the covisibility-local first pass.
734    pub used_broader_descriptor_store_fallback: bool,
735    /// Reference keyframe used for covisibility-local recovery store
736    /// selection.
737    pub covisibility_reference_keyframe_id: Option<u64>,
738    /// Number of keyframes that passed the appearance similarity /
739    /// temporal-gap filters.
740    pub appearance_candidate_keyframe_count: usize,
741    /// Highest appearance similarity among retrieved keyframes.
742    pub appearance_best_similarity: Option<f32>,
743    /// Best retrieved keyframe id by appearance similarity.
744    pub appearance_best_keyframe_id: Option<u64>,
745    /// Top retrieved keyframes retained for the appearance-retrieval
746    /// recovery store, sorted by descending similarity. Empty when the
747    /// appearance policy was disabled or no candidate passed its filters.
748    pub appearance_candidates: Vec<OnlineSlamRelocalizationAppearanceCandidate>,
749}
750
751fn median_positive_depth_for_landmarks(
752    map: &VisualMap,
753    pose: &Pose,
754    landmark_ids: &[u64],
755) -> Option<f64> {
756    let mut depths: Vec<f64> = landmark_ids
757        .iter()
758        .filter_map(|landmark_id| map.landmarks.get(landmark_id))
759        .map(|landmark| pose.transform_world_point(&landmark.position).z)
760        .filter(|depth| depth.is_finite() && *depth > 0.0)
761        .collect();
762    if depths.is_empty() {
763        return None;
764    }
765    depths.sort_by(|left, right| left.total_cmp(right));
766    let mid = depths.len() / 2;
767    if depths.len().is_multiple_of(2) {
768        Some((depths[mid - 1] + depths[mid]) * 0.5)
769    } else {
770        Some(depths[mid])
771    }
772}
773
774fn relocalization_pick_covisibility_reference_keyframe(
775    map: &VisualMap,
776    last_id: u64,
777) -> Option<u64> {
778    if map.keyframes.contains_key(&last_id) {
779        return Some(last_id);
780    }
781    let mut best: Option<u64> = None;
782    for keyframe_id in map.keyframes.keys() {
783        if *keyframe_id > last_id {
784            continue;
785        }
786        match best {
787            None => best = Some(*keyframe_id),
788            Some(current) if *keyframe_id > current => best = Some(*keyframe_id),
789            _ => {}
790        }
791    }
792    best
793}
794
795fn relocalization_covisibility_descriptor_store(
796    map: &VisualMap,
797    reference_keyframe_id: u64,
798    config: &OnlineSlamRelocalizationCovisibilityConfig,
799) -> Option<visloc_core::types::LandmarkDescriptorStore> {
800    let reference_keyframe = map.keyframes.get(&reference_keyframe_id)?;
801    let reference_landmarks: std::collections::HashSet<u64> = reference_keyframe
802        .observations
803        .iter()
804        .map(|observation| observation.landmark_id)
805        .collect();
806    if reference_landmarks.is_empty() {
807        return None;
808    }
809
810    let mut local_landmarks = reference_landmarks.clone();
811    let mut shared_counts: std::collections::HashMap<u64, usize> = std::collections::HashMap::new();
812    for landmark_id in &reference_landmarks {
813        let Some(landmark) = map.landmarks.get(landmark_id) else {
814            continue;
815        };
816        for observation in &landmark.observations {
817            let keyframe_id = observation.frame_id;
818            if keyframe_id == reference_keyframe_id || !map.keyframes.contains_key(&keyframe_id) {
819                continue;
820            }
821            *shared_counts.entry(keyframe_id).or_insert(0) += 1;
822        }
823    }
824
825    let mut ranked_neighbors: Vec<(u64, usize)> = shared_counts
826        .into_iter()
827        .filter(|(_, count)| *count >= config.min_shared_landmarks)
828        .collect();
829    ranked_neighbors.sort_by(|left, right| right.1.cmp(&left.1).then_with(|| left.0.cmp(&right.0)));
830    if let Some(cap) = config.max_neighbor_keyframes {
831        ranked_neighbors.truncate(cap);
832    }
833
834    for (keyframe_id, _) in ranked_neighbors {
835        if let Some(keyframe) = map.keyframes.get(&keyframe_id) {
836            for observation in &keyframe.observations {
837                local_landmarks.insert(observation.landmark_id);
838            }
839        }
840    }
841
842    let mut local_landmark_ids: Vec<u64> = local_landmarks.into_iter().collect();
843    local_landmark_ids.sort_unstable();
844    let mut store = visloc_core::types::LandmarkDescriptorStore::new();
845    for landmark_id in local_landmark_ids {
846        if let Some(descriptor) = map
847            .landmarks
848            .get(&landmark_id)
849            .and_then(|landmark| landmark.descriptor.as_ref())
850        {
851            store.insert(landmark_id, descriptor.clone());
852        }
853    }
854    if store.len() < config.min_local_map_landmarks {
855        return None;
856    }
857    Some(store)
858}
859
860struct RelocalizationAppearanceDescriptorStore {
861    store: visloc_core::types::LandmarkDescriptorStore,
862    candidate_keyframe_count: usize,
863    best_keyframe_id: Option<u64>,
864    best_similarity: Option<f32>,
865    candidates: Vec<OnlineSlamRelocalizationAppearanceCandidate>,
866}
867
868#[derive(Debug, Clone, Copy, PartialEq, Eq)]
869enum RelocalizationDescriptorStoreKind {
870    Broader,
871    CovisibilityLocal,
872    AppearanceRetrieval,
873}
874
875pub(crate) fn relocalization_mean_descriptor(descriptors: &[Vec<f32>]) -> Option<Vec<f32>> {
876    let first = descriptors.first()?;
877    if first.is_empty()
878        || descriptors
879            .iter()
880            .any(|descriptor| descriptor.len() != first.len())
881    {
882        return None;
883    }
884    let mut mean = vec![0.0_f32; first.len()];
885    for descriptor in descriptors {
886        for (acc, value) in mean.iter_mut().zip(descriptor) {
887            *acc += *value;
888        }
889    }
890    let inv_count = 1.0_f32 / descriptors.len() as f32;
891    let mut norm = 0.0_f32;
892    for value in &mut mean {
893        *value *= inv_count;
894        norm += *value * *value;
895    }
896    let norm = norm.sqrt();
897    if norm <= 1.0e-12 {
898        return None;
899    }
900    for value in &mut mean {
901        *value /= norm;
902    }
903    Some(mean)
904}
905
906pub(crate) fn relocalization_descriptor_cosine(left: &[f32], right: &[f32]) -> f32 {
907    if left.len() != right.len() || left.is_empty() {
908        return 0.0;
909    }
910    let dot: f32 = left.iter().zip(right).map(|(l, r)| l * r).sum();
911    let left_norm = left.iter().map(|v| v * v).sum::<f32>().sqrt();
912    let right_norm = right.iter().map(|v| v * v).sum::<f32>().sqrt();
913    if left_norm <= 1.0e-12 || right_norm <= 1.0e-12 {
914        0.0
915    } else {
916        dot / (left_norm * right_norm)
917    }
918}
919
920fn relocalization_appearance_descriptor_store(
921    map: &VisualMap,
922    frame: &Frame,
923    config: &OnlineSlamRelocalizationAppearanceConfig,
924) -> Option<RelocalizationAppearanceDescriptorStore> {
925    let query_descriptor = relocalization_mean_descriptor(&frame.descriptors)?;
926    let mut ranked_keyframes: Vec<(u64, f32)> = Vec::new();
927    for (keyframe_id, keyframe) in &map.keyframes {
928        if *keyframe_id >= frame.id {
929            continue;
930        }
931        if frame.id.saturating_sub(*keyframe_id) < config.exclude_recent_frame_gap {
932            continue;
933        }
934        let Some(keyframe_descriptor) = relocalization_mean_descriptor(&keyframe.frame.descriptors)
935        else {
936            continue;
937        };
938        let similarity = relocalization_descriptor_cosine(&query_descriptor, &keyframe_descriptor);
939        if similarity >= config.min_similarity {
940            ranked_keyframes.push((*keyframe_id, similarity));
941        }
942    }
943    ranked_keyframes.sort_by(|left, right| {
944        right
945            .1
946            .partial_cmp(&left.1)
947            .unwrap_or(std::cmp::Ordering::Equal)
948            .then_with(|| left.0.cmp(&right.0))
949    });
950    let candidate_keyframe_count = ranked_keyframes.len();
951    let best_keyframe_id = ranked_keyframes
952        .first()
953        .map(|(keyframe_id, _)| *keyframe_id);
954    let best_similarity = ranked_keyframes.first().map(|(_, similarity)| *similarity);
955    let recovery_keyframe_count = config.max_keyframes.max(1);
956    let log_keyframe_count = config
957        .candidate_log_limit
958        .unwrap_or(recovery_keyframe_count)
959        .max(1);
960    let candidates: Vec<OnlineSlamRelocalizationAppearanceCandidate> = ranked_keyframes
961        .iter()
962        .take(log_keyframe_count)
963        .map(
964            |(keyframe_id, similarity)| OnlineSlamRelocalizationAppearanceCandidate {
965                keyframe_id: *keyframe_id,
966                similarity: *similarity,
967            },
968        )
969        .collect();
970
971    let mut landmark_ids = std::collections::HashSet::new();
972    for (keyframe_id, _) in ranked_keyframes.iter().take(recovery_keyframe_count) {
973        if let Some(keyframe) = map.keyframes.get(keyframe_id) {
974            for observation in &keyframe.observations {
975                landmark_ids.insert(observation.landmark_id);
976            }
977        }
978    }
979    let mut landmark_ids: Vec<u64> = landmark_ids.into_iter().collect();
980    landmark_ids.sort_unstable();
981    let mut store = visloc_core::types::LandmarkDescriptorStore::new();
982    for landmark_id in landmark_ids {
983        if let Some(descriptor) = map
984            .landmarks
985            .get(&landmark_id)
986            .and_then(|landmark| landmark.descriptor.as_ref())
987        {
988            store.insert(landmark_id, descriptor.clone());
989        }
990    }
991    if store.len() < config.min_local_map_landmarks {
992        return None;
993    }
994    Some(RelocalizationAppearanceDescriptorStore {
995        store,
996        candidate_keyframe_count,
997        best_keyframe_id,
998        best_similarity,
999        candidates,
1000    })
1001}
1002
1003/// Build a [`visloc_core::types::LandmarkDescriptorStore`] scoped to a
1004/// single keyframe's own observed landmarks (no covisible-neighbor
1005/// expansion). Used by [`build_appearance_loop_candidates`] to restrict
1006/// descriptor-based correspondence building to exactly the candidate
1007/// keyframe's landmarks, since appearance candidates by construction share
1008/// no landmark ids with the current frame. Returns `None` when the
1009/// keyframe has no observations at all.
1010pub fn appearance_loop_candidate_descriptor_store(
1011    map: &VisualMap,
1012    keyframe: &Keyframe,
1013) -> Option<visloc_core::types::LandmarkDescriptorStore> {
1014    let mut landmark_ids: Vec<u64> = keyframe
1015        .observations
1016        .iter()
1017        .map(|observation| observation.landmark_id)
1018        .collect();
1019    landmark_ids.sort_unstable();
1020    landmark_ids.dedup();
1021    if landmark_ids.is_empty() {
1022        return None;
1023    }
1024    let mut store = visloc_core::types::LandmarkDescriptorStore::new();
1025    for landmark_id in landmark_ids {
1026        if let Some(descriptor) = map
1027            .landmarks
1028            .get(&landmark_id)
1029            .and_then(|landmark| landmark.descriptor.as_ref())
1030        {
1031            store.insert(landmark_id, descriptor.clone());
1032        }
1033    }
1034    Some(store)
1035}
1036
1037fn keyframes_ranked_by_covisibility(
1038    map: &VisualMap,
1039    seed_keyframe_id: u64,
1040    min_shared_landmarks: usize,
1041    max_keyframes: usize,
1042) -> Vec<u64> {
1043    let Some(seed) = map.keyframes.get(&seed_keyframe_id) else {
1044        return Vec::new();
1045    };
1046    let seed_landmarks: std::collections::HashSet<_> = seed
1047        .observations
1048        .iter()
1049        .map(|observation| observation.landmark_id)
1050        .collect();
1051    let mut ranked: Vec<(u64, usize)> = map
1052        .keyframes
1053        .iter()
1054        .filter(|(keyframe_id, _)| **keyframe_id != seed_keyframe_id)
1055        .filter_map(|(keyframe_id, keyframe)| {
1056            let shared = keyframe
1057                .observations
1058                .iter()
1059                .filter(|observation| seed_landmarks.contains(&observation.landmark_id))
1060                .count();
1061            (shared >= min_shared_landmarks.max(1)).then_some((*keyframe_id, shared))
1062        })
1063        .collect();
1064    ranked.sort_by(|left, right| right.1.cmp(&left.1).then_with(|| left.0.cmp(&right.0)));
1065    ranked.truncate(max_keyframes);
1066    ranked
1067        .into_iter()
1068        .map(|(keyframe_id, _)| keyframe_id)
1069        .collect()
1070}
1071
1072fn appearance_loop_region_descriptor_store(
1073    map: &VisualMap,
1074    keyframe_ids: &[u64],
1075) -> visloc_core::types::LandmarkDescriptorStore {
1076    let mut landmark_ids = std::collections::BTreeSet::new();
1077    for keyframe_id in keyframe_ids {
1078        if let Some(keyframe) = map.keyframes.get(keyframe_id) {
1079            landmark_ids.extend(
1080                keyframe
1081                    .observations
1082                    .iter()
1083                    .map(|observation| observation.landmark_id),
1084            );
1085        }
1086    }
1087    let mut store = visloc_core::types::LandmarkDescriptorStore::new();
1088    for landmark_id in landmark_ids {
1089        if let Some(descriptor) = map
1090            .landmarks
1091            .get(&landmark_id)
1092            .and_then(|landmark| landmark.descriptor.as_ref())
1093        {
1094            store.insert(landmark_id, descriptor.clone());
1095        }
1096    }
1097    store
1098}
1099
1100/// Rank the cached per-keyframe mean descriptors in `descriptor_cache` by
1101/// cosine similarity against `query_descriptor`, keeping only entries
1102/// strictly older than `frame_id` and at least `min_keyframe_id_gap`
1103/// keyframe-ids older. Ties broken by ascending keyframe id for
1104/// determinism. Shared between [`build_appearance_loop_candidates`] and its
1105/// unit tests.
1106fn rank_appearance_loop_candidate_keyframes(
1107    descriptor_cache: &HashMap<u64, Vec<f32>>,
1108    frame_id: u64,
1109    query_descriptor: &[f32],
1110    min_similarity: f32,
1111    min_keyframe_id_gap: u64,
1112) -> Vec<(u64, f32)> {
1113    let mut ranked: Vec<(u64, f32)> = descriptor_cache
1114        .iter()
1115        .filter(|(&keyframe_id, _)| {
1116            keyframe_id < frame_id && frame_id.saturating_sub(keyframe_id) >= min_keyframe_id_gap
1117        })
1118        .map(|(&keyframe_id, descriptor)| {
1119            (
1120                keyframe_id,
1121                relocalization_descriptor_cosine(query_descriptor, descriptor),
1122            )
1123        })
1124        .filter(|(_, similarity)| *similarity >= min_similarity)
1125        .collect();
1126    ranked.sort_by(|left, right| {
1127        right
1128            .1
1129            .partial_cmp(&left.1)
1130            .unwrap_or(std::cmp::Ordering::Equal)
1131            .then_with(|| left.0.cmp(&right.0))
1132    });
1133    ranked
1134}
1135
1136/// Build and PnP-verify appearance-based long-range loop-closure candidates
1137/// for `frame` against the per-keyframe mean descriptors cached in
1138/// `descriptor_cache` (see
1139/// [`OnlineSlamLoopClosureRefinementState::appearance_descriptor_cache`]).
1140///
1141/// Ranks past keyframes at least `config.min_keyframe_id_gap` keyframe-ids
1142/// older than `frame.id` by cosine similarity of their cached mean
1143/// descriptor against `frame`'s mean descriptor (reusing the same
1144/// `relocalization_mean_descriptor` / `relocalization_descriptor_cosine`
1145/// machinery [`OnlineSlamRelocalizationAppearanceConfig`]'s retrieval store
1146/// uses), keeps the top `config.max_candidates_per_frame`, and for each one:
1147///
1148/// 1. builds a [`visloc_core::types::LandmarkDescriptorStore`] scoped to
1149///    that keyframe's own observed landmarks
1150///    ([`appearance_loop_candidate_descriptor_store`]);
1151/// 2. builds 2D-3D correspondences by matching `frame`'s descriptors
1152///    against that store via
1153///    [`visloc_localization::CorrespondenceBuilder`] — descriptor
1154///    appearance alone, since appearance candidates share no landmark ids
1155///    with `frame` by construction;
1156/// 3. runs [`PnPLoopClosureVerifier`] (configured by `config.pnp_verifier`)
1157///    on the resulting correspondences against the candidate keyframe's
1158///    stored pose.
1159///
1160/// Returns one [`LoopClosureCandidate`] per candidate keyframe that passed
1161/// the PnP verifier's acceptance gates, with `verification` populated —
1162/// ready for [`LoopClosureConstraint::from_verified_candidate`], the same
1163/// as the shared-landmark detector's output. Candidates without a stored
1164/// pose, without a viable descriptor store (fewer than
1165/// `config.min_candidate_landmark_count` descriptors), or without a
1166/// correspondence match are silently skipped.
1167#[derive(Debug, Clone, PartialEq, Default)]
1168pub struct AppearanceLoopCandidateBuildResult {
1169    pub candidates: Vec<LoopClosureCandidate>,
1170    pub connected_region_rejected_count: usize,
1171    pub pnp_verified_count: usize,
1172    pub projection_rejected_count: usize,
1173    pub covisibility_rejected_count: usize,
1174    pub diagnostics: Vec<AppearanceLoopCandidateDiagnostic>,
1175}
1176
1177/// Per-candidate evidence retained after primary PnP succeeds, so threshold
1178/// changes can be based on measured covisibility support rather than only an
1179/// aggregate accept/reject count.
1180#[derive(Debug, Clone, PartialEq)]
1181pub struct AppearanceLoopCandidateDiagnostic {
1182    pub query_frame_id: u64,
1183    pub matched_keyframe_id: u64,
1184    pub appearance_similarity: f32,
1185    pub matched_region_keyframe_count: usize,
1186    pub matched_region_landmark_count: usize,
1187    pub primary_correspondence_count: usize,
1188    pub primary_inlier_count: usize,
1189    pub projection_attempted: bool,
1190    pub projection_correspondence_count: usize,
1191    pub projection_inlier_count: usize,
1192    pub projection_accepted: bool,
1193    pub current_covisible_keyframe_count: usize,
1194    pub neighbor_pnp_verified_count: usize,
1195    pub consistent_keyframe_count: usize,
1196    pub minimum_translation_disagreement_meters: Option<f64>,
1197    pub minimum_rotation_disagreement_radians: Option<f64>,
1198    pub accepted: bool,
1199}
1200
1201pub fn build_appearance_loop_candidates(
1202    map: &VisualMap,
1203    frame: &Frame,
1204    descriptor_cache: &HashMap<u64, Vec<f32>>,
1205    config: &LoopAppearanceCandidateConfig,
1206    camera: &Camera,
1207) -> Vec<LoopClosureCandidate> {
1208    build_appearance_loop_candidates_with_diagnostics(map, frame, descriptor_cache, config, camera)
1209        .candidates
1210}
1211
1212pub fn build_appearance_loop_candidates_with_diagnostics(
1213    map: &VisualMap,
1214    frame: &Frame,
1215    descriptor_cache: &HashMap<u64, Vec<f32>>,
1216    config: &LoopAppearanceCandidateConfig,
1217    camera: &Camera,
1218) -> AppearanceLoopCandidateBuildResult {
1219    let Some(query_descriptor) = relocalization_mean_descriptor(&frame.descriptors) else {
1220        return AppearanceLoopCandidateBuildResult::default();
1221    };
1222    let mut ranked = rank_appearance_loop_candidate_keyframes(
1223        descriptor_cache,
1224        frame.id,
1225        &query_descriptor,
1226        config.min_similarity,
1227        config.min_keyframe_id_gap,
1228    );
1229    ranked.truncate(config.max_candidates_per_frame.max(1));
1230
1231    let query = visloc_core::types::QueryImage::from_frame(frame, camera.clone());
1232    let matcher = visloc_vision::matching::BruteForceMatcher::default();
1233    let correspondence_builder = visloc_localization::CorrespondenceBuilder::new(matcher);
1234    let verifier = PnPLoopClosureVerifier {
1235        ransac: PnPRansac::default(),
1236        config: config.pnp_verifier,
1237    };
1238
1239    let mut result = AppearanceLoopCandidateBuildResult::default();
1240    let current_connected_keyframes: std::collections::HashSet<u64> =
1241        keyframes_ranked_by_covisibility(
1242            map,
1243            frame.id,
1244            config.covisibility_min_shared_landmarks,
1245            usize::MAX,
1246        )
1247        .into_iter()
1248        .chain(std::iter::once(frame.id))
1249        .collect();
1250    for (keyframe_id, similarity) in ranked {
1251        let Some(keyframe) = map.keyframes.get(&keyframe_id) else {
1252            continue;
1253        };
1254        let Some(keyframe_pose) = keyframe.frame.pose.as_ref() else {
1255            continue;
1256        };
1257        let mut matched_region_keyframe_ids = vec![keyframe_id];
1258        matched_region_keyframe_ids.extend(keyframes_ranked_by_covisibility(
1259            map,
1260            keyframe_id,
1261            config.covisibility_min_shared_landmarks,
1262            config.covisibility_max_keyframes,
1263        ));
1264        if matched_region_keyframe_ids
1265            .iter()
1266            .any(|keyframe_id| current_connected_keyframes.contains(keyframe_id))
1267        {
1268            result.connected_region_rejected_count += 1;
1269            continue;
1270        }
1271        let store = appearance_loop_region_descriptor_store(map, &matched_region_keyframe_ids);
1272        if store.len() < config.min_candidate_landmark_count {
1273            continue;
1274        }
1275        let Ok(mut correspondence_set) = correspondence_builder.build(&query, map, &store) else {
1276            continue;
1277        };
1278        let (mut verification, mut pnp_inlier_indices) = verifier.verify_with_inlier_indices(
1279            &correspondence_set.correspondences,
1280            keyframe_pose,
1281            camera,
1282        );
1283        if !verification.verified {
1284            continue;
1285        }
1286        result.pnp_verified_count += 1;
1287        let primary_correspondence_count = verification.correspondence_count;
1288        let primary_inlier_count = verification.inlier_count;
1289        let mut projection_attempted = false;
1290        let mut projection_correspondence_count = 0usize;
1291        let mut projection_inlier_count = 0usize;
1292        let mut projection_accepted = false;
1293        if let Some(search_radius_px) = config.projection_search_radius_px {
1294            projection_attempted = true;
1295            if let Some(primary_relative_pose) = verification.relative_pose.as_ref() {
1296                let recovered_current_pose = Pose {
1297                    world_to_camera: primary_relative_pose.compose(&keyframe_pose.world_to_camera),
1298                };
1299                let projection_builder = visloc_localization::ProjectionCorrespondenceBuilder::new(
1300                    visloc_vision::matching::BruteForceMatcher::default(),
1301                );
1302                if let Ok(projected_set) = projection_builder.build_with_pose_prior(
1303                    &query,
1304                    map,
1305                    &store,
1306                    &recovered_current_pose,
1307                    search_radius_px,
1308                ) {
1309                    projection_correspondence_count = projected_set.correspondences.len();
1310                    if projection_correspondence_count >= config.min_projection_correspondence_count
1311                    {
1312                        let (projected_verification, projected_inlier_indices) = verifier
1313                            .verify_with_inlier_indices(
1314                                &projected_set.correspondences,
1315                                keyframe_pose,
1316                                camera,
1317                            );
1318                        projection_inlier_count = projected_verification.inlier_count;
1319                        if projected_verification.verified {
1320                            projection_accepted = true;
1321                            correspondence_set = projected_set;
1322                            verification = projected_verification;
1323                            pnp_inlier_indices = projected_inlier_indices;
1324                        }
1325                    }
1326                }
1327            }
1328        }
1329        let required_verifications = config.min_covisible_keyframe_verifications.max(1);
1330        let mut region_verifications = 1usize;
1331        let current_covisible_keyframe_ids = keyframes_ranked_by_covisibility(
1332            map,
1333            frame.id,
1334            config.covisibility_min_shared_landmarks,
1335            config.covisibility_max_keyframes,
1336        );
1337        let mut diagnostic = AppearanceLoopCandidateDiagnostic {
1338            query_frame_id: frame.id,
1339            matched_keyframe_id: keyframe_id,
1340            appearance_similarity: similarity,
1341            matched_region_keyframe_count: matched_region_keyframe_ids.len(),
1342            matched_region_landmark_count: store.len(),
1343            primary_correspondence_count,
1344            primary_inlier_count,
1345            projection_attempted,
1346            projection_correspondence_count,
1347            projection_inlier_count,
1348            projection_accepted,
1349            current_covisible_keyframe_count: current_covisible_keyframe_ids.len(),
1350            neighbor_pnp_verified_count: 0,
1351            consistent_keyframe_count: 1,
1352            minimum_translation_disagreement_meters: None,
1353            minimum_rotation_disagreement_radians: None,
1354            accepted: false,
1355        };
1356        if projection_attempted && !projection_accepted {
1357            result.projection_rejected_count += 1;
1358            result.diagnostics.push(diagnostic);
1359            continue;
1360        }
1361        if required_verifications > 1 {
1362            let Some(primary_relative_pose) = verification.relative_pose.as_ref() else {
1363                result.covisibility_rejected_count += 1;
1364                result.diagnostics.push(diagnostic);
1365                continue;
1366            };
1367            let Some(current_pose) = map
1368                .keyframes
1369                .get(&frame.id)
1370                .and_then(|keyframe| keyframe.frame.pose.as_ref())
1371            else {
1372                result.covisibility_rejected_count += 1;
1373                result.diagnostics.push(diagnostic);
1374                continue;
1375            };
1376            for current_neighbor_id in current_covisible_keyframe_ids {
1377                let Some(current_neighbor) = map.keyframes.get(&current_neighbor_id) else {
1378                    continue;
1379                };
1380                let neighbor_query = visloc_core::types::QueryImage::from_frame(
1381                    &current_neighbor.frame,
1382                    camera.clone(),
1383                );
1384                let Ok(neighbor_correspondences) =
1385                    correspondence_builder.build(&neighbor_query, map, &store)
1386                else {
1387                    continue;
1388                };
1389                let neighbor_verification = verifier.verify(
1390                    &neighbor_correspondences.correspondences,
1391                    keyframe_pose,
1392                    camera,
1393                );
1394                if neighbor_verification.verified {
1395                    diagnostic.neighbor_pnp_verified_count += 1;
1396                    let Some(neighbor_relative_pose) = neighbor_verification.relative_pose.as_ref()
1397                    else {
1398                        continue;
1399                    };
1400                    let Some(neighbor_pose) = current_neighbor.frame.pose.as_ref() else {
1401                        continue;
1402                    };
1403                    let current_to_neighbor = relative_world_to_camera(current_pose, neighbor_pose);
1404                    let expected_neighbor_relative =
1405                        current_to_neighbor.compose(primary_relative_pose);
1406                    let disagreement =
1407                        neighbor_relative_pose.compose(&expected_neighbor_relative.inverse());
1408                    let translation_disagreement = disagreement.translation.norm();
1409                    let rotation_disagreement = disagreement.rotation.angle();
1410                    diagnostic.minimum_translation_disagreement_meters = Some(
1411                        diagnostic
1412                            .minimum_translation_disagreement_meters
1413                            .map_or(translation_disagreement, |value| {
1414                                value.min(translation_disagreement)
1415                            }),
1416                    );
1417                    diagnostic.minimum_rotation_disagreement_radians = Some(
1418                        diagnostic
1419                            .minimum_rotation_disagreement_radians
1420                            .map_or(rotation_disagreement, |value| {
1421                                value.min(rotation_disagreement)
1422                            }),
1423                    );
1424                    if translation_disagreement
1425                        <= config.max_covisibility_translation_disagreement_meters
1426                        && rotation_disagreement
1427                            <= config.max_covisibility_rotation_disagreement_radians
1428                    {
1429                        region_verifications += 1;
1430                        diagnostic.consistent_keyframe_count = region_verifications;
1431                    }
1432                    if region_verifications >= required_verifications {
1433                        break;
1434                    }
1435                }
1436            }
1437        }
1438        if region_verifications < required_verifications {
1439            result.covisibility_rejected_count += 1;
1440            result.diagnostics.push(diagnostic);
1441            continue;
1442        }
1443        diagnostic.accepted = true;
1444        result.diagnostics.push(diagnostic);
1445        result.candidates.push(LoopClosureCandidate {
1446            query_frame_id: frame.id,
1447            matched_keyframe_id: keyframe_id,
1448            shared_landmark_count: verification.inlier_count,
1449            query_inlier_count: verification.inlier_count,
1450            keyframe_observation_count: correspondence_set.candidate_landmark_count,
1451            shared_landmark_ratio: verification.inlier_ratio,
1452            score: f64::from(similarity) * verification.score,
1453            geometrically_verified: true,
1454            verification: Some(verification),
1455            pnp_query_landmark_pairs: pnp_inlier_indices
1456                .into_iter()
1457                .filter_map(|index| {
1458                    Some((
1459                        *correspondence_set.query_indices.get(index)?,
1460                        *correspondence_set.landmark_ids.get(index)?,
1461                    ))
1462                })
1463                .collect(),
1464        });
1465    }
1466    result
1467}
1468
1469fn appearance_regions_overlap(
1470    map: &VisualMap,
1471    left_keyframe_id: u64,
1472    right_keyframe_id: u64,
1473    config: &LoopAppearanceCandidateConfig,
1474) -> bool {
1475    if left_keyframe_id == right_keyframe_id {
1476        return true;
1477    }
1478    let mut left_region = keyframes_ranked_by_covisibility(
1479        map,
1480        left_keyframe_id,
1481        config.covisibility_min_shared_landmarks,
1482        config.covisibility_max_keyframes,
1483    );
1484    left_region.push(left_keyframe_id);
1485    let right_region: std::collections::HashSet<u64> = keyframes_ranked_by_covisibility(
1486        map,
1487        right_keyframe_id,
1488        config.covisibility_min_shared_landmarks,
1489        config.covisibility_max_keyframes,
1490    )
1491    .into_iter()
1492    .chain(std::iter::once(right_keyframe_id))
1493    .collect();
1494    left_region
1495        .iter()
1496        .any(|keyframe_id| right_region.contains(keyframe_id))
1497}
1498
1499#[derive(Debug, Clone, PartialEq, Default)]
1500struct AppearancePendingProjectionResult {
1501    attempted: bool,
1502    search_radius_px: Option<f64>,
1503    correspondence_count: usize,
1504    inlier_count: usize,
1505    candidate: Option<LoopClosureCandidate>,
1506}
1507
1508/// Carry an already verified appearance region into the next keyframe by
1509/// projection matching under the pending region's recovered pose plus the
1510/// intervening odometry motion. This is the temporal-consistency step: later
1511/// confirmations do not depend on independently retrieving the same place by
1512/// a global descriptor again.
1513fn verify_pending_appearance_region_by_projection(
1514    map: &VisualMap,
1515    frame: &Frame,
1516    camera: &Camera,
1517    config: &LoopAppearanceCandidateConfig,
1518    pending: &AppearancePendingRegion,
1519) -> AppearancePendingProjectionResult {
1520    let Some(search_radius_px) = config.projection_search_radius_px else {
1521        return AppearancePendingProjectionResult::default();
1522    };
1523    let Some(root_keyframe) = map.keyframes.get(&pending.root_keyframe_id) else {
1524        return AppearancePendingProjectionResult::default();
1525    };
1526    let Some(root_pose) = root_keyframe.frame.pose.as_ref() else {
1527        return AppearancePendingProjectionResult::default();
1528    };
1529    let Some(last_current_pose) = map
1530        .keyframes
1531        .get(&pending.last_current_keyframe_id)
1532        .and_then(|keyframe| keyframe.frame.pose.as_ref())
1533    else {
1534        return AppearancePendingProjectionResult::default();
1535    };
1536    let Some(current_pose) = map
1537        .keyframes
1538        .get(&frame.id)
1539        .and_then(|keyframe| keyframe.frame.pose.as_ref())
1540    else {
1541        return AppearancePendingProjectionResult::default();
1542    };
1543
1544    let mut region_keyframe_ids = vec![pending.root_keyframe_id];
1545    region_keyframe_ids.extend(keyframes_ranked_by_covisibility(
1546        map,
1547        pending.root_keyframe_id,
1548        config.covisibility_min_shared_landmarks,
1549        config.covisibility_max_keyframes,
1550    ));
1551    let store = appearance_loop_region_descriptor_store(map, &region_keyframe_ids);
1552    if store.len() < config.min_candidate_landmark_count {
1553        return AppearancePendingProjectionResult::default();
1554    }
1555
1556    let last_to_current = relative_world_to_camera(last_current_pose, current_pose);
1557    let predicted_root_to_current = last_to_current.compose(&pending.root_to_last_current);
1558    let predicted_current_pose = Pose {
1559        world_to_camera: predicted_root_to_current.compose(&root_pose.world_to_camera),
1560    };
1561    let query = visloc_core::types::QueryImage::from_frame(frame, camera.clone());
1562    let mut result = AppearancePendingProjectionResult {
1563        attempted: true,
1564        ..AppearancePendingProjectionResult::default()
1565    };
1566    let verifier = PnPLoopClosureVerifier {
1567        ransac: PnPRansac::default(),
1568        config: config.pnp_verifier,
1569    };
1570    let mut radii = [
1571        (search_radius_px / 3.0).max(1.0),
1572        (search_radius_px * 2.0 / 3.0).max(1.0),
1573        search_radius_px,
1574    ];
1575    radii.sort_by(f64::total_cmp);
1576    let mut previous_radius: Option<f64> = None;
1577    let mut best_ratio = -1.0_f64;
1578    for radius in radii {
1579        if previous_radius.is_some_and(|previous| (radius - previous).abs() <= f64::EPSILON) {
1580            continue;
1581        }
1582        previous_radius = Some(radius);
1583        let projection_builder = visloc_localization::ProjectionCorrespondenceBuilder::new(
1584            visloc_vision::matching::BruteForceMatcher::default(),
1585        );
1586        let Ok(correspondence_set) = projection_builder.build_with_pose_prior(
1587            &query,
1588            map,
1589            &store,
1590            &predicted_current_pose,
1591            radius,
1592        ) else {
1593            continue;
1594        };
1595        let correspondence_count = correspondence_set.correspondences.len();
1596        if correspondence_count < config.min_projection_correspondence_count {
1597            if result.search_radius_px.is_none() {
1598                result.search_radius_px = Some(radius);
1599                result.correspondence_count = correspondence_count;
1600            }
1601            continue;
1602        }
1603        let (verification, pnp_inlier_indices) = verifier.verify_with_inlier_indices(
1604            &correspondence_set.correspondences,
1605            root_pose,
1606            camera,
1607        );
1608        let ratio = if correspondence_count == 0 {
1609            0.0
1610        } else {
1611            verification.inlier_count as f64 / correspondence_count as f64
1612        };
1613        if ratio > best_ratio
1614            || (ratio == best_ratio && verification.inlier_count > result.inlier_count)
1615        {
1616            best_ratio = ratio;
1617            result.search_radius_px = Some(radius);
1618            result.correspondence_count = correspondence_count;
1619            result.inlier_count = verification.inlier_count;
1620        }
1621        if !verification.verified {
1622            continue;
1623        }
1624        result.search_radius_px = Some(radius);
1625        result.correspondence_count = correspondence_count;
1626        result.inlier_count = verification.inlier_count;
1627        result.candidate = Some(LoopClosureCandidate {
1628            query_frame_id: frame.id,
1629            matched_keyframe_id: pending.root_keyframe_id,
1630            shared_landmark_count: verification.inlier_count,
1631            query_inlier_count: verification.inlier_count,
1632            keyframe_observation_count: correspondence_set.candidate_landmark_count,
1633            shared_landmark_ratio: verification.inlier_ratio,
1634            score: verification.score,
1635            geometrically_verified: true,
1636            verification: Some(verification),
1637            pnp_query_landmark_pairs: pnp_inlier_indices
1638                .into_iter()
1639                .filter_map(|index| {
1640                    Some((
1641                        *correspondence_set.query_indices.get(index)?,
1642                        *correspondence_set.landmark_ids.get(index)?,
1643                    ))
1644                })
1645                .collect(),
1646        });
1647        break;
1648    }
1649    result
1650}
1651
1652fn confirm_appearance_region_across_keyframes(
1653    map: &VisualMap,
1654    current_keyframe_id: u64,
1655    candidates: Vec<LoopClosureCandidate>,
1656    config: &LoopAppearanceCandidateConfig,
1657    pending: &mut Option<AppearancePendingRegion>,
1658) -> (Vec<LoopClosureCandidate>, bool, bool) {
1659    let required = config.region_confirmation_required_keyframes.max(1);
1660    if required == 1 {
1661        *pending = None;
1662        return (candidates, false, false);
1663    }
1664
1665    let Some(current_pose) = map
1666        .keyframes
1667        .get(&current_keyframe_id)
1668        .and_then(|keyframe| keyframe.frame.pose.as_ref())
1669    else {
1670        *pending = None;
1671        return (Vec::new(), false, false);
1672    };
1673
1674    if pending.is_none() {
1675        let Some(candidate) = candidates
1676            .into_iter()
1677            .max_by(|left, right| left.score.total_cmp(&right.score))
1678        else {
1679            return (Vec::new(), false, false);
1680        };
1681        let Some(relative_pose) = candidate
1682            .verification
1683            .as_ref()
1684            .and_then(|verification| verification.relative_pose.clone())
1685        else {
1686            return (Vec::new(), false, false);
1687        };
1688        *pending = Some(AppearancePendingRegion {
1689            root_keyframe_id: candidate.matched_keyframe_id,
1690            last_current_keyframe_id: current_keyframe_id,
1691            root_to_last_current: relative_pose,
1692            confirmation_count: 1,
1693            miss_count: 0,
1694        });
1695        return (Vec::new(), true, false);
1696    }
1697
1698    let state = pending.as_mut().expect("pending region checked above");
1699    let matching_candidate = candidates.into_iter().find(|candidate| {
1700        appearance_regions_overlap(
1701            map,
1702            state.root_keyframe_id,
1703            candidate.matched_keyframe_id,
1704            config,
1705        )
1706    });
1707    let Some(candidate) = matching_candidate else {
1708        state.miss_count += 1;
1709        if state.miss_count >= config.region_confirmation_max_misses.max(1) {
1710            *pending = None;
1711        }
1712        return (Vec::new(), true, false);
1713    };
1714
1715    let recovered_candidate_to_current = candidate
1716        .verification
1717        .as_ref()
1718        .and_then(|verification| verification.relative_pose.as_ref());
1719    let root_pose = map
1720        .keyframes
1721        .get(&state.root_keyframe_id)
1722        .and_then(|keyframe| keyframe.frame.pose.as_ref());
1723    let candidate_pose = map
1724        .keyframes
1725        .get(&candidate.matched_keyframe_id)
1726        .and_then(|keyframe| keyframe.frame.pose.as_ref());
1727    let last_current_pose = map
1728        .keyframes
1729        .get(&state.last_current_keyframe_id)
1730        .and_then(|keyframe| keyframe.frame.pose.as_ref());
1731    let Some((recovered_candidate_to_current, root_pose, candidate_pose, last_current_pose)) =
1732        recovered_candidate_to_current
1733            .zip(root_pose)
1734            .zip(candidate_pose)
1735            .zip(last_current_pose)
1736            .map(|(((a, b), c), d)| (a, b, c, d))
1737    else {
1738        *pending = None;
1739        return (Vec::new(), false, false);
1740    };
1741
1742    let root_to_candidate = relative_world_to_camera(root_pose, candidate_pose);
1743    let recovered_root_to_current = recovered_candidate_to_current.compose(&root_to_candidate);
1744    let last_to_current = relative_world_to_camera(last_current_pose, current_pose);
1745    let predicted_root_to_current = last_to_current.compose(&state.root_to_last_current);
1746    let disagreement = recovered_root_to_current.compose(&predicted_root_to_current.inverse());
1747    let consistent = disagreement.translation.norm()
1748        <= config.max_covisibility_translation_disagreement_meters
1749        && disagreement.rotation.angle() <= config.max_covisibility_rotation_disagreement_radians;
1750    if !consistent {
1751        state.miss_count += 1;
1752        if state.miss_count >= config.region_confirmation_max_misses.max(1) {
1753            *pending = None;
1754        }
1755        return (Vec::new(), true, false);
1756    }
1757
1758    state.confirmation_count += 1;
1759    state.miss_count = 0;
1760    state.last_current_keyframe_id = current_keyframe_id;
1761    state.root_to_last_current = recovered_root_to_current;
1762    if state.confirmation_count < required {
1763        return (Vec::new(), true, false);
1764    }
1765    *pending = None;
1766    (vec![candidate], false, true)
1767}
1768
1769fn relocalization_recent_keyframe_descriptor_store(
1770    map: &VisualMap,
1771    recent_keyframe_window: Option<usize>,
1772) -> visloc_core::types::LandmarkDescriptorStore {
1773    match recent_keyframe_window {
1774        Some(window) if window > 0 => {
1775            let mut keyframe_ids: Vec<u64> = map.keyframes.keys().copied().collect();
1776            keyframe_ids.sort();
1777            let start = keyframe_ids.len().saturating_sub(window);
1778            let mut active_landmark_ids: std::collections::HashSet<u64> =
1779                std::collections::HashSet::new();
1780            for keyframe_id in &keyframe_ids[start..] {
1781                if let Some(keyframe) = map.keyframes.get(keyframe_id) {
1782                    for observation in &keyframe.observations {
1783                        active_landmark_ids.insert(observation.landmark_id);
1784                    }
1785                }
1786            }
1787            let mut store = visloc_core::types::LandmarkDescriptorStore::new();
1788            let mut landmark_ids: Vec<u64> = active_landmark_ids.into_iter().collect();
1789            landmark_ids.sort_unstable();
1790            for landmark_id in landmark_ids {
1791                if let Some(descriptor) = map
1792                    .landmarks
1793                    .get(&landmark_id)
1794                    .and_then(|landmark| landmark.descriptor.as_ref())
1795                {
1796                    store.insert(landmark_id, descriptor.clone());
1797                }
1798            }
1799            store
1800        }
1801        _ => visloc_core::types::LandmarkDescriptorStore::from_visual_map(map),
1802    }
1803}
1804
1805fn relocalization_result_has_better_score(
1806    candidate: &visloc_core::types::LocalizationResult,
1807    incumbent: &visloc_core::types::LocalizationResult,
1808) -> bool {
1809    candidate.inlier_count > incumbent.inlier_count
1810        || (candidate.inlier_count == incumbent.inlier_count
1811            && match (candidate.reprojection_error, incumbent.reprojection_error) {
1812                (Some(candidate_error), Some(incumbent_error)) => candidate_error < incumbent_error,
1813                (Some(_), None) => true,
1814                _ => false,
1815            })
1816}
1817
1818/// Which geometric verifier [`OnlineSlamLoopClosureRefinementConfig`] runs
1819/// on loop-closure candidates every frame.
1820///
1821/// - `EssentialMatrix` (the default) mirrors the original online-refinement
1822///   behaviour byte-for-byte: candidates are verified on 2D-2D
1823///   correspondences via [`EssentialMatrixLoopClosureVerifier`] using
1824///   `verifier_config`. Two-view essential-matrix geometry leaves
1825///   translation scale unobservable, so every accepted constraint's
1826///   translation is pinned to
1827///   `verifier_config.default_translation_scale` regardless of the true
1828///   relative translation norm — acceptable for topology-only pose-graph
1829///   corrections, but it actively corrupts the trajectory's metric scale
1830///   when the true baseline differs.
1831/// - `Pnp` verifies each candidate on 2D-3D correspondences instead: the
1832///   current frame's inlier observations of landmarks the older keyframe
1833///   already observed (built by
1834///   [`correspondences_2d3d_for_loop_candidate`], landmark positions read
1835///   from the live map) are handed to [`PnPLoopClosureVerifier`]. Because
1836///   the keyframe pose already carries the world scale, the recovered
1837///   relative translation is metric — no `default_translation_scale` is
1838///   involved. Candidates with too few 2D-3D correspondences (below the
1839///   configured `min_inliers`) are rejected outright; there is no fallback
1840///   to the essential-matrix path.
1841#[derive(Debug, Clone, PartialEq, Default)]
1842pub enum LoopRefinementVerifier {
1843    #[default]
1844    EssentialMatrix,
1845    Pnp(PnPLoopClosureVerifierConfig),
1846}
1847
1848/// Which pose-graph solver backs
1849/// [`OnlineSlamLoopClosureRefinementConfig`]'s periodic PGO trigger.
1850///
1851/// [`Self::Se3`] (the default) is today's rigid solve
1852/// ([`PoseGraph::optimize_se3_iterative`], or
1853/// [`PoseGraph::optimize_se3_gnc`] when `gnc` is set) — byte-identical
1854/// behaviour for existing callers.
1855///
1856/// [`Self::Sim3`] instead mirrors the running graph into a parallel
1857/// [`Sim3PoseGraph`] (one Sim3 node per keyframe, seeded at scale `1.0`
1858/// from its current rigid pose; one Sim3 edge per sequential/loop-closure
1859/// edge, likewise seeded at scale `1.0` since both the odometry chain and
1860/// the PnP loop-closure verifier are metric) and solves that instead. Its
1861/// extra per-node scale degree of freedom lets a loop closure absorb
1862/// **scale drift** — e.g. a learned monocular-style tracker's accumulated
1863/// `1.4-2.1x` scale error — that a rigid `SE(3)` graph cannot represent
1864/// and instead smears as rotation/translation error across the whole
1865/// trajectory (see `pipelines/slam/tests/online_slam.rs`'s
1866/// `sim3_solver_recovers_scale_drift_se3_cannot` for a measured A/B on a
1867/// synthetic drifted chain).
1868///
1869/// This variant is only appropriate when scale is genuinely unobservable,
1870/// such as a monocular map or a merge between independently scaled maps.
1871/// Metric stereo and RGB-D maps must use [`Self::Se3`]: following
1872/// ORB-SLAM2/3, their loop scale is fixed to `1` rather than re-estimated
1873/// from noisy per-frame depths. Allowing every pose-graph node to change
1874/// scale in a metric map discards the sensor's scale observation and can
1875/// turn depth noise into global scale drift.
1876///
1877/// Write-back and correction-propagation conventions for this path
1878/// (`maybe_run_loop_closure_refinement`'s `Sim3` branch): each solved
1879/// node's rigid pose for `map.keyframes[*].frame.pose` is
1880/// `Pose { rotation: R, translation: t / s }` (ORB-SLAM2's
1881/// `OptimizeEssentialGraph` convention — dividing by scale, not
1882/// multiplying, is what keeps the corrected pose's *reprojection ray*
1883/// invariant, since a pinhole projection is invariant to a positive
1884/// rescale of camera-frame depth); each corrected keyframe's world-frame
1885/// similarity correction for landmark propagation is
1886/// `Siw_new⁻¹ ∘ Siw_old` (the direct Sim(3) generalisation of the SE(3)
1887/// path's `T_cw_new⁻¹ ∘ T_cw_old`); the tracker's `last_successful_pose` is
1888/// corrected by the same correction's rotation+translation part only,
1889/// with the motion model's cached world velocity additionally scaled by
1890/// `correction.scale` (see [`visloc_tracking::Tracker::apply_similarity_pose_correction`]).
1891///
1892/// [`OnlineSlamLoopClosureRefinementConfig::gnc`] is **ignored** on this
1893/// path: [`Sim3PoseGraph`] has no Graduated Non-Convexity variant yet.
1894/// Callers that set both should treat it as a configuration smell (the
1895/// demo CLI warns); a wrong loop closure will not be annealed out when
1896/// `solver` is `Sim3`. [`OnlineSlamLoopClosureRefinementConfig::marginalization_window`]
1897/// is likewise ignored on this path — [`Sim3PoseGraph`] has no
1898/// fixed-lag marginalization yet, so the Sim3 mirror grows unbounded for
1899/// the lifetime of the session. PCM / the covariance gate are unaffected:
1900/// both screen a candidate before it enters either graph, using only the
1901/// always-maintained SE(3) mirror.
1902#[derive(Debug, Clone, Default, PartialEq)]
1903pub enum LoopRefinementSolver {
1904    #[default]
1905    Se3,
1906    Sim3(Sim3PoseGraphConfig),
1907}
1908
1909/// Opt-in appearance-based long-range loop-candidate source for
1910/// [`OnlineSlamLoopClosureRefinementConfig`]. The shared-landmark detector
1911/// (`detect_loop_closure_candidates`) can only ever propose candidates that
1912/// still reference the SAME map landmark ids the current frame's inliers
1913/// carry; once the tracker drifts around a loop and revisits a place, the
1914/// mapper has typically re-triangulated fresh landmark ids for the very same
1915/// walls, so shared-id candidates are inherently short-range (near-in-time
1916/// keyframes only). This stream instead ranks *past* keyframes by cosine
1917/// similarity of their cached mean local descriptor against the current
1918/// frame's, restricted to candidates at least `min_keyframe_id_gap`
1919/// keyframe-ids older — i.e. genuinely long-range, appearance-only place
1920/// recognition, mirroring
1921/// [`OnlineSlamRelocalizationAppearanceConfig`]'s retrieval machinery
1922/// (`relocalization_mean_descriptor` / cosine ranking) but tuned for
1923/// long-range loop detection rather than short-range recovery-after-loss.
1924///
1925/// Each ranked candidate keyframe is verified by building 2D-3D
1926/// correspondences via descriptor matching (current frame descriptors
1927/// against the candidate keyframe's own observed landmarks' descriptors —
1928/// there is no shared-id assembly to fall back to, by construction) and
1929/// running them through [`PnPLoopClosureVerifier`] configured by
1930/// `pnp_verifier`. Accepted candidates flow through the exact same
1931/// downstream fold as shared-landmark candidates (PCM / covariance gate /
1932/// PGO / GNC / write-back).
1933#[derive(Debug, Clone, PartialEq)]
1934pub struct LoopAppearanceCandidateConfig {
1935    /// Minimum keyframe-id gap between the newly-registered keyframe and a
1936    /// candidate older keyframe. This is what makes the stream long-range:
1937    /// set it comfortably above the span the shared-landmark detector and
1938    /// local mapping window already cover.
1939    pub min_keyframe_id_gap: u64,
1940    /// Maximum number of appearance-ranked candidate keyframes verified per
1941    /// frame. Bounds the per-frame PnP-verification cost.
1942    pub max_candidates_per_frame: usize,
1943    /// Minimum cosine similarity between the current frame's mean local
1944    /// descriptor and a candidate keyframe's cached mean local descriptor.
1945    pub min_similarity: f32,
1946    /// Minimum number of descriptor-bearing landmarks a candidate keyframe
1947    /// must observe before appearance verification runs against it. A
1948    /// keyframe with fewer descriptors than `pnp_verifier.min_inliers` can
1949    /// never pass the PnP gate anyway, so this is a cheap early reject.
1950    pub min_candidate_landmark_count: usize,
1951    /// Number of strongest covisible neighbors gathered on each side of a
1952    /// candidate, matching ORB-SLAM3's ten-keyframe local-region search.
1953    pub covisibility_max_keyframes: usize,
1954    /// Shared landmark floor used to define a covisibility edge.
1955    pub covisibility_min_shared_landmarks: usize,
1956    /// Number of current-region keyframes that must independently PnP-verify
1957    /// against the matched candidate region. Includes the current keyframe.
1958    pub min_covisible_keyframe_verifications: usize,
1959    /// Maximum translation disagreement between a neighbor's independent PnP
1960    /// loop pose and the primary loop pose propagated through local odometry.
1961    pub max_covisibility_translation_disagreement_meters: f64,
1962    /// Rotation counterpart of `max_covisibility_translation_disagreement_meters`.
1963    pub max_covisibility_rotation_disagreement_radians: f64,
1964    /// Number of separate current keyframes that must verify the same
1965    /// covisible candidate region before it may enter the graph.
1966    pub region_confirmation_required_keyframes: usize,
1967    /// Consecutive keyframes allowed to miss a pending region before reset.
1968    pub region_confirmation_max_misses: usize,
1969    /// Optional ORB-SLAM3-style post-PnP projection search radius. When set,
1970    /// the primary appearance PnP pose projects the candidate region into the
1971    /// current image, rematches only inside each landmark's pixel window, and
1972    /// requires a second PnP verification before covisibility confirmation.
1973    pub projection_search_radius_px: Option<f64>,
1974    /// Minimum one-to-one projection-guided correspondences required before
1975    /// the refined PnP solve. ORB-SLAM3 uses a 50-match pre-optimization gate;
1976    /// this remains configurable because visloc-rs uses SuperPoint rather than
1977    /// ORB descriptors and must measure its own correspondence distribution.
1978    pub min_projection_correspondence_count: usize,
1979    /// PnP RANSAC verifier thresholds. `min_inliers` defaults higher than
1980    /// the shared-landmark PnP path's default because a false long-range
1981    /// loop closure is catastrophic (it can fold the whole trajectory into
1982    /// a wrong basin), so this stream demands stronger evidence before
1983    /// admitting a candidate.
1984    pub pnp_verifier: PnPLoopClosureVerifierConfig,
1985}
1986
1987impl Default for LoopAppearanceCandidateConfig {
1988    fn default() -> Self {
1989        Self {
1990            min_keyframe_id_gap: 150,
1991            max_candidates_per_frame: 3,
1992            min_similarity: 0.2,
1993            min_candidate_landmark_count: 30,
1994            covisibility_max_keyframes: 10,
1995            covisibility_min_shared_landmarks: 10,
1996            min_covisible_keyframe_verifications: 3,
1997            max_covisibility_translation_disagreement_meters: 0.5,
1998            max_covisibility_rotation_disagreement_radians: 0.2,
1999            region_confirmation_required_keyframes: 3,
2000            region_confirmation_max_misses: 2,
2001            projection_search_radius_px: None,
2002            min_projection_correspondence_count: 50,
2003            pnp_verifier: PnPLoopClosureVerifierConfig {
2004                min_inliers: 30,
2005                min_inlier_ratio: 0.5,
2006                max_mean_reprojection_error_px: 4.0,
2007            },
2008        }
2009    }
2010}
2011
2012/// Which stream a folded [`LoopClosureConstraint`] (reported on
2013/// [`OnlineSlamLoopClosureRefinementStats::admitted_constraints`]) came from.
2014#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2015pub enum LoopClosureCandidateSource {
2016    /// From the default shared-landmark detector
2017    /// (`detect_loop_closure_candidates`), verified by
2018    /// [`OnlineSlamLoopClosureRefinementConfig::verifier`].
2019    SharedLandmark,
2020    /// From the opt-in appearance-based long-range candidate source
2021    /// (`OnlineSlamLoopClosureRefinementConfig::appearance_candidates`).
2022    Appearance,
2023}
2024
2025/// One loop-closure constraint admitted into the running pose graph this
2026/// frame, with enough detail for external diagnostics (e.g. a per-frame CSV
2027/// log distinguishing shared-landmark from appearance-sourced closures).
2028/// Reported on
2029/// [`OnlineSlamLoopClosureRefinementStats::admitted_constraints`]; does NOT
2030/// include constraints admitted via the `pcm_batch_rescreen` promotion path
2031/// (those remain counted only in
2032/// [`OnlineSlamLoopClosureRefinementStats::loop_closures_pcm_promoted`]).
2033#[derive(Debug, Clone, PartialEq)]
2034pub struct OnlineSlamAdmittedLoopConstraint {
2035    pub from_keyframe_id: u64,
2036    pub to_keyframe_id: u64,
2037    pub inlier_count: usize,
2038    pub translation_norm_m: f64,
2039    pub relative_pose: SE3,
2040    pub source: LoopClosureCandidateSource,
2041}
2042
2043/// Front-end gate that rejected an otherwise geometrically verified loop
2044/// constraint before it entered the pose graph.
2045#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2046pub enum OnlineSlamLoopConstraintRejectionReason {
2047    Pcm,
2048    Covariance,
2049    /// The PnP inliers did not yield a full-rank, sufficiently conditioned
2050    /// covariance-aware 6-DoF pose information matrix.
2051    PoseInformation,
2052}
2053
2054/// A verified loop measurement rejected before graph insertion. Keeping the
2055/// measurement is essential for deciding offline whether a robust gate caught
2056/// a false closure or over-rejected a ground-truth-consistent one.
2057#[derive(Debug, Clone, PartialEq)]
2058pub struct OnlineSlamRejectedLoopConstraint {
2059    pub from_keyframe_id: u64,
2060    pub to_keyframe_id: u64,
2061    pub inlier_count: usize,
2062    pub translation_norm_m: f64,
2063    pub relative_pose: SE3,
2064    pub source: LoopClosureCandidateSource,
2065    pub reason: OnlineSlamLoopConstraintRejectionReason,
2066}
2067
2068/// Per-session configuration for the online loop-closure + pose-graph
2069/// refinement stage owned by [`OnlineSlamPipeline`]. When attached via
2070/// [`OnlineSlamConfig::pose_graph_refinement`], the pipeline maintains a
2071/// running [`PoseGraph`] mirror of `map.keyframes`, runs the configured
2072/// [`LoopRefinementVerifier`] on every candidate emitted by
2073/// `detect_loop_closure_candidates`, and folds verified
2074/// [`LoopClosureConstraint`]s into the graph. When
2075/// `trigger_every_new_constraints` new verified edges have accumulated
2076/// since the last solve, [`PoseGraph::optimize_se3_iterative`] runs and
2077/// the optimised keyframe poses are written back into the map.
2078#[derive(Debug, Clone, PartialEq)]
2079pub struct OnlineSlamLoopClosureRefinementConfig {
2080    /// Camera intrinsics passed to the loop-closure verifier when it
2081    /// builds correspondences. Must match the camera that produced the
2082    /// keyframes' keypoints. Single-monocular for now — per-frame
2083    /// intrinsics are out of scope for the first version of this stage.
2084    pub camera: Camera,
2085    /// Thresholds (`min_inliers`, `min_inlier_ratio`,
2086    /// `max_mean_sampson_error`, `default_translation_scale`) handed to
2087    /// the [`EssentialMatrixLoopClosureVerifier`] every frame. Only
2088    /// consulted when `verifier` is [`LoopRefinementVerifier::EssentialMatrix`]
2089    /// (the default).
2090    pub verifier_config: LoopClosureVerifierConfig,
2091    /// Which verifier backend runs on candidates this frame. Defaults to
2092    /// [`LoopRefinementVerifier::EssentialMatrix`] so existing callers keep
2093    /// today's scale-free behaviour byte-identical; opt into
2094    /// [`LoopRefinementVerifier::Pnp`] for metric loop-closure translations.
2095    pub verifier: LoopRefinementVerifier,
2096    /// SE(3) Gauss-Newton settings consumed by
2097    /// [`PoseGraph::optimize_se3_iterative`] (or, when `gnc` is `Some`, the
2098    /// shared SE(3) settings consumed by [`PoseGraph::optimize_se3_gnc`])
2099    /// when the trigger fires.
2100    pub pose_graph_config: PoseGraphSe3Config,
2101    /// Override every admitted loop edge's isotropic scalar weight. `None`
2102    /// preserves the legacy verifier-inlier-count weight. `Some(1.0)` gives a
2103    /// loop the same scalar information as a sequential edge and is the
2104    /// conservative control when no calibrated PnP covariance is available.
2105    /// The same value is used by the SE(3) mirror and by directly admitted
2106    /// Sim(3) edges. As documented on `pcm_batch_rescreen`, batch reconciliation
2107    /// with the Sim(3) solver remains unsupported.
2108    pub fixed_loop_edge_weight: Option<f64>,
2109    /// Optional covariance-aware anisotropic information for PnP loop edges.
2110    /// The estimator uses only the verifier's final inlier correspondences,
2111    /// propagates each map landmark's multi-view covariance into the query
2112    /// reprojection residual, and rejects rank-deficient/ill-conditioned
2113    /// geometry instead of hiding it with a diagonal ridge. The identical
2114    /// estimator and spectral cap are applied to sequential PnP edges so loop
2115    /// and odometry factors share one information convention. `None` preserves
2116    /// the scalar edge path. When set, this takes precedence over
2117    /// `fixed_loop_edge_weight` for SE(3) loop edges.
2118    pub loop_pose_information: Option<LoopPoseInformationConfig>,
2119    /// Optional Graduated Non-Convexity outlier rejection for the back-end
2120    /// solve. `None` (default) runs the plain
2121    /// [`PoseGraph::optimize_se3_iterative`] M-estimator. `Some(gnc)` runs
2122    /// [`PoseGraph::optimize_se3_gnc`] instead, so a *verified-but-wrong*
2123    /// loop closure — a perceptual-aliasing match that still passed
2124    /// essential-matrix verification — is annealed down to a vanishing
2125    /// weight at the back-end before it can drag the whole trajectory into a
2126    /// corrupted basin. This is the last untouched GNC integration point;
2127    /// the local M-estimator alone cannot escape a basin a confident wrong
2128    /// closure captures. The rejected closures are reported on
2129    /// [`OnlineSlamLoopClosureRefinementStats`]. Use `auto_scale` so the
2130    /// inlier band tracks the live graph's noise; do NOT use
2131    /// `auto_scale_readapt` here (it is a BA-only win and over-rejects real
2132    /// edges on pose graphs).
2133    pub gnc: Option<gnc::GncConfig>,
2134    /// Optional Pairwise Consistency Maximization *front-end* screen
2135    /// ([`crate::pcm`]). `None` (default) admits every verified loop closure;
2136    /// `Some(cfg)` screens each newly-verified closure for geometric
2137    /// consistency with the already-admitted set BEFORE it enters the graph,
2138    /// so a perceptual-aliasing false positive never corrupts the
2139    /// (non-robust) initializer or the solve. A closure is admitted when it is
2140    /// individually consistent with the odometry (current graph poses) and
2141    /// pairwise-consistent with a strict majority of the established
2142    /// closures. This is complementary to `gnc`: PCM removes the gross
2143    /// outliers up front, GNC catches the borderline ones the residual gate
2144    /// admits. Rejections are reported on
2145    /// [`OnlineSlamLoopClosureRefinementStats::loop_closures_pcm_rejected`].
2146    pub pcm: Option<pcm::PcmConfig>,
2147    /// Optional covariance-based *metric* gate (a χ² threshold such as
2148    /// [`covariance::CHI2_95_6DOF`]). `None` (default) applies no metric gate;
2149    /// `Some(threshold)` admits a verified closure only when the squared
2150    /// Mahalanobis distance of its innovation — the measured relative pose
2151    /// versus the estimate's prediction — under the relative-pose covariance
2152    /// ([`PoseGraph::relative_pose_covariance`]) is `<= threshold`. This is the
2153    /// metric counterpart to the combinatorial `pcm` screen: it rejects a
2154    /// confident-but-wrong closure whose implied correction is statistically
2155    /// implausible given the trajectory's uncertainty. Recovering the relative
2156    /// covariance solves two block-columns of `Σ` against the sparse block
2157    /// factor (`O(nnz(L))` per loop, no dense inverse), cheap enough for the
2158    /// online path. Rejections are reported on
2159    /// [`OnlineSlamLoopClosureRefinementStats::loop_closures_covariance_rejected`].
2160    pub covariance_gate: Option<f64>,
2161    /// When `pcm` is set, also run a *batch* re-screen each frame that admits
2162    /// loop closures: over the full history of essential-verified closures (the
2163    /// ones in the graph plus the ones the incremental screen deferred),
2164    /// recompute the maximum mutually-consistent set
2165    /// ([`pcm::maximum_consistent_set`], order-independent) and reconcile the
2166    /// graph's loop edges to it — *promoting* a closure the incremental,
2167    /// order-dependent admission wrongly deferred and *evicting* one it wrongly
2168    /// admitted. This self-heals the cold-start failure of the purely
2169    /// incremental screen: a perceptual-aliasing closure admitted first (against
2170    /// the empty set, so unconditionally) then poisons every genuine closure
2171    /// checked against it. `false` (default) keeps the purely incremental
2172    /// behavior; ignored when `pcm` is `None`. Promotions/evictions are reported
2173    /// on [`OnlineSlamLoopClosureRefinementStats`] and bump the trigger counter
2174    /// so a reconciled graph is re-solved.
2175    ///
2176    /// Divergence when `solver` is [`LoopRefinementSolver::Sim3`]:
2177    /// reconciliation only edits the `Se3` mirror (`graph.edges`); the
2178    /// `Sim3` mirror is not reconciled to match (promoted/evicted loop
2179    /// edges are not added to / removed from it), so combining both is
2180    /// currently unsupported. Not exercised by tonight's Sim3 work.
2181    pub pcm_batch_rescreen: bool,
2182    /// Optional fixed-lag / sliding-window bound on the pose graph. `None`
2183    /// (default) keeps the full graph and re-solves it batch every trigger.
2184    /// `Some(w)` runs [`PoseGraph::marginalize_oldest`] after each solve to keep
2185    /// at most `w` poses (the anchor among them), marginalizing the oldest into a
2186    /// dense Gaussian prior so the per-solve cost stays bounded as keyframes
2187    /// accumulate — the marginalized keyframes' optimised poses are frozen in the
2188    /// map at marginalization time, and loop closures to them are no longer
2189    /// admitted (their node has left the graph). Choose `w` ≥ a few so the
2190    /// sequential chain and recent loop closures stay in the window;
2191    /// marginalization runs at the just-solved (converged) estimate, so it is
2192    /// first-order exact. Marginalized pose ids are reported on
2193    /// [`OnlineSlamLoopClosureRefinementStats::poses_marginalized`].
2194    pub marginalization_window: Option<usize>,
2195    /// When `marginalization_window` is set, **sparsify** each marginalized
2196    /// blanket prior to its Chow-Liu tree
2197    /// ([`PoseGraph::marginalize_oldest_sparsified`]) instead of keeping the dense
2198    /// clique. Default `false` (dense, bit-identical to before). Set it so a
2199    /// long-running window does not accumulate dense priors as it slides —
2200    /// trading an exact marginal for a sparse, KL-optimal tree approximation that
2201    /// preserves every kept pose's marginal.
2202    pub marginalization_sparsify: bool,
2203    /// Minimum number of *new* verified loop-closure constraints that
2204    /// must accumulate before a fresh pose-graph solve runs. Clamped to
2205    /// at least `1`; `1` runs PGO on every accepted loop edge, higher
2206    /// values batch.
2207    pub trigger_every_new_constraints: usize,
2208    /// Optional appearance-based long-range loop-candidate source. `None`
2209    /// (the default) keeps the stage's only candidate source as
2210    /// `detect_loop_closure_candidates`'s shared-landmark detector — byte-
2211    /// identical to the stage's original behaviour. `Some(config)` also
2212    /// ranks past keyframes by appearance (independent of shared landmark
2213    /// ids) and PnP-verifies the top candidates every frame; see
2214    /// [`LoopAppearanceCandidateConfig`] for the retrieval + verification
2215    /// details. When set, the stage maintains a per-keyframe mean-
2216    /// descriptor cache (`OnlineSlamLoopClosureRefinementState::appearance_descriptor_cache`)
2217    /// as keyframes register, independent of whether
2218    /// [`OnlineSlamConfig::relocalization`] is configured.
2219    pub appearance_candidates: Option<LoopAppearanceCandidateConfig>,
2220    /// Persist accepted appearance-PnP inliers as cross-loop map
2221    /// observations. This is the `SearchAndFuse`/welding data-association step
2222    /// used by ORB-SLAM before reprojection BA: without it the loop exists only
2223    /// as a pose-pose edge and BA cannot see the long-range visual evidence.
2224    /// When a query keypoint already observes a different (duplicated) local
2225    /// landmark, that one frame/keypoint relation is reassigned to the older
2226    /// loop landmark on both mirrored observation indices; the duplicate
2227    /// landmark and its other observations are retained for a later explicit
2228    /// merge. `false` preserves the historical pose-edge-only behavior.
2229    pub fuse_loop_observations: bool,
2230    /// Optional synchronous covisibility "welding" BA after a PGO solve that
2231    /// fused at least one cross-loop observation. The solve runs on a cloned
2232    /// map and commits only when reprojection error does not increase and the
2233    /// resulting map validates. `None` preserves pose-graph-only behavior.
2234    pub loop_welding_ba: Option<CovisibilityLocalBaConfig>,
2235    /// When `true`, propagate each solved keyframe's rigid pose
2236    /// correction `C_k = T_cw_new⁻¹ ∘ T_cw_old` (world-frame, computed from
2237    /// the keyframe's pose immediately before this solve versus the
2238    /// solved [`PoseGraph`] pose) to (a) every landmark whose *anchor*
2239    /// keyframe — the first (lowest-id) keyframe that observed it — is
2240    /// among the keyframes this solve updated, moving the landmark
2241    /// rigidly with its anchor so the map stays internally consistent
2242    /// after PGO write-back, and (b) the tracker's continuation state
2243    /// (`last_successful_pose` plus motion-model state such as
2244    /// [`visloc_tracking::ImuPredictiveMotionModel`]'s `velocity_world`)
2245    /// via [`Tracker::apply_pose_correction`], using the correction of
2246    /// the highest-id (most-recently registered) solved keyframe so the
2247    /// very next `track_frame`'s PnP prior is consistent with the
2248    /// corrected map instead of re-anchoring to the pre-solve drift.
2249    /// `false` (default) keeps today's behaviour byte-identical: only
2250    /// `map.keyframes[*].frame.pose` moves; landmarks and the tracker's
2251    /// state are untouched, which is the write-back gap that leaves the
2252    /// tracker immediately re-localizing against the stale landmark
2253    /// field. Per-solve propagation diagnostics land on
2254    /// [`OnlineSlamLoopClosureRefinementStats::landmarks_moved`],
2255    /// `max_landmark_displacement_meters`,
2256    /// `mean_landmark_displacement_meters`, and
2257    /// `tracker_correction_applied`.
2258    pub propagate_corrections: bool,
2259    /// Which pose-graph solver backs the periodic PGO trigger. Defaults
2260    /// to [`LoopRefinementSolver::Se3`] — byte-identical to this stage's
2261    /// original behaviour. See [`LoopRefinementSolver`] for the `Sim3`
2262    /// opt-in (scale-drift correction) and its write-back /
2263    /// correction-propagation conventions.
2264    pub solver: LoopRefinementSolver,
2265}
2266
2267impl OnlineSlamLoopClosureRefinementConfig {
2268    /// Pose-graph mirror that registers keyframes for recovered marginal factors
2269    /// without ever triggering PGO (Basalt mapper sink).
2270    pub fn recovered_factor_sink(camera: Camera) -> Self {
2271        Self {
2272            camera,
2273            verifier_config: LoopClosureVerifierConfig::default(),
2274            verifier: LoopRefinementVerifier::EssentialMatrix,
2275            pose_graph_config: PoseGraphSe3Config::default(),
2276            fixed_loop_edge_weight: None,
2277            loop_pose_information: None,
2278            gnc: None,
2279            pcm: None,
2280            covariance_gate: None,
2281            pcm_batch_rescreen: false,
2282            marginalization_window: None,
2283            marginalization_sparsify: false,
2284            trigger_every_new_constraints: usize::MAX,
2285            appearance_candidates: None,
2286            fuse_loop_observations: false,
2287            loop_welding_ba: None,
2288            propagate_corrections: false,
2289            solver: LoopRefinementSolver::Se3,
2290        }
2291    }
2292}
2293
2294/// Running state for the online loop-closure + pose-graph refinement
2295/// stage. Lives on [`OnlineSlamPipeline`] when
2296/// [`OnlineSlamConfig::pose_graph_refinement`] is `Some`.
2297#[derive(Debug, Clone, PartialEq)]
2298pub struct OnlineSlamLoopClosureRefinementState {
2299    pub config: OnlineSlamLoopClosureRefinementConfig,
2300    /// Running pose-graph mirror. One node per registered keyframe, one
2301    /// sequential edge between every consecutive pair of registered
2302    /// keyframes (in insertion order), and one loop-closure edge per
2303    /// verified [`LoopClosureConstraint`].
2304    pub graph: PoseGraph,
2305    /// `Sim(3)` mirror of `graph`, maintained in lockstep (same node ids,
2306    /// same edges, seeded at scale `1.0`) exactly when
2307    /// `config.solver` is [`LoopRefinementSolver::Sim3`]; `None`
2308    /// otherwise, so the [`LoopRefinementSolver::Se3`] default pays no
2309    /// extra bookkeeping. Solved by [`Sim3PoseGraph::optimize`] on the
2310    /// same trigger cadence as `graph`; see [`LoopRefinementSolver::Sim3`]
2311    /// for the write-back convention.
2312    pub sim3_graph: Option<Sim3PoseGraph>,
2313    /// Keyframe ids in the order they were first registered. The first
2314    /// entry is the [`PoseGraph::anchor`]; subsequent entries form the
2315    /// sequential edge chain.
2316    pub keyframe_order: Vec<u64>,
2317    /// Essential-verified loop closures currently admitted into the graph (one
2318    /// loop-closure edge each). With the incremental PCM screen this is the
2319    /// admitted set; with `pcm_batch_rescreen` it is the latest batch
2320    /// maximum-consistent set.
2321    pub verified_constraints: Vec<LoopClosureConstraint>,
2322    /// Covariance-derived information retained across PCM deferral/promotion.
2323    /// Keyed by `(older_keyframe, query_keyframe)`.
2324    loop_pose_information: HashMap<(u64, u64), Matrix6<f64>>,
2325    /// Essential-verified loop closures the incremental PCM screen *deferred*
2326    /// (not in the graph), retained so the batch re-screen
2327    /// ([`OnlineSlamLoopClosureRefinementConfig::pcm_batch_rescreen`]) can
2328    /// promote one later if it joins the consensus. Empty when batch re-screen
2329    /// is off.
2330    pub pcm_deferred: Vec<LoopClosureConstraint>,
2331    /// New verified constraints since the last successful PGO trigger.
2332    /// Reset to `0` after each fired solve.
2333    pub pending_since_last_trigger: usize,
2334    /// Total number of [`PoseGraph::optimize_se3_iterative`] calls fired
2335    /// by the pipeline since construction (counts both converged and
2336    /// not-converged solves; mismatches between the two go to
2337    /// `OnlineSlamLoopClosureRefinementStats::pose_graph_result`).
2338    pub trigger_count: u64,
2339    /// Cached per-keyframe mean local descriptor for the appearance-based
2340    /// long-range loop candidate source (see
2341    /// [`OnlineSlamLoopClosureRefinementConfig::appearance_candidates`]).
2342    /// Populated as each keyframe registers with the running graph whenever
2343    /// `config.appearance_candidates` is `Some`; maintained independently of
2344    /// [`OnlineSlamConfig::relocalization`]. Empty (and never consulted)
2345    /// when `appearance_candidates` is `None`.
2346    pub appearance_descriptor_cache: HashMap<u64, Vec<f32>>,
2347    appearance_pending_region: Option<AppearancePendingRegion>,
2348    pending_loop_observation_fusions: Vec<PendingLoopObservationFusion>,
2349}
2350
2351#[derive(Debug, Clone, PartialEq)]
2352struct PendingLoopObservationFusion {
2353    from_keyframe_id: u64,
2354    query_keyframe_id: u64,
2355    relative_pose: SE3,
2356    pairs: Vec<(usize, u64)>,
2357}
2358
2359#[derive(Debug, Clone, PartialEq)]
2360struct AppearancePendingRegion {
2361    root_keyframe_id: u64,
2362    last_current_keyframe_id: u64,
2363    root_to_last_current: SE3,
2364    confirmation_count: usize,
2365    miss_count: usize,
2366}
2367
2368impl OnlineSlamLoopClosureRefinementState {
2369    fn new(config: OnlineSlamLoopClosureRefinementConfig) -> Self {
2370        let sim3_graph =
2371            matches!(config.solver, LoopRefinementSolver::Sim3(_)).then(Sim3PoseGraph::new);
2372        Self {
2373            config,
2374            graph: PoseGraph::new(),
2375            sim3_graph,
2376            keyframe_order: Vec::new(),
2377            verified_constraints: Vec::new(),
2378            loop_pose_information: HashMap::new(),
2379            pcm_deferred: Vec::new(),
2380            pending_since_last_trigger: 0,
2381            trigger_count: 0,
2382            appearance_descriptor_cache: HashMap::new(),
2383            appearance_pending_region: None,
2384            pending_loop_observation_fusions: Vec::new(),
2385        }
2386    }
2387
2388    fn reset(&mut self) {
2389        self.appearance_descriptor_cache.clear();
2390        self.appearance_pending_region = None;
2391        self.pending_loop_observation_fusions.clear();
2392        self.graph = PoseGraph::new();
2393        self.sim3_graph =
2394            matches!(self.config.solver, LoopRefinementSolver::Sim3(_)).then(Sim3PoseGraph::new);
2395        self.keyframe_order.clear();
2396        self.verified_constraints.clear();
2397        self.loop_pose_information.clear();
2398        self.pcm_deferred.clear();
2399        self.pending_since_last_trigger = 0;
2400        self.trigger_count = 0;
2401    }
2402}
2403
2404/// Per-frame outcome of the online loop-closure + pose-graph
2405/// refinement stage. Exposed on
2406/// [`OnlineSlamResult::pose_graph_refinement`] and used by the demos to
2407/// audit verifier acceptance + PGO trigger cadence.
2408#[derive(Debug, Clone, PartialEq, Default)]
2409pub struct OnlineSlamLoopClosureRefinementStats {
2410    /// Number of [`LoopClosureCandidate`]s fed through the verifier
2411    /// this `process_frame` call.
2412    pub verified_candidate_count: usize,
2413    /// Number of candidates the verifier accepted this frame. Note that
2414    /// only candidates whose `query_frame_id` matches the keyframe
2415    /// registered this frame are eligible — a verified candidate for a
2416    /// frame that did not become a keyframe is silently dropped because
2417    /// the running graph has no node for it.
2418    pub accepted_count: usize,
2419    /// `Some` when [`PoseGraph::optimize_se3_iterative`] fired on this
2420    /// frame; `None` when no new constraint arrived, the new-constraint
2421    /// trigger threshold was not yet reached, or the GNC robust solver ran
2422    /// instead (see `gnc_result`).
2423    pub pose_graph_result: Option<PoseGraphSe3Result>,
2424    /// `Some` when the GNC robust solver ([`PoseGraph::optimize_se3_gnc`])
2425    /// fired this frame instead of the plain iterative one — i.e. when
2426    /// [`OnlineSlamLoopClosureRefinementConfig::gnc`] is set and the trigger
2427    /// threshold was met. Its `edge_weights` classify every graph edge as
2428    /// inlier/outlier; `pose_graph_result` is `None` on this path.
2429    pub gnc_result: Option<PoseGraphGncResult>,
2430    /// `Some` when [`Sim3PoseGraph::optimize`] fired on this frame — i.e.
2431    /// [`OnlineSlamLoopClosureRefinementConfig::solver`] is
2432    /// [`LoopRefinementSolver::Sim3`] and the trigger threshold was met.
2433    /// Mutually exclusive with `pose_graph_result` / `gnc_result` (always
2434    /// `None` on the `Se3` path).
2435    pub sim3_pose_graph_result: Option<Sim3PoseGraphResult>,
2436    /// `(min, max)` per-node scale across the just-solved `Sim3PoseGraph`
2437    /// when `sim3_pose_graph_result` is `Some` — observability for how
2438    /// much scale drift the solve absorbed (both `1.0` when the graph is
2439    /// scale-consistent; a wide spread means the solve is actively
2440    /// redistributing accumulated monocular-style scale error). `None`
2441    /// on the `Se3` path or when no `Sim3` solve fired this frame.
2442    pub sim3_scale_spread: Option<(f64, f64)>,
2443    /// Number of *loop-closure* edges the GNC solver drove below the inlier
2444    /// threshold (weight `< 0.5`) on the solve fired this frame — the
2445    /// verified-but-wrong closures caught and rejected at the back-end.
2446    /// Always `0` on the plain iterative path (`gnc` unset).
2447    pub loop_closures_rejected: usize,
2448    /// Number of verified loop closures the PCM front-end screen rejected this
2449    /// frame *before* they entered the graph (geometrically inconsistent with
2450    /// the established set). Always `0` when `pcm` is unset.
2451    pub loop_closures_pcm_rejected: usize,
2452    /// Number of verified loop closures the covariance gate rejected this frame
2453    /// *before* they entered the graph (innovation statistically implausible
2454    /// under the relative-pose covariance). Always `0` when `covariance_gate`
2455    /// is unset.
2456    pub loop_closures_covariance_rejected: usize,
2457    /// Number of verified PnP loops rejected because their covariance-aware
2458    /// 6×6 information was unavailable, rank-deficient, or ill-conditioned.
2459    pub loop_closures_pose_information_rejected: usize,
2460    /// Number of admitted SE(3) loop edges carrying covariance-aware 6×6
2461    /// information rather than an isotropic scalar.
2462    pub loop_closures_with_pose_information: usize,
2463    /// Per-loop numerical evidence for covariance-aware matrices that passed
2464    /// the rank and condition gates, before PCM/covariance admission screens.
2465    pub loop_pose_information_diagnostics: Vec<LoopPoseInformationDiagnostic>,
2466    /// Typed reasons for loop information failures, preserving whether the
2467    /// problem was configuration, missing state, correspondence support, or
2468    /// pose geometry.
2469    pub loop_pose_information_failures: LoopPoseInformationFailureCounts,
2470    /// Sequential PnP edges carrying the same covariance-aware information
2471    /// convention as loop edges during this frame.
2472    pub sequential_edges_with_pose_information: usize,
2473    /// Sequential edges that fell back to identity information because too few
2474    /// usable landmark covariances survived. The chain is never dropped.
2475    pub sequential_pose_information_fallbacks: usize,
2476    pub sequential_pose_information_diagnostics: Vec<LoopPoseInformationDiagnostic>,
2477    /// Typed reason for each sequential edge that used identity information.
2478    pub sequential_pose_information_failures: LoopPoseInformationFailureCounts,
2479    /// Number of deferred loop closures the batch PCM re-screen *promoted* into
2480    /// the graph this frame (they joined the maximum-consistent consensus the
2481    /// incremental, order-dependent screen had wrongly excluded). Always `0`
2482    /// unless `pcm_batch_rescreen` is set.
2483    pub loop_closures_pcm_promoted: usize,
2484    /// Number of admitted loop closures the batch PCM re-screen *evicted* from
2485    /// the graph this frame (inconsistent with the larger consensus — e.g. a
2486    /// perceptual-aliasing closure admitted first against the empty set). Always
2487    /// `0` unless `pcm_batch_rescreen` is set.
2488    pub loop_closures_pcm_evicted: usize,
2489    /// Number of `map.keyframes[id].frame.pose` slots overwritten with
2490    /// the optimised pose after PGO. Zero unless a solve fired this frame
2491    /// (`pose_graph_result.is_some()` or `gnc_result.is_some()`).
2492    pub keyframes_updated: usize,
2493    /// Pose ids the fixed-lag `marginalization_window` marginalized out of the
2494    /// graph this frame (oldest first), folded into a dense Gaussian prior.
2495    /// Empty unless `marginalization_window` is set and the graph exceeded it.
2496    pub poses_marginalized: Vec<u64>,
2497    /// Number of appearance-ranked candidate keyframes evaluated this frame
2498    /// (post ranking / gap filter, pre PnP verification). Always `0` when
2499    /// [`OnlineSlamLoopClosureRefinementConfig::appearance_candidates`] is
2500    /// unset.
2501    pub appearance_candidate_count: usize,
2502    /// Number of keyframes surviving appearance ranking and the frame-gap
2503    /// filter before descriptor matching / PnP verification.
2504    pub appearance_ranked_candidate_count: usize,
2505    /// Appearance regions rejected because they intersect the current
2506    /// keyframe's connected/covisible local region and are not a loop.
2507    pub appearance_connected_region_rejected_count: usize,
2508    /// Candidates passing the primary current-vs-candidate-region PnP test.
2509    pub appearance_pnp_verified_count: usize,
2510    /// Primary-PnP successes rejected by the optional projection-rematch and
2511    /// refined-PnP gate.
2512    pub appearance_projection_rejected_count: usize,
2513    /// Primary-PnP successes rejected by current-side covisibility checking.
2514    pub appearance_covisibility_rejected_count: usize,
2515    /// Pending-region projection verification attempts on later keyframes.
2516    pub appearance_pending_projection_attempted_count: usize,
2517    /// Pending-region projection attempts that passed refined PnP.
2518    pub appearance_pending_projection_verified_count: usize,
2519    /// Projection correspondences produced for the pending-region attempt on
2520    /// this keyframe (zero when not attempted or correspondence build failed).
2521    pub appearance_pending_projection_correspondence_count: usize,
2522    /// Refined-PnP inliers from the pending-region attempt on this keyframe.
2523    pub appearance_pending_projection_inlier_count: usize,
2524    /// Radius selected by the adaptive pending-region projection search.
2525    pub appearance_pending_projection_search_radius_px: Option<f64>,
2526    /// Per-primary-PnP candidate evidence for reproducible gate analysis.
2527    pub appearance_candidate_diagnostics: Vec<AppearanceLoopCandidateDiagnostic>,
2528    /// A geometrically verified region is being carried into later keyframes.
2529    pub appearance_region_confirmation_waiting: bool,
2530    /// A pending region reached its configured cross-keyframe confirmation count.
2531    pub appearance_region_confirmed_count: usize,
2532    /// Appearance candidates whose PnP verification succeeded but whose
2533    /// matched 3D regions could not produce a robust Sim3 scale observation.
2534    pub appearance_scale_estimation_failed_count: usize,
2535    pub appearance_scale_insufficient_points_count: usize,
2536    pub appearance_scale_insufficient_matches_count: usize,
2537    pub appearance_scale_no_consensus_count: usize,
2538    /// Robust scale observations rejected because they were within the
2539    /// Sim3 arm's five-percent no-op band around unit scale.
2540    pub appearance_near_unit_scale_count: usize,
2541    /// Number of appearance candidates admitted into the graph this frame
2542    /// (subset of `accepted_count`). Always `0` when
2543    /// `appearance_candidates` is unset.
2544    pub appearance_accepted_count: usize,
2545    /// Accepted appearance-PnP inlier pairs considered by the optional
2546    /// cross-loop observation fusion stage.
2547    pub loop_fusion_pairs_considered: usize,
2548    /// New query-keyframe/old-landmark observation relations inserted.
2549    pub loop_fusion_observations_inserted: usize,
2550    /// Insertions that replaced a query keypoint's relation to a different
2551    /// local duplicate landmark.
2552    pub loop_fusion_observations_reassigned: usize,
2553    /// Pairs withheld because final GNC classified their loop edge below the
2554    /// inlier threshold.
2555    pub loop_fusion_pairs_robust_rejected: usize,
2556    /// Pairs withheld because the corrected query pose failed the pixel-space
2557    /// reprojection gate.
2558    pub loop_fusion_pairs_reprojection_rejected: usize,
2559    /// Pairs skipped because the landmark/keypoint was missing, invalid, or
2560    /// the older landmark already had another observation in the query frame.
2561    pub loop_fusion_pairs_skipped: usize,
2562    pub loop_welding_ba_attempted: bool,
2563    pub loop_welding_ba_succeeded: bool,
2564    pub loop_welding_ba_mean_reprojection_before_px: Option<f64>,
2565    pub loop_welding_ba_mean_reprojection_after_px: Option<f64>,
2566    pub loop_welding_initial_translation_meters: Option<f64>,
2567    pub loop_welding_initial_rotation_radians: Option<f64>,
2568    pub loop_welding_ba_updated_keyframes: usize,
2569    pub loop_welding_ba_updated_landmarks: usize,
2570    pub loop_welding_ba_rejected_or_failed: bool,
2571    pub loop_welding_post_pgo_attempted: bool,
2572    pub loop_welding_post_pgo_succeeded: bool,
2573    pub loop_welding_post_pgo_mean_reprojection_px: Option<f64>,
2574    pub loop_welding_post_ba_error: Option<CovisibilityLocalBaError>,
2575    pub loop_welding_post_ba_behind_camera_ratio: Option<f64>,
2576    /// Loop-closure constraints admitted into the graph this frame — both
2577    /// the shared-landmark and (when configured) appearance streams — with
2578    /// enough detail for external diagnostics (e.g.
2579    /// `examples/euroc_online_slam_vi_image_demo`'s `loop_constraints.csv`).
2580    /// Does NOT include constraints admitted via the `pcm_batch_rescreen`
2581    /// promotion path.
2582    pub admitted_constraints: Vec<OnlineSlamAdmittedLoopConstraint>,
2583    /// Verified loop measurements rejected by PCM or the covariance gate this
2584    /// frame. Unlike the aggregate counters, this retains the pose needed for
2585    /// post-hoc ground-truth correctness and over-rejection analysis.
2586    pub rejected_constraints: Vec<OnlineSlamRejectedLoopConstraint>,
2587    /// Number of landmarks moved by
2588    /// [`OnlineSlamLoopClosureRefinementConfig::propagate_corrections`]'s
2589    /// landmark-propagation pass this frame. Always `0` when
2590    /// `propagate_corrections` is `false`, no solve fired this frame, or
2591    /// the solve updated no keyframe with a previously-known pose.
2592    pub landmarks_moved: usize,
2593    /// Maximum per-landmark displacement (metres) applied by the
2594    /// propagation pass this frame. `None` when `landmarks_moved == 0`.
2595    pub max_landmark_displacement_meters: Option<f64>,
2596    /// Mean per-landmark displacement (metres) applied by the
2597    /// propagation pass this frame. `None` when `landmarks_moved == 0`.
2598    pub mean_landmark_displacement_meters: Option<f64>,
2599    /// `true` when the tracker's continuation state
2600    /// (`last_successful_pose` plus motion-model state) was corrected
2601    /// this frame via [`Tracker::apply_pose_correction`] with the
2602    /// most-recently solved keyframe's correction. Always `false` when
2603    /// `propagate_corrections` is `false` or no solve fired this frame.
2604    pub tracker_correction_applied: bool,
2605}
2606
2607/// Per-session IMU integration parameters consumed by
2608/// [`OnlineSlamPipeline`] when [`OnlineSlamConfig::imu`] is `Some`. Gravity
2609/// is in the world frame (KITTI y-down: `(0, 9.81, 0)`); biases are the
2610/// linearisation point for the pre-integrator's first-order bias-Jacobians;
2611/// the three `weight_*` fields populate the corresponding
2612/// [`ImuPreintegrationFactor`] weights so a downstream BA can consume the
2613/// emitted factor without further configuration.
2614#[derive(Debug, Clone, PartialEq)]
2615pub struct OnlineSlamImuConfig {
2616    pub gravity_world: Vector3<f64>,
2617    pub bias_gyro: Vector3<f64>,
2618    pub bias_acc: Vector3<f64>,
2619    pub weight_position: f64,
2620    pub weight_velocity: f64,
2621    pub weight_rotation: f64,
2622    /// Optional continuous-time measurement noise used to propagate the
2623    /// preintegrated `[rotation, velocity, position]` covariance. `None`
2624    /// preserves the legacy scalar factor weights.
2625    pub noise_model: Option<ImuNoiseModel>,
2626}
2627
2628impl Default for OnlineSlamImuConfig {
2629    fn default() -> Self {
2630        Self {
2631            gravity_world: Vector3::new(0.0, 9.81, 0.0),
2632            bias_gyro: Vector3::zeros(),
2633            bias_acc: Vector3::zeros(),
2634            weight_position: 1.0,
2635            weight_velocity: 1.0,
2636            weight_rotation: 1.0,
2637            noise_model: None,
2638        }
2639    }
2640}
2641
2642/// Internal IMU running state attached to an [`OnlineSlamPipeline`] when
2643/// [`OnlineSlamConfig::imu`] is `Some`. Carries the running pre-integrator,
2644/// the `keyframe_id_from` of the open integration window (`None` before the
2645/// first keyframe is registered), and any factor staged by `process_frame`
2646/// for the caller to take via [`OnlineSlamPipeline::take_pending_imu_factor`].
2647#[derive(Debug, Clone, PartialEq)]
2648pub struct OnlineSlamImuState {
2649    pub config: OnlineSlamImuConfig,
2650    pub preintegrator: ImuPreintegrator,
2651    pub last_keyframe_id: Option<u64>,
2652    pub pending_factor: Option<ImuPreintegrationFactor>,
2653}
2654
2655impl OnlineSlamImuState {
2656    fn new(config: OnlineSlamImuConfig) -> Self {
2657        let preintegrator = config
2658            .noise_model
2659            .and_then(|noise| {
2660                ImuPreintegrator::new_with_bias_and_noise(config.bias_gyro, config.bias_acc, noise)
2661            })
2662            .unwrap_or_else(|| ImuPreintegrator::new_with_bias(config.bias_gyro, config.bias_acc));
2663        Self {
2664            config,
2665            preintegrator,
2666            last_keyframe_id: None,
2667            pending_factor: None,
2668        }
2669    }
2670
2671    fn reset(&mut self) {
2672        self.preintegrator = self
2673            .config
2674            .noise_model
2675            .and_then(|noise| {
2676                ImuPreintegrator::new_with_bias_and_noise(
2677                    self.config.bias_gyro,
2678                    self.config.bias_acc,
2679                    noise,
2680                )
2681            })
2682            .unwrap_or_else(|| {
2683                ImuPreintegrator::new_with_bias(self.config.bias_gyro, self.config.bias_acc)
2684            });
2685        self.last_keyframe_id = None;
2686        self.pending_factor = None;
2687    }
2688
2689    fn reset_preintegrator_with_bias(&mut self, bias_gyro: Vector3<f64>, bias_acc: Vector3<f64>) {
2690        self.config.bias_gyro = bias_gyro;
2691        self.config.bias_acc = bias_acc;
2692        self.preintegrator = self
2693            .config
2694            .noise_model
2695            .and_then(|noise| ImuPreintegrator::new_with_bias_and_noise(bias_gyro, bias_acc, noise))
2696            .unwrap_or_else(|| ImuPreintegrator::new_with_bias(bias_gyro, bias_acc));
2697        self.pending_factor = None;
2698    }
2699}
2700
2701#[derive(Debug, Clone, PartialEq)]
2702pub struct OnlineSlamPipeline<T, M> {
2703    pub map: VisualMap,
2704    pub tracker: T,
2705    pub mapper: M,
2706    pub config: OnlineSlamConfig,
2707    /// Running IMU pre-integration state. `Some` exactly when
2708    /// `config.imu.is_some()` (initialised by [`Self::new`]); `None`
2709    /// otherwise so existing IMU-free flows pay no per-frame overhead.
2710    pub imu_state: Option<OnlineSlamImuState>,
2711    /// Running local VI-BA state. `Some` exactly when
2712    /// `config.local_vi_ba.is_some()` (initialised by [`Self::new`]);
2713    /// `None` otherwise so non-VI-BA flows do no extra book-keeping.
2714    pub local_vi_ba_state: Option<OnlineSlamLocalBaState>,
2715    /// Sparse visual factor lifecycle state. Present exactly when
2716    /// `config.sparse_factor_graph` is configured.
2717    pub sparse_factor_graph_state: Option<SparseFactorGraph>,
2718    /// Running auto-bootstrap state. `Some` exactly when
2719    /// `config.vi_init.is_some() && config.imu.is_some()` (initialised
2720    /// by [`Self::new`]); deliberately private because writes to
2721    /// `completed` cross-cut with `imu_state` / `local_vi_ba_state` /
2722    /// `map.keyframes`. Inspected via [`Self::vi_initialization_status`].
2723    vi_init_state: Option<OnlineSlamViInitState>,
2724    /// Running motion-based VI init state. `Some` exactly when
2725    /// `config.vi_motion_init.is_some() && config.vi_init.is_some() &&
2726    /// config.imu.is_some()`. Private because the motion-based fire is
2727    /// normally gated on the static stage having completed first; an explicit
2728    /// motion-start fallback may instead begin after that stage gives up. The
2729    /// pipeline owns the ordering. Inspected via
2730    /// [`Self::motion_vi_initialization_status`].
2731    vi_motion_init_state: Option<OnlineSlamMotionViInitState>,
2732    /// Running loop-closure + pose-graph refinement state. `Some`
2733    /// exactly when `config.pose_graph_refinement.is_some()`
2734    /// (initialised by [`Self::new`]); `None` otherwise so pure-
2735    /// odometry flows do no extra book-keeping.
2736    pub pose_graph_state: Option<OnlineSlamLoopClosureRefinementState>,
2737    /// Running relocalization-on-tracker-death state. `Some` exactly
2738    /// when `config.relocalization.is_some()` (initialised by
2739    /// [`Self::new`]). Owns its own [`LocalizationPipeline`] instance
2740    /// so the recovery attempt does not perturb the tracker's primary
2741    /// localizer state.
2742    pub relocalization_state: Option<OnlineSlamRelocalizationState>,
2743}
2744
2745impl Default
2746    for OnlineSlamPipeline<
2747        Tracker<LocalizationPipeline, ConstantPoseMotionModel>,
2748        LocalMappingPipeline<SimpleKeyframePolicy, LinearTriangulator>,
2749    >
2750{
2751    fn default() -> Self {
2752        Self {
2753            map: VisualMap::new(),
2754            tracker: Tracker::new(LocalizationPipeline::default(), TrackingConfig::default()),
2755            mapper: LocalMappingPipeline::default(),
2756            config: OnlineSlamConfig::default(),
2757            imu_state: None,
2758            local_vi_ba_state: None,
2759            sparse_factor_graph_state: None,
2760            vi_init_state: None,
2761            vi_motion_init_state: None,
2762            pose_graph_state: None,
2763            relocalization_state: None,
2764        }
2765    }
2766}
2767
2768impl<T, M> OnlineSlamPipeline<T, M> {
2769    /// Construct a pipeline. Validates cross-field configuration
2770    /// invariants (currently: `vi_init` requires `imu`, gravity vectors
2771    /// must agree) via [`OnlineSlamConfig::validate`]; panics with the
2772    /// surfaced [`OnlineSlamConfigError`] on a mismatch. This is a
2773    /// developer error — every public caller passes a literal config —
2774    /// so failing loudly at construction is correct.
2775    pub fn new(map: VisualMap, tracker: T, mapper: M, config: OnlineSlamConfig) -> Self {
2776        if let Err(err) = config.validate() {
2777            panic!("OnlineSlamPipeline::new: invalid config: {err}");
2778        }
2779        let imu_state = config.imu.clone().map(OnlineSlamImuState::new);
2780        let local_vi_ba_state = config.local_vi_ba.clone().map(OnlineSlamLocalBaState::new);
2781        let mut sparse_factor_graph_state = config
2782            .sparse_factor_graph
2783            .clone()
2784            .map(SparseFactorGraph::new);
2785        if let Some(graph) = sparse_factor_graph_state.as_mut() {
2786            let mut existing_keyframe_ids = map.keyframes.keys().copied().collect::<Vec<_>>();
2787            existing_keyframe_ids.sort_unstable();
2788            for keyframe_id in existing_keyframe_ids {
2789                graph.update_from_map(&map, keyframe_id);
2790            }
2791        }
2792        let vi_init_state = config.vi_init.clone().map(OnlineSlamViInitState::new);
2793        let vi_motion_init_state = config
2794            .vi_motion_init
2795            .clone()
2796            .map(OnlineSlamMotionViInitState::new);
2797        let pose_graph_state = config
2798            .pose_graph_refinement
2799            .clone()
2800            .map(OnlineSlamLoopClosureRefinementState::new);
2801        let relocalization_state = config
2802            .relocalization
2803            .clone()
2804            .map(OnlineSlamRelocalizationState::new);
2805        Self {
2806            map,
2807            tracker,
2808            mapper,
2809            config,
2810            imu_state,
2811            local_vi_ba_state,
2812            sparse_factor_graph_state,
2813            vi_init_state,
2814            vi_motion_init_state,
2815            pose_graph_state,
2816            relocalization_state,
2817        }
2818    }
2819
2820    /// Read-only snapshot of the auto-bootstrap stage. Returns
2821    /// [`ViInitializationStatus::Disabled`] when `vi_init` is `None`;
2822    /// otherwise reports buffering / initialised / gave-up state.
2823    pub fn vi_initialization_status(&self) -> ViInitializationStatus {
2824        match &self.vi_init_state {
2825            None => ViInitializationStatus::Disabled,
2826            Some(state) => state.snapshot(),
2827        }
2828    }
2829
2830    /// Read-only snapshot of the motion-based VI init stage. Returns
2831    /// [`MotionViInitializationStatus::Disabled`] when
2832    /// `vi_motion_init` is `None`; otherwise reports
2833    /// waiting / initialised state.
2834    pub fn motion_vi_initialization_status(&self) -> MotionViInitializationStatus {
2835        match &self.vi_motion_init_state {
2836            None => MotionViInitializationStatus::Disabled,
2837            Some(state) => state.snapshot(),
2838        }
2839    }
2840
2841    /// Fold one body-frame IMU sample into the pipeline's running pre-
2842    /// integrator. No-op when [`OnlineSlamConfig::imu`] is `None`. `dt`
2843    /// is seconds since the previous sample; the integrator only accepts
2844    /// strictly positive `dt` and silently drops non-positive values so
2845    /// callers can replay raw IMU streams without pre-filtering.
2846    pub fn push_imu_measurement(&mut self, gyro: Vector3<f64>, accel: Vector3<f64>, dt: f64) {
2847        if dt <= 0.0 || !dt.is_finite() {
2848            return;
2849        }
2850        if let Some(state) = self.imu_state.as_mut() {
2851            state.preintegrator.integrate_sample(gyro, accel, dt);
2852        }
2853        // While the auto-bootstrap stage is still active, also fan the
2854        // sample into its initialiser buffer. Once `completed` /
2855        // `gave_up` is `Some`, stop forwarding so the standalone module
2856        // is not asked to keep growing memory after it has fired.
2857        if let Some(state) = self.vi_init_state.as_mut() {
2858            if state.is_active() {
2859                state.initializer.push_sample(gyro, accel, dt);
2860                state.samples_buffered += 1;
2861                state.buffered_duration_seconds += dt;
2862            }
2863        }
2864    }
2865
2866    /// Feed a sample only to the stationary visual-inertial initializer,
2867    /// without integrating it into the first inter-keyframe IMU factor.
2868    /// Dataset runners use this for IMU measurements that precede the visual
2869    /// seed keyframe: those samples contain the best stationary bias/gravity
2870    /// window, but including them in the running preintegrator would attach
2871    /// motion from before the first graph state to its first factor.
2872    pub fn push_vi_initialization_measurement(
2873        &mut self,
2874        gyro: Vector3<f64>,
2875        accel: Vector3<f64>,
2876        dt: f64,
2877    ) {
2878        if dt <= 0.0 || !dt.is_finite() {
2879            return;
2880        }
2881        if let Some(state) = self.vi_init_state.as_mut() {
2882            if state.is_active() {
2883                state.initializer.push_sample(gyro, accel, dt);
2884                state.samples_buffered += 1;
2885                state.buffered_duration_seconds += dt;
2886            }
2887        }
2888    }
2889
2890    /// Take the IMU pre-integration factor staged by the most recent
2891    /// [`Self::process_frame`] call, if any. Returns `None` when IMU is
2892    /// disabled, when the last `process_frame` did not register a new
2893    /// keyframe to close the running window against, or when the
2894    /// auto-bootstrap stale-factor gate is still active (factors staged
2895    /// before VI init success are discarded — they were built with the
2896    /// caller's placeholder bias linearisation and would feed an
2897    /// inconsistent point into downstream VI-BA).
2898    pub fn take_pending_imu_factor(&mut self) -> Option<ImuPreintegrationFactor> {
2899        self.imu_state
2900            .as_mut()
2901            .and_then(|s| s.pending_factor.take())
2902    }
2903
2904    pub const fn map(&self) -> &VisualMap {
2905        &self.map
2906    }
2907
2908    pub const fn map_mut(&mut self) -> &mut VisualMap {
2909        &mut self.map
2910    }
2911
2912    /// Synchronize the sparse factor lifecycle after a caller commits a
2913    /// keyframe outside [`Self::process_frame`], such as a calibrated-stereo
2914    /// segment restart. Returns `None` when the graph is disabled or the
2915    /// keyframe is not present in the map.
2916    pub fn sync_sparse_factor_graph_keyframe(
2917        &mut self,
2918        keyframe_id: u64,
2919    ) -> Option<SparseFactorGraphUpdateStats> {
2920        if !self.map.keyframes.contains_key(&keyframe_id) {
2921            return None;
2922        }
2923        self.sparse_factor_graph_state
2924            .as_mut()
2925            .map(|graph| graph.update_from_map(&self.map, keyframe_id))
2926    }
2927
2928    /// Run the appearance-based pairwise loop scanner over every keyframe
2929    /// currently in `self.map`. Returns the verifier-accepted pairs as
2930    /// [`LoopClosureCandidate`]s with `verification` populated and
2931    /// `geometrically_verified = true` — the same shape `process_frame`'s
2932    /// shared-landmark detector emits, so callers can mix the two streams.
2933    /// Unlike [`Self::process_frame`], this runs `O(K²)` over the keyframe
2934    /// count and is meant for periodic (every-N-frames) or end-of-session
2935    /// use rather than every frame. Each accepted pair has
2936    /// `query_frame_id` set to the later keyframe and `matched_keyframe_id`
2937    /// set to the earlier — same convention as `LoopClosureConstraint`.
2938    /// `shared_landmark_count` is filled with the verifier inlier count
2939    /// (no map-side landmark intersection is computed) so candidates are
2940    /// directly consumable by [`LoopClosureConstraint::from_verified_candidate`].
2941    pub fn scan_appearance_loops<Mat, V>(
2942        &self,
2943        matcher: &Mat,
2944        verifier: &V,
2945        camera: &Camera,
2946        settings: &AppearanceLoopScannerSettings,
2947    ) -> Vec<LoopClosureCandidate>
2948    where
2949        Mat: Matcher,
2950        V: LoopClosureVerifier,
2951    {
2952        // Sort keyframes by id for deterministic pair ordering.
2953        let mut kfs: Vec<(&u64, &Keyframe)> = self.map.keyframes.iter().collect();
2954        kfs.sort_by_key(|(id, _)| *id);
2955        let views: Vec<PairwiseKeyframeView> = kfs
2956            .iter()
2957            .map(|(_, kf)| PairwiseKeyframeView {
2958                frame_id: kf.frame.id,
2959                keypoints: &kf.frame.keypoints,
2960                descriptors: &kf.frame.descriptors,
2961            })
2962            .collect();
2963        scan_pairwise_loop_closures(
2964            &views,
2965            matcher,
2966            verifier,
2967            camera,
2968            &PairwiseLoopClosureScannerConfig {
2969                min_keyframe_id_gap: settings.min_keyframe_id_gap,
2970                min_matches: settings.min_matches,
2971            },
2972        )
2973    }
2974}
2975
2976/// Tunables for [`OnlineSlamPipeline::scan_appearance_loops`]. Mirrors
2977/// [`PairwiseLoopClosureScannerConfig`] but with names that emphasise the
2978/// pipeline-level use ("how aggressively should the periodic scan run?").
2979/// Defaults are chosen so a typical local-mapping window doesn't get
2980/// confused for a loop, and so visually disjoint keyframes are rejected
2981/// before the verifier ever fires.
2982#[derive(Debug, Clone, Copy, PartialEq)]
2983pub struct AppearanceLoopScannerSettings {
2984    /// Minimum frame-id gap between two keyframes for the pair to be
2985    /// considered. Set this larger than the local-mapping window so the
2986    /// scanner never proposes a "loop" between adjacent keyframes that
2987    /// share most of their tracks anyway.
2988    pub min_keyframe_id_gap: u64,
2989    /// Minimum number of brute-force descriptor matches a pair needs
2990    /// before its 2D-2D correspondences are even handed to the verifier.
2991    pub min_matches: usize,
2992}
2993
2994impl Default for AppearanceLoopScannerSettings {
2995    fn default() -> Self {
2996        Self {
2997            min_keyframe_id_gap: 30,
2998            min_matches: 30,
2999        }
3000    }
3001}
3002
3003impl<P, Motion, K, Tri> OnlineSlamPipeline<Tracker<P, Motion>, LocalMappingPipeline<K, Tri>>
3004where
3005    P: FrameLocalizer,
3006    Motion: MotionModel,
3007    K: KeyframePolicy,
3008    Tri: Triangulator,
3009{
3010    pub fn process_frame<I>(&mut self, frame: &Frame, candidates: I) -> OnlineSlamResult
3011    where
3012        I: IntoIterator<Item = LandmarkCandidate>,
3013    {
3014        self.process_frame_with_metric_points(frame, candidates, &HashMap::new())
3015    }
3016
3017    /// Process a frame while exposing independently triangulated metric 3D
3018    /// points in the current camera frame, keyed by query keypoint index.
3019    /// The lookup is consumed only by appearance-loop Sim3 verification;
3020    /// tracking and mapping retain the existing `process_frame` behaviour.
3021    pub fn process_frame_with_metric_points<I>(
3022        &mut self,
3023        frame: &Frame,
3024        candidates: I,
3025        metric_points_camera: &HashMap<usize, Point3<f64>>,
3026    ) -> OnlineSlamResult
3027    where
3028        I: IntoIterator<Item = LandmarkCandidate>,
3029    {
3030        let mut tracking = self.tracker.track_frame(frame, &self.map);
3031        // Relocalization-on-tracker-death: if the primary attempt
3032        // failed and the stage is enabled, run a fresh PnP against the
3033        // full map via the pipeline's owned `LocalizationPipeline`. On
3034        // acceptance, override the tracker's history with the recovered
3035        // result so the rest of `process_frame` (loop detection,
3036        // mapper, IMU staging, etc.) sees a successful frame.
3037        let relocalization_stats = self.maybe_run_relocalization(frame, &mut tracking);
3038        let mut mapping = None;
3039        let mut applied_update = None;
3040        let mut loop_closure_candidates =
3041            detect_loop_closure_candidates(frame, &tracking, &self.map, &self.config.loop_closure);
3042
3043        if tracking.localization.success {
3044            let keyframe = keyframe_from_tracking_result(frame, &tracking);
3045            let mapping_result = self
3046                .mapper
3047                .process_keyframe(&self.map, &tracking, keyframe, candidates);
3048            if self.config.apply_map_updates && mapping_result.staged_update_validation.is_valid() {
3049                if let Ok(applied) = mapping_result.staged_update.clone().apply_to(&mut self.map) {
3050                    if applied.keyframe_count > 0 {
3051                        record_tracking_observation_confidences(&mut self.map, frame.id, &tracking);
3052                    }
3053                    applied_update = Some(applied);
3054                }
3055            }
3056            mapping = Some(mapping_result);
3057        }
3058
3059        // When IMU is configured and the mapper registered a new keyframe
3060        // at this frame, snapshot the running pre-integration window into
3061        // an `ImuPreintegrationFactor` connecting the previous keyframe to
3062        // this one, then reset the integrator so the next window starts
3063        // fresh. The factor is exposed both inline on the result and via
3064        // `take_pending_imu_factor()` so callers can pick whichever shape
3065        // fits their pose-graph / BA glue.
3066        let imu_factor = self.stage_imu_factor_on_new_keyframe(frame, applied_update.as_ref());
3067        // Run the VI init step AFTER `stage_imu_factor_on_new_keyframe`
3068        // so that on the success frame the just-promoted keyframe id is
3069        // already in `imu_state.last_keyframe_id` and the staged factor
3070        // (if any) has already been discarded by the stale-factor gate.
3071        // The step is a no-op when VI init is disabled or terminal.
3072        let vi_init = self.run_vi_init_step(frame, applied_update.as_ref());
3073        let just_promoted_vi_init =
3074            matches!(vi_init, Some(ViInitializationEvent::Succeeded { .. }));
3075        // Motion-based initialization must run before local VI-BA. In the
3076        // moving-start fallback, static init has terminally given up but the
3077        // navigation state is still uninitialized; running BA in that gap
3078        // would optimize with placeholder zero velocity/bias and corrupt the
3079        // visual map before VIBA1 gets a chance to recover them.
3080        let vi_motion_init =
3081            self.run_motion_vi_init_step(frame, applied_update.as_ref(), imu_factor.as_ref());
3082        let mut local_vi_ba = self.maybe_run_local_vi_ba(imu_factor.clone());
3083        // Phase-16: when VI-init promoted *this frame* and the config
3084        // opted in, force a sliding-window BA pass on the banked
3085        // factors. Bypasses the new-factor gate inside
3086        // `maybe_run_local_vi_ba` so the post-promotion refinement
3087        // doesn't have to wait for the next keyframe registration —
3088        // critical when the visual tracker is fragile and the next KF
3089        // arrives late or never.
3090        let run_at_promotion = self
3091            .config
3092            .local_vi_ba
3093            .as_ref()
3094            .is_some_and(|c| c.run_at_vi_init_promotion);
3095        if just_promoted_vi_init && run_at_promotion && local_vi_ba.is_none() {
3096            if let Some(state) = self.local_vi_ba_state.as_mut() {
3097                local_vi_ba = crate::online_slam_vi_ba::run_local_vi_ba(&mut self.map, state);
3098            }
3099        }
3100        let sparse_factor_graph =
3101            self.maybe_update_sparse_factor_graph(frame.id, applied_update.as_ref());
3102        // Visual-only covisibility local BA runs after the per-keyframe
3103        // visual/VI stages so the map reflects the just-finalised active
3104        // keyframe, and before pose-graph refinement so PGO mirrors the
3105        // post-local-BA pose.
3106        let covisibility_local_ba =
3107            self.maybe_run_covisibility_local_ba(frame, applied_update.as_ref());
3108
3109        // Online loop-closure + pose-graph refinement runs LAST so the
3110        // graph mirrors the just-finalised keyframe pose (post local-VI-
3111        // BA) before PGO write-back. No-op when the stage is disabled or
3112        // no keyframe was registered this frame.
3113        let pose_graph_refinement = self.maybe_run_loop_closure_refinement(
3114            frame,
3115            &tracking,
3116            applied_update.as_ref(),
3117            &mut loop_closure_candidates,
3118            metric_points_camera,
3119        );
3120        if self
3121            .local_vi_ba_state
3122            .as_ref()
3123            .is_some_and(|s| !s.pending_recovered_pose_factors.is_empty())
3124        {
3125            let injected = self.maybe_inject_recovered_factors();
3126            if let Some(ref mut stats) = local_vi_ba.as_mut() {
3127                stats.recovered_marginal_factors_injected = injected;
3128            }
3129        }
3130
3131        OnlineSlamResult {
3132            tracking,
3133            mapping,
3134            applied_update,
3135            loop_closure_candidates,
3136            imu_factor,
3137            local_vi_ba,
3138            sparse_factor_graph,
3139            map_keyframe_count: self.map.keyframes.len(),
3140            map_landmark_count: self.map.landmarks.len(),
3141            vi_init,
3142            vi_motion_init,
3143            covisibility_local_ba,
3144            pose_graph_refinement,
3145            relocalization: relocalization_stats,
3146        }
3147    }
3148
3149    fn maybe_update_sparse_factor_graph(
3150        &mut self,
3151        frame_id: u64,
3152        applied_update: Option<&AppliedMapUpdate>,
3153    ) -> Option<SparseFactorGraphUpdateStats> {
3154        applied_update.filter(|update| update.keyframe_count > 0)?;
3155        self.sync_sparse_factor_graph_keyframe(frame_id)
3156    }
3157
3158    /// Relocalization-on-tracker-death. Runs only when (a) the
3159    /// `relocalization` stage is configured AND (b) the primary
3160    /// `track_frame` call returned `localization.success == false`.
3161    /// Re-runs PnP against the full visual map via the stage's owned
3162    /// [`LocalizationPipeline`], gates the recovered solution against
3163    /// the configured thresholds, and on acceptance overwrites the
3164    /// tracker's per-frame history via
3165    /// [`Tracker::accept_relocalization_result`] so the rest of
3166    /// `process_frame` sees a successful frame. Returns
3167    /// `Some(stats)` whenever the stage actually ran; `None` when
3168    /// disabled OR primary tracking already succeeded.
3169    fn maybe_run_relocalization(
3170        &mut self,
3171        frame: &Frame,
3172        tracking: &mut TrackingResult,
3173    ) -> Option<OnlineSlamRelocalizationStats> {
3174        let state = self.relocalization_state.as_mut()?;
3175        if tracking.localization.success {
3176            state.consecutive_failed_attempts = 0;
3177            state.pending_confirmation = None;
3178            return None;
3179        }
3180        if state
3181            .config
3182            .max_consecutive_failed_attempts
3183            .is_some_and(|max| state.consecutive_failed_attempts >= max)
3184        {
3185            state.budget_skip_count = state.budget_skip_count.saturating_add(1);
3186            return None;
3187        }
3188        let attempt_interval_frames = state.config.attempt_interval_frames.max(1);
3189        if let Some(last_attempt_frame_id) = state.last_attempt_frame_id {
3190            if frame.id.saturating_sub(last_attempt_frame_id) < attempt_interval_frames {
3191                return None;
3192            }
3193        }
3194        state.trigger_count += 1;
3195        state.last_attempt_frame_id = Some(frame.id);
3196        let (recovered, mut stats, accept, tried_broader_descriptor_store) = {
3197            let pose_prior = if state.config.pose_prior_candidate_radius_meters.is_some() {
3198                self.tracker.pose_prior_for_frame(frame)
3199            } else {
3200                None
3201            };
3202            let candidate_radius = state.config.pose_prior_candidate_radius_meters;
3203            let localize_with_store =
3204                |descriptor_store: &visloc_core::types::LandmarkDescriptorStore| {
3205                    if pose_prior.is_some() {
3206                        state
3207                            .localizer
3208                            .localize_frame_with_pose_prior_warm_start_and_descriptor_store(
3209                                frame,
3210                                &self.map,
3211                                descriptor_store,
3212                                pose_prior.as_ref(),
3213                                candidate_radius,
3214                            )
3215                    } else {
3216                        state.localizer.localize_frame_with_descriptor_store(
3217                            frame,
3218                            &self.map,
3219                            descriptor_store,
3220                        )
3221                    }
3222                };
3223            let build_attempt_stats =
3224                |recovered: &visloc_core::types::LocalizationResult,
3225                 descriptor_store_landmark_count: usize,
3226                 covisibility_local_descriptor_store_landmark_count: Option<usize>,
3227                 appearance_descriptor_store_landmark_count: Option<usize>,
3228                 broader_descriptor_store_landmark_count: Option<usize>,
3229                 tried_covisibility_local_descriptor_store: bool,
3230                 used_covisibility_local_descriptor_store: bool,
3231                 tried_appearance_descriptor_store: bool,
3232                 used_appearance_descriptor_store: bool,
3233                 tried_broader_descriptor_store_fallback: bool,
3234                 broader_descriptor_store_retry_skipped_by_interval: bool,
3235                 used_broader_descriptor_store_fallback: bool,
3236                 covisibility_reference_keyframe_id: Option<u64>,
3237                 appearance_candidate_keyframe_count: usize,
3238                 appearance_best_similarity: Option<f32>,
3239                 appearance_best_keyframe_id: Option<u64>,
3240                 appearance_candidates: Vec<OnlineSlamRelocalizationAppearanceCandidate>| {
3241                    let mut stats = OnlineSlamRelocalizationStats {
3242                        attempted: true,
3243                        localization_success: recovered.success,
3244                        succeeded: false,
3245                        inlier_count: recovered.inlier_count,
3246                        inlier_ratio: recovered.inlier_ratio,
3247                        correspondence_count: recovered.correspondence_count,
3248                        mean_reprojection_error: recovered.reprojection_error,
3249                        translation_from_last_success_meters: None,
3250                        translation_per_frame_from_last_success_meters: None,
3251                        inlier_depth_median_meters: None,
3252                        last_success_inlier_depth_median_meters: None,
3253                        inlier_depth_median_ratio_to_last_success: None,
3254                        passed_acceptance_gates: false,
3255                        confirmation_count: 0,
3256                        confirmation_required_count: state
3257                            .config
3258                            .confirmation_required_recoveries
3259                            .max(1),
3260                        confirmation_translation_per_frame_from_previous_meters: None,
3261                        descriptor_store_landmark_count,
3262                        covisibility_local_descriptor_store_landmark_count,
3263                        appearance_descriptor_store_landmark_count,
3264                        broader_descriptor_store_landmark_count,
3265                        tried_covisibility_local_descriptor_store,
3266                        used_covisibility_local_descriptor_store,
3267                        tried_appearance_descriptor_store,
3268                        used_appearance_descriptor_store,
3269                        tried_broader_descriptor_store_fallback,
3270                        broader_descriptor_store_retry_skipped_by_interval,
3271                        used_broader_descriptor_store_fallback,
3272                        covisibility_reference_keyframe_id,
3273                        appearance_candidate_keyframe_count,
3274                        appearance_best_similarity,
3275                        appearance_best_keyframe_id,
3276                        appearance_candidates,
3277                    };
3278                    if let (Some(last_pose), Some(recovered_pose)) =
3279                        (self.tracker.last_successful_pose(), recovered.pose.as_ref())
3280                    {
3281                        let translation = (recovered_pose.camera_center_world()
3282                            - last_pose.camera_center_world())
3283                        .norm();
3284                        stats.translation_from_last_success_meters = Some(translation);
3285                        if let Some(last_frame_id) = self.tracker.last_successful_frame_id() {
3286                            let frame_gap = frame.id.saturating_sub(last_frame_id).max(1) as f64;
3287                            stats.translation_per_frame_from_last_success_meters =
3288                                Some(translation / frame_gap);
3289                        }
3290                        stats.inlier_depth_median_meters = median_positive_depth_for_landmarks(
3291                            &self.map,
3292                            recovered_pose,
3293                            &recovered.inlier_landmark_ids,
3294                        );
3295                        stats.last_success_inlier_depth_median_meters =
3296                            median_positive_depth_for_landmarks(
3297                                &self.map,
3298                                last_pose,
3299                                &recovered.inlier_landmark_ids,
3300                            );
3301                        if let (Some(recovered_depth), Some(last_depth)) = (
3302                            stats.inlier_depth_median_meters,
3303                            stats.last_success_inlier_depth_median_meters,
3304                        ) {
3305                            if last_depth > 0.0 {
3306                                stats.inlier_depth_median_ratio_to_last_success =
3307                                    Some(recovered_depth / last_depth);
3308                            }
3309                        }
3310                    }
3311                    let basic_accept = recovered.success
3312                        && recovered.inlier_count >= state.config.min_inliers
3313                        && recovered.inlier_ratio >= state.config.min_inlier_ratio
3314                        && match (
3315                            state.config.max_mean_reprojection_error,
3316                            recovered.reprojection_error,
3317                        ) {
3318                            (Some(max), Some(actual)) => actual <= max,
3319                            (Some(_), None) => false,
3320                            (None, _) => true,
3321                        };
3322                    let imu_accept = if let Some(max_dist) =
3323                        state.config.max_translation_from_imu_prediction_meters
3324                    {
3325                        match (
3326                            self.tracker.pose_prior_for_frame(frame),
3327                            recovered.pose.as_ref(),
3328                        ) {
3329                            (Some(predicted), Some(recovered_pose)) => {
3330                                let predicted_centre =
3331                                    predicted.world_to_camera.inverse().translation;
3332                                let recovered_centre =
3333                                    recovered_pose.world_to_camera.inverse().translation;
3334                                (recovered_centre - predicted_centre).norm() <= max_dist
3335                            }
3336                            _ => true,
3337                        }
3338                    } else {
3339                        true
3340                    };
3341                    let continuity_accept = match (
3342                        state
3343                            .config
3344                            .max_translation_per_frame_from_last_success_meters,
3345                        stats.translation_per_frame_from_last_success_meters,
3346                    ) {
3347                        (Some(max), Some(actual)) => actual <= max,
3348                        (Some(_), None) => true,
3349                        (None, _) => true,
3350                    };
3351                    let depth_ratio_accept = match stats.inlier_depth_median_ratio_to_last_success {
3352                        Some(ratio) => {
3353                            state
3354                                .config
3355                                .min_inlier_depth_median_ratio_to_last_success
3356                                .is_none_or(|min| ratio >= min)
3357                                && state
3358                                    .config
3359                                    .max_inlier_depth_median_ratio_to_last_success
3360                                    .is_none_or(|max| ratio <= max)
3361                        }
3362                        None => true,
3363                    };
3364                    let accept =
3365                        basic_accept && imu_accept && continuity_accept && depth_ratio_accept;
3366                    stats.passed_acceptance_gates = accept;
3367                    (stats, accept)
3368                };
3369
3370            let mut broader_descriptor_store =
3371                Some(relocalization_recent_keyframe_descriptor_store(
3372                    &self.map,
3373                    state.config.recent_keyframe_window,
3374                ));
3375            let appearance_store =
3376                state
3377                    .config
3378                    .appearance_retrieval_map
3379                    .as_ref()
3380                    .and_then(|appearance_config| {
3381                        relocalization_appearance_descriptor_store(
3382                            &self.map,
3383                            frame,
3384                            appearance_config,
3385                        )
3386                    });
3387            let covis_store =
3388                state
3389                    .config
3390                    .covisibility_local_map
3391                    .as_ref()
3392                    .and_then(|covis_config| {
3393                        self.tracker
3394                            .last_successful_frame_id()
3395                            .and_then(|last_id| {
3396                                relocalization_pick_covisibility_reference_keyframe(
3397                                    &self.map, last_id,
3398                                )
3399                            })
3400                            .and_then(|reference_id| {
3401                                relocalization_covisibility_descriptor_store(
3402                                    &self.map,
3403                                    reference_id,
3404                                    covis_config,
3405                                )
3406                                .map(|store| (reference_id, store))
3407                            })
3408                    });
3409            let (
3410                initial_descriptor_store,
3411                initial_store_kind,
3412                reference_keyframe_id,
3413                appearance_candidate_keyframe_count,
3414                appearance_best_similarity,
3415                appearance_best_keyframe_id,
3416                appearance_candidates,
3417            ) = if let Some(appearance) = appearance_store {
3418                (
3419                    appearance.store,
3420                    RelocalizationDescriptorStoreKind::AppearanceRetrieval,
3421                    None,
3422                    appearance.candidate_keyframe_count,
3423                    appearance.best_similarity,
3424                    appearance.best_keyframe_id,
3425                    appearance.candidates,
3426                )
3427            } else if let Some((reference_keyframe_id, store)) = covis_store {
3428                (
3429                    store,
3430                    RelocalizationDescriptorStoreKind::CovisibilityLocal,
3431                    Some(reference_keyframe_id),
3432                    0,
3433                    None,
3434                    None,
3435                    Vec::new(),
3436                )
3437            } else {
3438                (
3439                    broader_descriptor_store
3440                        .take()
3441                        .expect("broader descriptor store was built"),
3442                    RelocalizationDescriptorStoreKind::Broader,
3443                    None,
3444                    0,
3445                    None,
3446                    None,
3447                    Vec::new(),
3448                )
3449            };
3450            let fallback_to_broader_store_on_failure = match initial_store_kind {
3451                RelocalizationDescriptorStoreKind::AppearanceRetrieval => state
3452                    .config
3453                    .appearance_retrieval_map
3454                    .as_ref()
3455                    .is_some_and(|config| config.fallback_to_broader_store_on_failure),
3456                RelocalizationDescriptorStoreKind::CovisibilityLocal => state
3457                    .config
3458                    .covisibility_local_map
3459                    .as_ref()
3460                    .is_some_and(|config| config.fallback_to_broader_store_on_failure),
3461                RelocalizationDescriptorStoreKind::Broader => false,
3462            };
3463            let compare_broader_store_on_success = match initial_store_kind {
3464                RelocalizationDescriptorStoreKind::AppearanceRetrieval => state
3465                    .config
3466                    .appearance_retrieval_map
3467                    .as_ref()
3468                    .is_some_and(|config| config.compare_broader_store_on_success),
3469                RelocalizationDescriptorStoreKind::CovisibilityLocal => state
3470                    .config
3471                    .covisibility_local_map
3472                    .as_ref()
3473                    .is_some_and(|config| config.compare_broader_store_on_success),
3474                RelocalizationDescriptorStoreKind::Broader => false,
3475            };
3476            let broader_store_retry_interval_frames = match initial_store_kind {
3477                RelocalizationDescriptorStoreKind::AppearanceRetrieval => state
3478                    .config
3479                    .appearance_retrieval_map
3480                    .as_ref()
3481                    .map_or(1, |config| {
3482                        config.broader_store_retry_interval_frames.max(1)
3483                    }),
3484                RelocalizationDescriptorStoreKind::CovisibilityLocal => state
3485                    .config
3486                    .covisibility_local_map
3487                    .as_ref()
3488                    .map_or(1, |config| {
3489                        config.broader_store_retry_interval_frames.max(1)
3490                    }),
3491                RelocalizationDescriptorStoreKind::Broader => 1,
3492            };
3493            let broader_retry_interval_allows = state
3494                .last_broader_descriptor_store_retry_frame_id
3495                .is_none_or(|last_frame_id| {
3496                    frame.id.saturating_sub(last_frame_id) >= broader_store_retry_interval_frames
3497                });
3498            let initial_is_covisibility =
3499                initial_store_kind == RelocalizationDescriptorStoreKind::CovisibilityLocal;
3500            let initial_is_appearance =
3501                initial_store_kind == RelocalizationDescriptorStoreKind::AppearanceRetrieval;
3502            let initial_is_narrow =
3503                initial_store_kind != RelocalizationDescriptorStoreKind::Broader;
3504            let covisibility_local_descriptor_store_landmark_count =
3505                initial_is_covisibility.then_some(initial_descriptor_store.len());
3506            let appearance_descriptor_store_landmark_count =
3507                initial_is_appearance.then_some(initial_descriptor_store.len());
3508            let mut recovered = localize_with_store(&initial_descriptor_store);
3509            let (mut stats, mut accept) = build_attempt_stats(
3510                &recovered,
3511                initial_descriptor_store.len(),
3512                covisibility_local_descriptor_store_landmark_count,
3513                appearance_descriptor_store_landmark_count,
3514                None,
3515                initial_is_covisibility,
3516                initial_is_covisibility,
3517                initial_is_appearance,
3518                initial_is_appearance,
3519                false,
3520                false,
3521                false,
3522                reference_keyframe_id,
3523                appearance_candidate_keyframe_count,
3524                appearance_best_similarity,
3525                appearance_best_keyframe_id,
3526                appearance_candidates.clone(),
3527            );
3528            let wants_broader_retry = initial_is_narrow
3529                && ((!accept && fallback_to_broader_store_on_failure)
3530                    || (accept && compare_broader_store_on_success));
3531            let should_try_broader = wants_broader_retry && broader_retry_interval_allows;
3532            if wants_broader_retry && !broader_retry_interval_allows {
3533                stats.broader_descriptor_store_retry_skipped_by_interval = true;
3534            }
3535            if should_try_broader {
3536                let broader_store = broader_descriptor_store.take().unwrap_or_else(|| {
3537                    relocalization_recent_keyframe_descriptor_store(
3538                        &self.map,
3539                        state.config.recent_keyframe_window,
3540                    )
3541                });
3542                let broader_store_len = broader_store.len();
3543                let broader_recovered = localize_with_store(&broader_store);
3544                let (broader_stats, broader_accept) = build_attempt_stats(
3545                    &broader_recovered,
3546                    broader_store_len,
3547                    covisibility_local_descriptor_store_landmark_count,
3548                    appearance_descriptor_store_landmark_count,
3549                    Some(broader_store_len),
3550                    initial_is_covisibility,
3551                    false,
3552                    initial_is_appearance,
3553                    false,
3554                    true,
3555                    false,
3556                    true,
3557                    reference_keyframe_id,
3558                    appearance_candidate_keyframe_count,
3559                    appearance_best_similarity,
3560                    appearance_best_keyframe_id,
3561                    appearance_candidates,
3562                );
3563                stats.tried_broader_descriptor_store_fallback = true;
3564                stats.broader_descriptor_store_landmark_count = Some(broader_store_len);
3565                let use_broader = if !accept {
3566                    true
3567                } else {
3568                    broader_accept
3569                        && relocalization_result_has_better_score(&broader_recovered, &recovered)
3570                };
3571                if use_broader {
3572                    recovered = broader_recovered;
3573                    stats = broader_stats;
3574                    accept = broader_accept;
3575                }
3576            }
3577            (recovered, stats, accept, should_try_broader)
3578        };
3579        if tried_broader_descriptor_store {
3580            state.last_broader_descriptor_store_retry_frame_id = Some(frame.id);
3581        }
3582        if !accept {
3583            state.consecutive_failed_attempts = state.consecutive_failed_attempts.saturating_add(1);
3584            state.pending_confirmation = None;
3585            return Some(stats);
3586        }
3587        let confirmation_required = state.config.confirmation_required_recoveries.max(1);
3588        stats.confirmation_required_count = confirmation_required;
3589        if confirmation_required > 1 {
3590            let Some(recovered_pose) = recovered.pose.as_ref() else {
3591                state.consecutive_failed_attempts =
3592                    state.consecutive_failed_attempts.saturating_add(1);
3593                state.pending_confirmation = None;
3594                stats.passed_acceptance_gates = false;
3595                return Some(stats);
3596            };
3597            let mut confirmation_count = 1usize;
3598            if let Some(pending) = state.pending_confirmation.as_ref() {
3599                let translation = (recovered_pose.camera_center_world()
3600                    - pending.pose.camera_center_world())
3601                .norm();
3602                let frame_gap = frame.id.saturating_sub(pending.frame_id).max(1) as f64;
3603                let translation_per_frame = translation / frame_gap;
3604                stats.confirmation_translation_per_frame_from_previous_meters =
3605                    Some(translation_per_frame);
3606                let chain_is_consistent = state
3607                    .config
3608                    .confirmation_max_translation_per_frame_meters
3609                    .is_none_or(|max| translation_per_frame <= max);
3610                if chain_is_consistent {
3611                    confirmation_count = pending.count.saturating_add(1);
3612                }
3613            }
3614            stats.confirmation_count = confirmation_count;
3615            if confirmation_count < confirmation_required {
3616                state.pending_confirmation = Some(OnlineSlamRelocalizationPendingConfirmation {
3617                    frame_id: frame.id,
3618                    pose: recovered_pose.clone(),
3619                    count: confirmation_count,
3620                });
3621                return Some(stats);
3622            }
3623            state.pending_confirmation = None;
3624        } else {
3625            stats.confirmation_count = 1;
3626            state.pending_confirmation = None;
3627        }
3628        let recovered_tracking = TrackingResult {
3629            frame_id: frame.id,
3630            state: visloc_tracking::TrackingState::Tracking,
3631            event: visloc_tracking::TrackingEvent::Relocalized,
3632            successive_failures: 0,
3633            pose_prior: tracking.pose_prior.clone(),
3634            used_pose_prior: tracking.used_pose_prior,
3635            used_external_localization_prior: tracking.used_external_localization_prior,
3636            external_localization_prior_radius: tracking.external_localization_prior_radius,
3637            tracking_failure_reason: None,
3638            map_landmark_count: tracking.map_landmark_count,
3639            map_stats: tracking.map_stats,
3640            localization: recovered,
3641            covisibility_local_map_size: tracking.covisibility_local_map_size,
3642        };
3643        self.tracker
3644            .accept_relocalization_result(recovered_tracking.clone());
3645        state.success_count += 1;
3646        state.consecutive_failed_attempts = 0;
3647        state.last_success_frame_id = Some(frame.id);
3648        stats.succeeded = true;
3649        *tracking = recovered_tracking;
3650        Some(stats)
3651    }
3652
3653    /// Online loop-closure + pose-graph refinement. Runs verifier on the
3654    /// candidates produced by [`detect_loop_closure_candidates`] this
3655    /// frame, folds verified constraints into a running [`PoseGraph`]
3656    /// that mirrors the registered keyframes, and triggers
3657    /// [`PoseGraph::optimize_se3_iterative`] when the new-constraint
3658    /// threshold has been reached. On a converged solve the optimised
3659    /// poses are written back into `self.map.keyframes[id].frame.pose`.
3660    ///
3661    /// Returns `None` when the stage is disabled OR when the current
3662    /// frame did not register a new keyframe (the running graph has no
3663    /// node to anchor verifier output to). Returns `Some(stats)` whenever
3664    /// the verifier was actually run this frame; `stats.pose_graph_result`
3665    /// is `Some` only on the frames where PGO fired.
3666    fn maybe_run_loop_closure_refinement(
3667        &mut self,
3668        frame: &Frame,
3669        tracking: &TrackingResult,
3670        applied_update: Option<&AppliedMapUpdate>,
3671        loop_closure_candidates: &mut [LoopClosureCandidate],
3672        metric_points_camera: &HashMap<usize, Point3<f64>>,
3673    ) -> Option<OnlineSlamLoopClosureRefinementStats> {
3674        let state = self.pose_graph_state.as_mut()?;
3675        // The pipeline mirrors keyframes into the running graph on
3676        // every new-keyframe frame. Without a new keyframe this call,
3677        // the verifier output would have no node to anchor against
3678        // (loop constraints target the just-finalised keyframe id),
3679        // so skip the entire stage.
3680        applied_update?;
3681        let new_keyframe_id = frame.id;
3682        // Snapshot the new keyframe's pose from the map (which already
3683        // reflects local-VI-BA refinement applied earlier this frame).
3684        let new_pose = self
3685            .map
3686            .keyframes
3687            .get(&new_keyframe_id)
3688            .and_then(|kf| kf.frame.pose.clone())?;
3689        let mut stats = OnlineSlamLoopClosureRefinementStats::default();
3690
3691        // Add the node + the sequential edge from the previous
3692        // keyframe in registration order. Anchor on the first registered
3693        // keyframe so the absolute frame stays fixed across PGO solves.
3694        let prev_keyframe_id = state.keyframe_order.last().copied();
3695        state.graph.add_pose(new_keyframe_id, new_pose.clone());
3696        if let Some(sim3_graph) = state.sim3_graph.as_mut() {
3697            sim3_graph.add_pose(
3698                new_keyframe_id,
3699                sim3_at_unit_scale(&new_pose.world_to_camera),
3700            );
3701        }
3702        if state.keyframe_order.is_empty() {
3703            state.graph.anchor(new_keyframe_id);
3704            if let Some(sim3_graph) = state.sim3_graph.as_mut() {
3705                sim3_graph.anchor(new_keyframe_id);
3706            }
3707        } else if let Some(prev_id) = prev_keyframe_id {
3708            if let Some(prev_pose) = state.graph.poses.get(&prev_id).cloned() {
3709                let relative = relative_world_to_camera(&prev_pose, &new_pose);
3710                if let Some(sim3_graph) = state.sim3_graph.as_mut() {
3711                    // Scale-1 measurement: the odometry chain's relative
3712                    // motion between two consecutive keyframes is derived
3713                    // from the (already metric) tracked poses, same as the
3714                    // `Se3` path's sequential edge — no independent scale
3715                    // source exists between adjacent frames.
3716                    sim3_graph.add_edge(
3717                        prev_id,
3718                        new_keyframe_id,
3719                        sim3_at_unit_scale(&relative),
3720                        1.0,
3721                    );
3722                }
3723                let sequential_information =
3724                    state
3725                        .config
3726                        .loop_pose_information
3727                        .map(|information_config| {
3728                            if !matches!(state.config.solver, LoopRefinementSolver::Se3) {
3729                                return Err(LoopPoseInformationFailure::UnsupportedSolver);
3730                            }
3731                            let pnp_inliers: Vec<(usize, u64)> = tracking
3732                                .localization
3733                                .inlier_query_indices
3734                                .iter()
3735                                .copied()
3736                                .zip(tracking.localization.inlier_landmark_ids.iter().copied())
3737                                .collect();
3738                            let measurement = LoopClosureConstraint {
3739                                from_keyframe_id: prev_id,
3740                                to_keyframe_id: new_keyframe_id,
3741                                relative_pose: relative.clone(),
3742                                inlier_count: pnp_inliers.len(),
3743                                inlier_ratio: 1.0,
3744                                mean_sampson_error: 0.0,
3745                                score: pnp_inliers.len() as f64,
3746                            };
3747                            estimate_loop_pose_information(
3748                                &self.map,
3749                                frame,
3750                                &state.config.camera,
3751                                &measurement,
3752                                &pnp_inliers,
3753                                information_config,
3754                            )
3755                        });
3756                if let Some(Ok((information, diagnostic))) = sequential_information {
3757                    state.graph.add_edge_with_information(
3758                        prev_id,
3759                        new_keyframe_id,
3760                        relative,
3761                        PoseGraphEdgeKind::Sequential,
3762                        information,
3763                    );
3764                    stats.sequential_edges_with_pose_information += 1;
3765                    stats
3766                        .sequential_pose_information_diagnostics
3767                        .push(diagnostic);
3768                } else {
3769                    state
3770                        .graph
3771                        .add_sequential_edge(prev_id, new_keyframe_id, relative);
3772                    if state.config.loop_pose_information.is_some() {
3773                        stats.sequential_pose_information_fallbacks += 1;
3774                    }
3775                    if let Some(Err(reason)) = sequential_information {
3776                        stats.sequential_pose_information_failures.record(reason);
3777                    }
3778                }
3779            }
3780        }
3781        state.keyframe_order.push(new_keyframe_id);
3782
3783        // Cache this keyframe's mean local descriptor for the appearance-
3784        // based long-range candidate source. Independent of whether
3785        // relocalization is configured — this cache lives on the pose-
3786        // graph refinement state, keyed only on `appearance_candidates`.
3787        if state.config.appearance_candidates.is_some() {
3788            if let Some(mean_descriptor) = relocalization_mean_descriptor(&frame.descriptors) {
3789                state
3790                    .appearance_descriptor_cache
3791                    .insert(new_keyframe_id, mean_descriptor);
3792            }
3793        }
3794
3795        // Verify candidates with the configured backend (see
3796        // `LoopRefinementVerifier`): essential-matrix (default, scale-free —
3797        // every accepted constraint's translation is pinned to
3798        // `verifier_config.default_translation_scale`) or PnP (2D-3D,
3799        // metric translation recovered from the map's triangulated
3800        // landmarks; candidates with too few 2D-3D correspondences are
3801        // rejected outright, never falling back to essential-matrix).
3802        if !loop_closure_candidates.is_empty() {
3803            stats.verified_candidate_count = loop_closure_candidates.len();
3804            match &state.config.verifier {
3805                LoopRefinementVerifier::EssentialMatrix => {
3806                    let verifier = EssentialMatrixLoopClosureVerifier {
3807                        config: state.config.verifier_config,
3808                        ..Default::default()
3809                    };
3810                    verify_loop_closure_candidates(
3811                        loop_closure_candidates,
3812                        frame,
3813                        tracking,
3814                        &self.map,
3815                        &state.config.camera,
3816                        &verifier,
3817                    );
3818                }
3819                LoopRefinementVerifier::Pnp(pnp_config) => {
3820                    let verifier = PnPLoopClosureVerifier {
3821                        ransac: PnPRansac::default(),
3822                        config: *pnp_config,
3823                    };
3824                    verify_loop_closure_candidates_pnp(
3825                        loop_closure_candidates,
3826                        frame,
3827                        tracking,
3828                        &self.map,
3829                        &state.config.camera,
3830                        &verifier,
3831                    );
3832                }
3833            }
3834        }
3835
3836        // Appearance-based long-range candidate stream (opt-in, see
3837        // `LoopAppearanceCandidateConfig`). Independent of the shared-
3838        // landmark stream above: built and PnP-verified regardless of
3839        // whether `detect_loop_closure_candidates` found anything this
3840        // frame, since the whole point is to catch loops the shared-id
3841        // detector structurally cannot see.
3842        let appearance_candidates: Vec<LoopClosureCandidate> = if let Some(appearance_config) =
3843            state.config.appearance_candidates.clone()
3844        {
3845            stats.appearance_ranked_candidate_count =
3846                relocalization_mean_descriptor(&frame.descriptors).map_or(0, |descriptor| {
3847                    rank_appearance_loop_candidate_keyframes(
3848                        &state.appearance_descriptor_cache,
3849                        frame.id,
3850                        &descriptor,
3851                        appearance_config.min_similarity,
3852                        appearance_config.min_keyframe_id_gap,
3853                    )
3854                    .len()
3855                    .min(appearance_config.max_candidates_per_frame.max(1))
3856                });
3857            let mut builder_config = appearance_config.clone();
3858            // ORB-SLAM3 first obtains one strong current-vs-region pose,
3859            // then carries that region into later keyframes. Do not make
3860            // the one-frame builder consume the cross-keyframe count.
3861            builder_config.min_covisible_keyframe_verifications = 1;
3862            let built = build_appearance_loop_candidates_with_diagnostics(
3863                &self.map,
3864                frame,
3865                &state.appearance_descriptor_cache,
3866                &builder_config,
3867                &state.config.camera,
3868            );
3869            stats.appearance_connected_region_rejected_count =
3870                built.connected_region_rejected_count;
3871            stats.appearance_pnp_verified_count = built.pnp_verified_count;
3872            stats.appearance_projection_rejected_count = built.projection_rejected_count;
3873            stats.appearance_covisibility_rejected_count = built.covisibility_rejected_count;
3874            let mut candidates = built.candidates;
3875            let pending_needs_projection =
3876                state
3877                    .appearance_pending_region
3878                    .as_ref()
3879                    .is_some_and(|pending| {
3880                        !candidates.iter().any(|candidate| {
3881                            appearance_regions_overlap(
3882                                &self.map,
3883                                pending.root_keyframe_id,
3884                                candidate.matched_keyframe_id,
3885                                &appearance_config,
3886                            )
3887                        })
3888                    });
3889            if pending_needs_projection {
3890                let projected = verify_pending_appearance_region_by_projection(
3891                    &self.map,
3892                    frame,
3893                    &state.config.camera,
3894                    &appearance_config,
3895                    state
3896                        .appearance_pending_region
3897                        .as_ref()
3898                        .expect("pending projection was requested"),
3899                );
3900                stats.appearance_pending_projection_attempted_count =
3901                    usize::from(projected.attempted);
3902                stats.appearance_pending_projection_verified_count =
3903                    usize::from(projected.candidate.is_some());
3904                stats.appearance_pending_projection_correspondence_count =
3905                    projected.correspondence_count;
3906                stats.appearance_pending_projection_inlier_count = projected.inlier_count;
3907                stats.appearance_pending_projection_search_radius_px = projected.search_radius_px;
3908                if let Some(candidate) = projected.candidate {
3909                    candidates.push(candidate);
3910                }
3911            }
3912            stats.appearance_candidate_count = candidates.len();
3913            stats.appearance_candidate_diagnostics = built.diagnostics;
3914            let (confirmed, waiting, just_confirmed) = confirm_appearance_region_across_keyframes(
3915                &self.map,
3916                frame.id,
3917                candidates,
3918                &appearance_config,
3919                &mut state.appearance_pending_region,
3920            );
3921            stats.appearance_region_confirmation_waiting = waiting;
3922            stats.appearance_region_confirmed_count = usize::from(just_confirmed);
3923            confirmed
3924        } else {
3925            Vec::new()
3926        };
3927
3928        if !loop_closure_candidates.is_empty() || !appearance_candidates.is_empty() {
3929            // PCM front-end screen (optional): snapshot the current odometry
3930            // (graph poses) and the already-admitted closures once, then admit
3931            // a new closure only if it is geometrically consistent with the
3932            // established set — so a wrong closure never enters the graph.
3933            let pcm_cfg = state.config.pcm;
3934            let odometry: BTreeMap<u64, SE3> = if pcm_cfg.is_some() {
3935                state
3936                    .graph
3937                    .poses
3938                    .iter()
3939                    .map(|(id, p)| (*id, p.world_to_camera.clone()))
3940                    .collect()
3941            } else {
3942                BTreeMap::new()
3943            };
3944            let mut admitted: Vec<pcm::LoopMeasurement> = if pcm_cfg.is_some() {
3945                state
3946                    .verified_constraints
3947                    .iter()
3948                    .map(loop_measurement_of)
3949                    .collect()
3950            } else {
3951                Vec::new()
3952            };
3953
3954            // Both streams flow through the identical accept path (PCM /
3955            // covariance gate / graph add / write-back) so folding is
3956            // untouched regardless of which stream a candidate came from.
3957            let tagged_candidates = loop_closure_candidates
3958                .iter()
3959                .map(|candidate| (candidate, LoopClosureCandidateSource::SharedLandmark))
3960                .chain(
3961                    appearance_candidates
3962                        .iter()
3963                        .map(|candidate| (candidate, LoopClosureCandidateSource::Appearance)),
3964                );
3965
3966            for (candidate, source) in tagged_candidates {
3967                let Some(constraint) = LoopClosureConstraint::from_verified_candidate(candidate)
3968                else {
3969                    continue;
3970                };
3971                // Loop edges target the keyframe registered this frame
3972                // (`candidate.query_frame_id == new_keyframe_id`); the
3973                // matched keyframe must already exist in the graph.
3974                if !state.graph.poses.contains_key(&constraint.from_keyframe_id) {
3975                    continue;
3976                }
3977                let measured_sim3_scale =
3978                    if matches!(state.config.solver, LoopRefinementSolver::Sim3(_))
3979                        && source == LoopClosureCandidateSource::Appearance
3980                    {
3981                        let scale = match estimate_loop_sim3_scale_3d3d(
3982                            &self.map,
3983                            constraint.from_keyframe_id,
3984                            constraint.to_keyframe_id,
3985                            &candidate.pnp_query_landmark_pairs,
3986                            metric_points_camera,
3987                        ) {
3988                            Ok(scale) => scale,
3989                            Err(reason) => {
3990                                stats.appearance_scale_estimation_failed_count += 1;
3991                                match reason {
3992                                    Sim3ScaleEstimationFailure::InsufficientPoints => {
3993                                        stats.appearance_scale_insufficient_points_count += 1;
3994                                    }
3995                                    Sim3ScaleEstimationFailure::InsufficientMatches => {
3996                                        stats.appearance_scale_insufficient_matches_count += 1;
3997                                    }
3998                                    Sim3ScaleEstimationFailure::NoConsensus => {
3999                                        stats.appearance_scale_no_consensus_count += 1;
4000                                    }
4001                                }
4002                                // A PnP pose alone contains no scale observation.
4003                                // Do not let an arbitrary scale-1 edge perturb an
4004                                // already accurate map on the Sim3-only path.
4005                                continue;
4006                            }
4007                        };
4008                        if (scale - 1.0).abs() < 0.05 {
4009                            stats.appearance_near_unit_scale_count += 1;
4010                            // This solver option is specifically the scale-drift
4011                            // correction arm. Leave near-unit rigid corrections
4012                            // to the established SE3 path.
4013                            continue;
4014                        }
4015                        Some(scale)
4016                    } else {
4017                        None
4018                    };
4019                let loop_information =
4020                    if let Some(information_config) = state.config.loop_pose_information {
4021                        // The 6×6 matrix describes an SE(3) tangent. Do not
4022                        // silently reuse it for the 7-DoF Sim(3) mirror.
4023                        let estimate = if matches!(state.config.solver, LoopRefinementSolver::Se3) {
4024                            estimate_loop_pose_information(
4025                                &self.map,
4026                                frame,
4027                                &state.config.camera,
4028                                &constraint,
4029                                &candidate.pnp_query_landmark_pairs,
4030                                information_config,
4031                            )
4032                        } else {
4033                            Err(LoopPoseInformationFailure::UnsupportedSolver)
4034                        };
4035                        let (mut information, diagnostic) = match estimate {
4036                            Ok(estimate) => estimate,
4037                            Err(reason) => {
4038                                stats.loop_pose_information_failures.record(reason);
4039                                stats.loop_closures_pose_information_rejected += 1;
4040                                stats
4041                            .rejected_constraints
4042                            .push(OnlineSlamRejectedLoopConstraint {
4043                                from_keyframe_id: constraint.from_keyframe_id,
4044                                to_keyframe_id: constraint.to_keyframe_id,
4045                                inlier_count: constraint.inlier_count,
4046                                translation_norm_m: constraint.relative_pose.translation.norm(),
4047                                relative_pose: constraint.relative_pose.clone(),
4048                                source,
4049                                reason: OnlineSlamLoopConstraintRejectionReason::PoseInformation,
4050                            });
4051                                continue;
4052                            }
4053                        };
4054                        // Preserve the covariance-derived anisotropy while
4055                        // controlling loop strength relative to sequential
4056                        // PnP odometry information.
4057                        information =
4058                            apply_loop_edge_scale(information, information_config.loop_edge_scale);
4059                        stats.loop_pose_information_diagnostics.push(diagnostic);
4060                        state.loop_pose_information.insert(
4061                            (constraint.from_keyframe_id, constraint.to_keyframe_id),
4062                            information,
4063                        );
4064                        Some(information)
4065                    } else {
4066                        None
4067                    };
4068                // Front-end screens (both before the closure enters the graph):
4069                // PCM combinatorial consistency, then the covariance metric gate.
4070                let pcm_measurement = pcm_cfg.as_ref().map(|cfg| {
4071                    let m = loop_measurement_of(&constraint);
4072                    (pcm_admits_loop(&m, &admitted, &odometry, cfg), m)
4073                });
4074                if let Some((false, _)) = pcm_measurement {
4075                    stats.loop_closures_pcm_rejected += 1;
4076                    stats
4077                        .rejected_constraints
4078                        .push(OnlineSlamRejectedLoopConstraint {
4079                            from_keyframe_id: constraint.from_keyframe_id,
4080                            to_keyframe_id: constraint.to_keyframe_id,
4081                            inlier_count: constraint.inlier_count,
4082                            translation_norm_m: constraint.relative_pose.translation.norm(),
4083                            relative_pose: constraint.relative_pose.clone(),
4084                            source,
4085                            reason: OnlineSlamLoopConstraintRejectionReason::Pcm,
4086                        });
4087                    // Hold a deferred-but-verified closure for the batch
4088                    // re-screen, which may promote it once a consensus forms.
4089                    if state.config.pcm_batch_rescreen {
4090                        state.pcm_deferred.push(constraint);
4091                    }
4092                    continue;
4093                }
4094                if let Some(threshold) = state.config.covariance_gate {
4095                    if !covariance_gate_admits(&state.graph, &constraint, threshold) {
4096                        stats.loop_closures_covariance_rejected += 1;
4097                        stats
4098                            .rejected_constraints
4099                            .push(OnlineSlamRejectedLoopConstraint {
4100                                from_keyframe_id: constraint.from_keyframe_id,
4101                                to_keyframe_id: constraint.to_keyframe_id,
4102                                inlier_count: constraint.inlier_count,
4103                                translation_norm_m: constraint.relative_pose.translation.norm(),
4104                                relative_pose: constraint.relative_pose.clone(),
4105                                source,
4106                                reason: OnlineSlamLoopConstraintRejectionReason::Covariance,
4107                            });
4108                        continue;
4109                    }
4110                }
4111                if let Some((_, m)) = pcm_measurement {
4112                    admitted.push(m);
4113                }
4114                let loop_edge_weight = state
4115                    .config
4116                    .fixed_loop_edge_weight
4117                    .filter(|weight| weight.is_finite() && *weight > 0.0)
4118                    .unwrap_or_else(|| (constraint.inlier_count as f64).max(1.0));
4119                if let Some(information) = loop_information {
4120                    state.graph.add_edge_with_information(
4121                        constraint.from_keyframe_id,
4122                        constraint.to_keyframe_id,
4123                        constraint.relative_pose.clone(),
4124                        PoseGraphEdgeKind::LoopClosure,
4125                        information,
4126                    );
4127                    stats.loop_closures_with_pose_information += 1;
4128                } else {
4129                    state
4130                        .graph
4131                        .add_loop_closure_constraint_with_weight(&constraint, loop_edge_weight);
4132                }
4133                if let Some(sim3_graph) = state.sim3_graph.as_mut() {
4134                    sim3_graph.add_edge(
4135                        constraint.from_keyframe_id,
4136                        constraint.to_keyframe_id,
4137                        Sim3::new(
4138                            constraint.relative_pose.rotation,
4139                            constraint.relative_pose.translation,
4140                            measured_sim3_scale.unwrap_or(1.0),
4141                        ),
4142                        loop_edge_weight,
4143                    );
4144                }
4145                stats
4146                    .admitted_constraints
4147                    .push(OnlineSlamAdmittedLoopConstraint {
4148                        from_keyframe_id: constraint.from_keyframe_id,
4149                        to_keyframe_id: constraint.to_keyframe_id,
4150                        inlier_count: constraint.inlier_count,
4151                        translation_norm_m: constraint.relative_pose.translation.norm(),
4152                        relative_pose: constraint.relative_pose.clone(),
4153                        source,
4154                    });
4155                if source == LoopClosureCandidateSource::Appearance {
4156                    stats.appearance_accepted_count += 1;
4157                    if state.config.fuse_loop_observations {
4158                        state
4159                            .pending_loop_observation_fusions
4160                            .push(PendingLoopObservationFusion {
4161                                from_keyframe_id: constraint.from_keyframe_id,
4162                                query_keyframe_id: constraint.to_keyframe_id,
4163                                relative_pose: constraint.relative_pose.clone(),
4164                                pairs: candidate.pnp_query_landmark_pairs.clone(),
4165                            });
4166                    }
4167                }
4168                state.verified_constraints.push(constraint);
4169                state.pending_since_last_trigger += 1;
4170                stats.accepted_count += 1;
4171            }
4172
4173            // Batch PCM self-heal (optional): the incremental admission above is
4174            // order-dependent — a wrong closure admitted first (against the
4175            // empty set) poisons the genuine ones checked against it. Recompute
4176            // the order-independent maximum-consistent set over the full history
4177            // (admitted ∪ deferred) and reconcile the graph's loop edges to it,
4178            // promoting/evicting as the consensus dictates.
4179            if state.config.pcm_batch_rescreen {
4180                if let Some(cfg) = pcm_cfg {
4181                    let (promoted, evicted) = pcm_batch_reconcile(
4182                        &mut state.graph,
4183                        &mut state.verified_constraints,
4184                        &mut state.pcm_deferred,
4185                        &odometry,
4186                        &cfg,
4187                        state.config.fixed_loop_edge_weight,
4188                    );
4189                    stats.loop_closures_pcm_promoted = promoted;
4190                    stats.loop_closures_pcm_evicted = evicted;
4191                    // `pcm_batch_reconcile` reconstructs promoted edges via
4192                    // the legacy scalar API. Restore the covariance-derived
4193                    // matrix retained when that candidate was first verified.
4194                    for edge in &mut state.graph.edges {
4195                        if edge.kind != PoseGraphEdgeKind::LoopClosure || edge.information.is_some()
4196                        {
4197                            continue;
4198                        }
4199                        if let Some(information) = state
4200                            .loop_pose_information
4201                            .get(&(edge.from, edge.to))
4202                            .copied()
4203                        {
4204                            edge.information = Some(information);
4205                            stats.loop_closures_with_pose_information += 1;
4206                        }
4207                    }
4208                    // A changed loop-edge set must be re-solved.
4209                    state.pending_since_last_trigger += promoted + evicted;
4210                }
4211            }
4212        }
4213
4214        // Trigger PGO when the configured number of new constraints has
4215        // accumulated. A higher threshold batches solves; `1` (the
4216        // recommended default) runs PGO on every accepted loop edge.
4217        let trigger_threshold = state.config.trigger_every_new_constraints.max(1);
4218        if state.pending_since_last_trigger >= trigger_threshold {
4219            let pgo_config = state.config.pose_graph_config.clone();
4220            let sim3_solver_config = match &state.config.solver {
4221                LoopRefinementSolver::Sim3(cfg) => Some(cfg.clone()),
4222                LoopRefinementSolver::Se3 => None,
4223            };
4224            // Preserve the actual pre-solve Sim3 nodes, including their
4225            // accumulated scales. Re-embedding the rigid write-back poses at
4226            // unit scale here would make an unchanged non-unit solution look
4227            // like a fresh correction on every solve, repeatedly moving
4228            // landmarks and the tracker.
4229            let pre_solve_sim3_nodes = state.sim3_graph.as_ref().map(|graph| graph.poses.clone());
4230            state.pending_since_last_trigger = 0;
4231            state.trigger_count += 1;
4232            // `Sim3` solves the parallel Sim3 mirror instead of the rigid
4233            // graph; `gnc` has no Sim3 counterpart yet (see
4234            // `LoopRefinementSolver::Sim3`'s doc comment) so it is ignored
4235            // on this path. Otherwise: when GNC is configured, run the
4236            // robust solver so a verified-but-wrong loop closure is
4237            // annealed out at the back-end; otherwise the plain
4238            // M-estimator. All paths write the optimised poses back into
4239            // the map, so a wrong closure GNC rejected never reaches
4240            // subsequent tracking / local-VI-BA.
4241            let solved = if let Some(sim3_config) = sim3_solver_config {
4242                match state
4243                    .sim3_graph
4244                    .get_or_insert_with(Sim3PoseGraph::new)
4245                    .optimize(&sim3_config)
4246                {
4247                    Ok(result) => {
4248                        stats.sim3_scale_spread =
4249                            state.sim3_graph.as_ref().and_then(sim3_pose_scale_spread);
4250                        stats.sim3_pose_graph_result = Some(result);
4251                        true
4252                    }
4253                    Err(_) => false,
4254                }
4255            } else if let Some(gnc_config) = state.config.gnc {
4256                match state.graph.optimize_se3_gnc(&pgo_config, &gnc_config) {
4257                    Ok(result) => {
4258                        // Count the loop-closure edges driven below the
4259                        // inlier band — the rejected wrong closures.
4260                        // `edge_weights` is in `graph.edges` order.
4261                        stats.loop_closures_rejected = state
4262                            .graph
4263                            .edges
4264                            .iter()
4265                            .zip(&result.edge_weights)
4266                            .filter(|(edge, &w)| {
4267                                edge.kind == PoseGraphEdgeKind::LoopClosure && w < 0.5
4268                            })
4269                            .count();
4270                        stats.gnc_result = Some(result);
4271                        true
4272                    }
4273                    Err(_) => false,
4274                }
4275            } else {
4276                match state.graph.optimize_se3_iterative(&pgo_config) {
4277                    Ok(result) => {
4278                        stats.pose_graph_result = Some(result);
4279                        true
4280                    }
4281                    Err(_) => false,
4282                }
4283            };
4284            if solved && matches!(state.config.solver, LoopRefinementSolver::Sim3(_)) {
4285                // Write-back convention (see `LoopRefinementSolver::Sim3`'s
4286                // doc comment for the full derivation): each solved node
4287                // `Siw_new` becomes the rigid pose `[R | t/s]` for
4288                // `map.keyframes[*].frame.pose` — dividing the translation
4289                // by the solved scale is what keeps the corrected pose's
4290                // reprojection *ray* invariant (pinhole projection ignores
4291                // a positive rescale of camera-frame depth). The SE(3)
4292                // mirror (`state.graph.poses`) is also updated so the next
4293                // keyframe's sequential edge is built from the corrected
4294                // trajectory, not the stale pre-solve one.
4295                let mut updated = 0usize;
4296                let mut corrections: HashMap<u64, Sim3> = HashMap::new();
4297                let solved_nodes: Vec<(u64, Sim3)> = state
4298                    .sim3_graph
4299                    .as_ref()
4300                    .map(|graph| graph.poses.iter().map(|(id, s)| (*id, s.clone())).collect())
4301                    .unwrap_or_default();
4302                for (id, siw_new) in &solved_nodes {
4303                    let Some(keyframe) = self.map.keyframes.get_mut(id) else {
4304                        continue;
4305                    };
4306                    let new_pose = Pose {
4307                        world_to_camera: SE3::new(
4308                            siw_new.rotation,
4309                            siw_new.translation / siw_new.scale,
4310                        ),
4311                    };
4312                    if state.config.propagate_corrections {
4313                        if let Some(siw_old) = pre_solve_sim3_nodes
4314                            .as_ref()
4315                            .and_then(|nodes| nodes.get(id))
4316                        {
4317                            corrections.insert(*id, siw_new.inverse().compose(siw_old));
4318                        }
4319                    }
4320                    keyframe.frame.pose = Some(new_pose.clone());
4321                    state.graph.poses.insert(*id, new_pose);
4322                    updated += 1;
4323                }
4324                stats.keyframes_updated = updated;
4325
4326                if state.config.propagate_corrections && !corrections.is_empty() {
4327                    // Landmark propagation: each landmark moves with its
4328                    // ANCHOR keyframe's world-frame *similarity*
4329                    // `Siw_new⁻¹ ∘ Siw_old` (the direct Sim(3)
4330                    // generalisation of the SE(3) path's
4331                    // `T_cw_new⁻¹ ∘ T_cw_old`); see
4332                    // `propagate_pose_graph_corrections_sim3`.
4333                    let (moved, max_displacement, mean_displacement) =
4334                        propagate_pose_graph_corrections_sim3(&mut self.map, &corrections);
4335                    stats.landmarks_moved = moved;
4336                    stats.max_landmark_displacement_meters = max_displacement;
4337                    stats.mean_landmark_displacement_meters = mean_displacement;
4338
4339                    // Tracker/current-pose propagation: rotation+
4340                    // translation into `last_successful_pose`, plus the
4341                    // motion model's cached world velocity scaled by
4342                    // `correction.scale` (see
4343                    // `Tracker::apply_similarity_pose_correction`).
4344                    if let Some((_, last_correction)) =
4345                        corrections.iter().max_by_key(|(id, _)| **id)
4346                    {
4347                        self.tracker
4348                            .apply_similarity_pose_correction(last_correction);
4349                        stats.tracker_correction_applied = true;
4350                    }
4351                }
4352                // `marginalization_window` has no effect on this path yet
4353                // (`Sim3PoseGraph` has no fixed-lag marginalization) — see
4354                // that field's doc comment.
4355            } else if solved {
4356                // Write optimised poses back into the map so subsequent
4357                // tracking / local-VI-BA passes see the refined frame.
4358                // When `propagate_corrections` is set, snapshot each
4359                // updated keyframe's PRE-solve `world_to_camera` before
4360                // overwriting it so the rigid world-frame correction
4361                // `C_k = T_cw_new⁻¹ ∘ T_cw_old` can be computed (see
4362                // `propagate_pose_graph_corrections` for the derivation
4363                // and why this is the correction that keeps a landmark's
4364                // reprojection into keyframe k invariant).
4365                let mut updated = 0usize;
4366                let mut corrections: HashMap<u64, SE3> = HashMap::new();
4367                for (id, pose) in state.graph.poses.iter() {
4368                    if let Some(keyframe) = self.map.keyframes.get_mut(id) {
4369                        if state.config.propagate_corrections {
4370                            if let Some(old_pose) = keyframe.frame.pose.as_ref() {
4371                                let correction = pose
4372                                    .world_to_camera
4373                                    .inverse()
4374                                    .compose(&old_pose.world_to_camera);
4375                                corrections.insert(*id, correction);
4376                            }
4377                        }
4378                        keyframe.frame.pose = Some(pose.clone());
4379                        updated += 1;
4380                    }
4381                }
4382                stats.keyframes_updated = updated;
4383
4384                if state.config.propagate_corrections && !corrections.is_empty() {
4385                    // Landmark propagation: each landmark moves rigidly
4386                    // with its ANCHOR keyframe (the first, lowest-id,
4387                    // keyframe that observed it). Landmarks anchored to a
4388                    // keyframe this solve did not update keep their
4389                    // position untouched.
4390                    let (moved, max_displacement, mean_displacement) =
4391                        propagate_pose_graph_corrections(&mut self.map, &corrections);
4392                    stats.landmarks_moved = moved;
4393                    stats.max_landmark_displacement_meters = max_displacement;
4394                    stats.mean_landmark_displacement_meters = mean_displacement;
4395
4396                    // Tracker/current-pose propagation: map the
4397                    // tracker's continuation state (last successful pose
4398                    // + motion-model state) into the corrected frame
4399                    // using the most-recently solved keyframe's
4400                    // correction, so the very next `track_frame`'s PnP
4401                    // prior starts consistent with the just-corrected
4402                    // map instead of re-anchoring the trajectory to the
4403                    // pre-solve drift.
4404                    if let Some((_, last_correction)) =
4405                        corrections.iter().max_by_key(|(id, _)| **id)
4406                    {
4407                        self.tracker.apply_pose_correction(last_correction);
4408                        stats.tracker_correction_applied = true;
4409                    }
4410                }
4411
4412                // Fixed-lag bound: marginalize the oldest poses past the window
4413                // into a dense prior, keeping the graph (and next solve) bounded.
4414                // Runs at the just-solved estimate, so it is first-order exact;
4415                // the marginalized keyframes keep their written-back pose.
4416                if let Some(window) = state.config.marginalization_window {
4417                    let result = if state.config.marginalization_sparsify {
4418                        state.graph.marginalize_oldest_sparsified(window)
4419                    } else {
4420                        state.graph.marginalize_oldest(window)
4421                    };
4422                    if let Ok(removed) = result {
4423                        stats.poses_marginalized = removed;
4424                    }
4425                }
4426            }
4427
4428            if solved {
4429                let max_reprojection_error_px = state
4430                    .config
4431                    .appearance_candidates
4432                    .as_ref()
4433                    .map_or(4.0, |config| {
4434                        config.pnp_verifier.max_mean_reprojection_error_px
4435                    });
4436                for pending in std::mem::take(&mut state.pending_loop_observation_fusions) {
4437                    let edge_is_still_admitted = state
4438                        .graph
4439                        .edges
4440                        .iter()
4441                        .enumerate()
4442                        .find(|(_, edge)| {
4443                            edge.kind == PoseGraphEdgeKind::LoopClosure
4444                                && edge.from == pending.from_keyframe_id
4445                                && edge.to == pending.query_keyframe_id
4446                        })
4447                        .is_some_and(|(index, _)| {
4448                            stats
4449                                .gnc_result
4450                                .as_ref()
4451                                .and_then(|result| result.edge_weights.get(index))
4452                                .is_none_or(|weight| *weight >= 0.5)
4453                        });
4454                    if !edge_is_still_admitted {
4455                        stats.loop_fusion_pairs_considered += pending.pairs.len();
4456                        stats.loop_fusion_pairs_skipped += pending.pairs.len();
4457                        stats.loop_fusion_pairs_robust_rejected += pending.pairs.len();
4458                        continue;
4459                    }
4460                    if let Some(welding_config) = state.config.loop_welding_ba.clone() {
4461                        // ORB-SLAM-style welding is speculative: first move
4462                        // the current covisible region rigidly onto the PnP
4463                        // loop pose, then SearchAndFuse and BA on a clone. A
4464                        // failed selector, fusion, solve, or quality gate
4465                        // leaves the live map untouched.
4466                        stats.loop_welding_ba_attempted = true;
4467                        let active_pose_before = self
4468                            .map
4469                            .keyframes
4470                            .get(&pending.query_keyframe_id)
4471                            .and_then(|keyframe| keyframe.frame.pose.clone());
4472                        let live_map_before_welding = self.map.clone();
4473                        let graph_before_welding = state.graph.clone();
4474                        let mut candidate_map = live_map_before_welding.clone();
4475                        let Some(correction) = correct_loop_welding_region(
4476                            &mut candidate_map,
4477                            pending.from_keyframe_id,
4478                            pending.query_keyframe_id,
4479                            &pending.relative_pose,
4480                            &welding_config,
4481                        ) else {
4482                            stats.loop_fusion_pairs_considered += pending.pairs.len();
4483                            stats.loop_fusion_pairs_skipped += pending.pairs.len();
4484                            stats.loop_welding_ba_rejected_or_failed = true;
4485                            continue;
4486                        };
4487                        stats.loop_welding_initial_translation_meters = Some(
4488                            stats
4489                                .loop_welding_initial_translation_meters
4490                                .map_or(correction.translation_meters, |value| {
4491                                    value.max(correction.translation_meters)
4492                                }),
4493                        );
4494                        stats.loop_welding_initial_rotation_radians = Some(
4495                            stats
4496                                .loop_welding_initial_rotation_radians
4497                                .map_or(correction.rotation_radians, |value| {
4498                                    value.max(correction.rotation_radians)
4499                                }),
4500                        );
4501                        let (max_welding_translation, max_welding_rotation) = state
4502                            .config
4503                            .appearance_candidates
4504                            .as_ref()
4505                            .map_or((0.5, 0.2), |config| {
4506                                (
4507                                    config.max_covisibility_translation_disagreement_meters,
4508                                    config.max_covisibility_rotation_disagreement_radians,
4509                                )
4510                            });
4511                        if correction.translation_meters > max_welding_translation
4512                            || correction.rotation_radians > max_welding_rotation
4513                        {
4514                            stats.loop_fusion_pairs_considered += pending.pairs.len();
4515                            stats.loop_fusion_pairs_skipped += pending.pairs.len();
4516                            stats.loop_welding_ba_rejected_or_failed = true;
4517                            continue;
4518                        }
4519                        let mut corrected_ids = correction.keyframe_ids;
4520                        let fusion = fuse_loop_observations(
4521                            &mut candidate_map,
4522                            &state.config.camera,
4523                            pending.query_keyframe_id,
4524                            &pending.pairs,
4525                            max_reprojection_error_px,
4526                        );
4527                        stats.loop_fusion_pairs_considered += fusion.pairs_considered;
4528                        stats.loop_fusion_pairs_skipped += fusion.pairs_skipped;
4529                        stats.loop_fusion_pairs_reprojection_rejected +=
4530                            fusion.reprojection_rejected;
4531                        if fusion.observations_inserted == 0 {
4532                            stats.loop_welding_ba_rejected_or_failed = true;
4533                            continue;
4534                        }
4535                        let rotations_before_ba: HashMap<u64, UnitQuaternion<f64>> = candidate_map
4536                            .keyframes
4537                            .iter()
4538                            .filter_map(|(id, keyframe)| {
4539                                keyframe
4540                                    .frame
4541                                    .pose
4542                                    .as_ref()
4543                                    .map(|pose| (*id, pose.world_to_camera.rotation))
4544                            })
4545                            .collect();
4546
4547                        match refine_visual_map_with_covisibility_ba(
4548                            &mut candidate_map,
4549                            pending.query_keyframe_id,
4550                            &welding_config,
4551                        ) {
4552                            Ok(result) => {
4553                                // Preserve the verified/PnP-initialized local
4554                                // orientations while retaining BA-refined
4555                                // camera centers and landmarks. This is an
4556                                // explicit rotation prior implemented as a
4557                                // transactional projection, until the generic
4558                                // BA API grows native SO(3) priors.
4559                                for id in &result.selection.optimized_keyframe_ids {
4560                                    let (Some(rotation), Some(pose)) = (
4561                                        rotations_before_ba.get(id),
4562                                        candidate_map
4563                                            .keyframes
4564                                            .get_mut(id)
4565                                            .and_then(|keyframe| keyframe.frame.pose.as_mut()),
4566                                    ) else {
4567                                        continue;
4568                                    };
4569                                    let center = pose.camera_center_world();
4570                                    pose.world_to_camera.rotation = *rotation;
4571                                    pose.world_to_camera.translation =
4572                                        -(rotation.transform_vector(&center.coords));
4573                                }
4574                                let anchored_reprojection = mean_selected_reprojection_px(
4575                                    &candidate_map,
4576                                    &result.selection,
4577                                );
4578                                stats.loop_welding_ba_mean_reprojection_before_px =
4579                                    Some(result.mean_reprojection_before_px);
4580                                stats.loop_welding_ba_mean_reprojection_after_px =
4581                                    anchored_reprojection;
4582                                if !anchored_reprojection.is_some_and(|error| {
4583                                    error.is_finite()
4584                                        && error <= result.mean_reprojection_before_px + 1.0e-9
4585                                }) || !candidate_map.validate().is_valid()
4586                                {
4587                                    stats.loop_welding_ba_rejected_or_failed = true;
4588                                    continue;
4589                                }
4590                                corrected_ids.extend(
4591                                    result.selection.optimized_keyframe_ids.iter().copied(),
4592                                );
4593                                corrected_ids.sort_unstable();
4594                                corrected_ids.dedup();
4595                                self.map = candidate_map;
4596                                for id in corrected_ids {
4597                                    if let Some(pose) = self
4598                                        .map
4599                                        .keyframes
4600                                        .get(&id)
4601                                        .and_then(|keyframe| keyframe.frame.pose.clone())
4602                                    {
4603                                        if state.graph.poses.contains_key(&id) {
4604                                            state.graph.poses.insert(id, pose);
4605                                        }
4606                                    }
4607                                }
4608                                stats.loop_welding_post_pgo_attempted = true;
4609                                let (
4610                                    post_pgo_succeeded,
4611                                    post_pgo_reprojection,
4612                                    post_ba_error,
4613                                    post_ba_behind_camera_ratio,
4614                                ) = if matches!(state.config.solver, LoopRefinementSolver::Se3) {
4615                                    refine_pose_graph_after_welding(
4616                                        &mut self.map,
4617                                        &mut state.graph,
4618                                        &pgo_config,
4619                                        state.config.gnc.as_ref(),
4620                                        pending.query_keyframe_id,
4621                                        &welding_config,
4622                                        result.mean_reprojection_before_px,
4623                                    )
4624                                } else {
4625                                    (false, None, None, None)
4626                                };
4627                                stats.loop_welding_post_pgo_mean_reprojection_px =
4628                                    post_pgo_reprojection;
4629                                stats.loop_welding_post_ba_error = post_ba_error;
4630                                stats.loop_welding_post_ba_behind_camera_ratio =
4631                                    post_ba_behind_camera_ratio;
4632                                if !post_pgo_succeeded {
4633                                    self.map = live_map_before_welding;
4634                                    state.graph = graph_before_welding;
4635                                    stats.loop_welding_ba_rejected_or_failed = true;
4636                                    continue;
4637                                }
4638                                stats.loop_welding_post_pgo_succeeded = true;
4639                                stats.loop_welding_ba_updated_keyframes +=
4640                                    result.updated_keyframe_count;
4641                                stats.loop_welding_ba_updated_landmarks +=
4642                                    result.updated_landmark_count;
4643                                if let (Some(old_pose), Some(new_pose)) = (
4644                                    active_pose_before,
4645                                    self.map
4646                                        .keyframes
4647                                        .get(&pending.query_keyframe_id)
4648                                        .and_then(|keyframe| keyframe.frame.pose.clone()),
4649                                ) {
4650                                    let correction = new_pose
4651                                        .world_to_camera
4652                                        .inverse()
4653                                        .compose(&old_pose.world_to_camera);
4654                                    self.tracker.apply_pose_correction(&correction);
4655                                    stats.tracker_correction_applied = true;
4656                                }
4657                                stats.loop_fusion_observations_inserted +=
4658                                    fusion.observations_inserted;
4659                                stats.loop_fusion_observations_reassigned +=
4660                                    fusion.observations_reassigned;
4661                                stats.loop_welding_ba_succeeded = true;
4662                            }
4663                            Err(_) => stats.loop_welding_ba_rejected_or_failed = true,
4664                        }
4665                    } else {
4666                        let fusion = fuse_loop_observations(
4667                            &mut self.map,
4668                            &state.config.camera,
4669                            pending.query_keyframe_id,
4670                            &pending.pairs,
4671                            max_reprojection_error_px,
4672                        );
4673                        stats.loop_fusion_pairs_considered += fusion.pairs_considered;
4674                        stats.loop_fusion_observations_inserted += fusion.observations_inserted;
4675                        stats.loop_fusion_observations_reassigned += fusion.observations_reassigned;
4676                        stats.loop_fusion_pairs_skipped += fusion.pairs_skipped;
4677                        stats.loop_fusion_pairs_reprojection_rejected +=
4678                            fusion.reprojection_rejected;
4679                    }
4680                }
4681            }
4682        }
4683
4684        Some(stats)
4685    }
4686
4687    /// Register the freshly-staged IMU factor with the local VI-BA state
4688    /// table and, when the trigger threshold has been reached, run a
4689    /// sliding-window VI-BA pass that refines the trailing window's
4690    /// poses + landmarks + velocities + biases. No-op when local VI-BA
4691    /// is disabled OR when no IMU factor was staged this frame.
4692    /// `true` while local VI-BA must stay gated because no stage has yet
4693    /// replaced the placeholder-zero bias linearisation with a real
4694    /// estimate.
4695    ///
4696    /// When `keep_pre_promotion_imu_factors` lets factors flow before
4697    /// VI-init promotes, the factors must still be banked for the
4698    /// post-promotion BA replay, but the BA itself cannot run yet while
4699    /// its bias linearisation is the placeholder zero seed — a
4700    /// pre-promotion solve corrupts the map's keyframe poses
4701    /// (empirically: tracking-success collapses from 9.8 % to 1.8 %
4702    /// on MH_01 because the next-frame matcher sees BA-shifted
4703    /// keyframe descriptors).
4704    ///
4705    /// The zero-placeholder rationale stops applying the moment EITHER:
4706    /// * the static stage completes (`vi_init_state.completed.is_some()`),
4707    ///   or
4708    /// * the motion-based stage reaches its terminal state
4709    ///   (`vi_motion_init_state.completed.is_some()`), or
4710    /// * the motion-based stage has fired a [`crate::BiasReleaseSchedule`]
4711    ///   Stage A ("velocity stage") solve
4712    ///   (`vi_motion_init_state.velocity_stage_fired()`).
4713    ///
4714    /// Stage A is a non-terminal success: `bias_released` stays `false`
4715    /// and `vi_motion_init_state.completed` stays `None` so the stage keeps
4716    /// registering keyframes/translation toward the Stage B release gate,
4717    /// but its promotion has already mirrored the refined per-keyframe
4718    /// `(velocity, bias)` into `local_vi_ba_state.keyframe_state` and the
4719    /// estimated/refined biases into `imu_state`/configs (see
4720    /// `promote_motion_vi_init_result`). From that point on local VI-BA's
4721    /// linearisation point is the estimated seed, not the placeholder
4722    /// zero — ORB-SLAM3 itself runs local VI-BA after VIBA1, which Stage A
4723    /// mirrors. A later Stage B firing re-mirrors on top harmlessly (same
4724    /// sinks, refined values), so there is no double-counting risk in
4725    /// treating Stage A as "no longer pending" here.
4726    fn vi_initialization_pending(&self) -> bool {
4727        self.vi_init_state.as_ref().is_some_and(|static_state| {
4728            // Static VI init has not yet succeeded.
4729            let static_not_done = static_state.completed.is_none();
4730            if !static_not_done {
4731                return false;
4732            }
4733            // When the static init gave up, unblock only if there is no motion-init
4734            // stage configured (no hope of a better initialisation) OR if the
4735            // motion-init stage has already succeeded (velocity + bias are valid).
4736            // If motion-init is configured but has not yet succeeded, remain pending
4737            // so IMU factors carrying stale biases are not fed into local VI-BA.
4738            let static_gave_up = static_state.gave_up.is_some();
4739            match self.vi_motion_init_state.as_ref() {
4740                None => {
4741                    // No motion-init stage: unblock once the static stage gives up.
4742                    !static_gave_up
4743                }
4744                Some(motion_state) => {
4745                    if motion_state.completed.is_some() || motion_state.velocity_stage_fired() {
4746                        // Motion-init succeeded: unblock regardless of static outcome.
4747                        false
4748                    } else {
4749                        // Motion-init configured but not yet done: stay pending.
4750                        true
4751                    }
4752                }
4753            }
4754        })
4755    }
4756
4757    fn maybe_run_local_vi_ba(
4758        &mut self,
4759        new_factor: Option<ImuPreintegrationFactor>,
4760    ) -> Option<OnlineSlamLocalBaStats> {
4761        let vi_initialization_pending = self.vi_initialization_pending();
4762        let state = self.local_vi_ba_state.as_mut()?;
4763        let factor = new_factor?;
4764        let should_trigger = state.register_new_factor(factor);
4765        if !should_trigger || vi_initialization_pending {
4766            return None;
4767        }
4768        crate::online_slam_vi_ba::run_local_vi_ba(&mut self.map, state)
4769    }
4770
4771    /// After a successful VI-BA window shift, harvest the `SqrtNavMarginal`
4772    /// produced by [`crate::nonlinear_factor_recovery`] and inject the resulting
4773    /// Chow-Liu relative-pose factors into the pose graph.
4774    ///
4775    /// No-op when:
4776    /// - the sqrt-window marginalization path is disabled,
4777    /// - no `sqrt_nav_marginal` is available (first window),
4778    /// - there is no active `pose_graph_state`, or
4779    /// - there are fewer than 2 retained keyframes (single-node tree has no edges).
4780    fn maybe_inject_recovered_factors(&mut self) -> usize {
4781        let vi_ba_state = match self.local_vi_ba_state.as_mut() {
4782            Some(s) => s,
4783            None => return 0,
4784        };
4785        if !vi_ba_state.config.use_sqrt_window_marginalization {
4786            return 0;
4787        }
4788        let pending = std::mem::take(&mut vi_ba_state.pending_recovered_pose_factors);
4789        if pending.is_empty() {
4790            return 0;
4791        }
4792        let pg_state = match self.pose_graph_state.as_mut() {
4793            Some(s) => s,
4794            None => {
4795                vi_ba_state.pending_recovered_pose_factors = pending;
4796                return 0;
4797            }
4798        };
4799        let mut injected = 0usize;
4800        let mut retry = Vec::new();
4801        for (id_i, id_j, f) in pending {
4802            let pose_i = Self::pose_graph_pose_or_map(&self.map, pg_state, id_i);
4803            let pose_j = Self::pose_graph_pose_or_map(&self.map, pg_state, id_j);
4804            let (pose_i, pose_j) = match (pose_i, pose_j) {
4805                (Some(pi), Some(pj)) => (pi, pj),
4806                _ => {
4807                    retry.push((id_i, id_j, f));
4808                    continue;
4809                }
4810            };
4811            let relative = relative_world_to_camera(&pose_i, &pose_j);
4812            if f.omega_relative.nrows() != 6 || f.omega_relative.ncols() != 6 {
4813                continue;
4814            }
4815            let mut information = nalgebra::Matrix6::<f64>::zeros();
4816            for row in 0..6 {
4817                for col in 0..6 {
4818                    information[(row, col)] = f.omega_relative[(row, col)];
4819                }
4820            }
4821            pg_state.graph.add_edge_with_information(
4822                id_i,
4823                id_j,
4824                relative,
4825                PoseGraphEdgeKind::Sequential,
4826                information,
4827            );
4828            injected += 1;
4829        }
4830        vi_ba_state.pending_recovered_pose_factors = retry;
4831        injected
4832    }
4833
4834    fn pose_graph_pose_or_map(
4835        map: &VisualMap,
4836        pg_state: &mut OnlineSlamLoopClosureRefinementState,
4837        keyframe_id: u64,
4838    ) -> Option<Pose> {
4839        if let Some(pose) = pg_state.graph.poses.get(&keyframe_id) {
4840            return Some(pose.clone());
4841        }
4842        let pose = map.keyframes.get(&keyframe_id)?.frame.pose.clone()?;
4843        pg_state.graph.add_pose(keyframe_id, pose.clone());
4844        Some(pose)
4845    }
4846
4847    /// Run visual-only covisibility local BA when a new keyframe has just
4848    /// entered the map and the configured trigger interval fires. No-op
4849    /// when disabled, when the mapper only staged-but-did-not-apply the
4850    /// keyframe, or while the map is still below the configured minimum
4851    /// keyframe count.
4852    fn maybe_run_covisibility_local_ba(
4853        &mut self,
4854        frame: &Frame,
4855        applied_update: Option<&AppliedMapUpdate>,
4856    ) -> Option<OnlineSlamCovisibilityLocalBaStats> {
4857        let config = self.config.covisibility_local_ba.clone()?;
4858        let added_new_keyframe = applied_update.is_some_and(|a| a.keyframe_count > 0);
4859        if !added_new_keyframe {
4860            return None;
4861        }
4862
4863        if let Some(activation) = config.motion_vi_raw_residual_activation {
4864            let motion_state = self.vi_motion_init_state.as_ref()?;
4865            if motion_state.completed.is_some()
4866                || !motion_state.last_rejection.as_ref().is_some_and(|reason| {
4867                    motion_vi_raw_residual_activation_satisfied(activation, reason)
4868                })
4869            {
4870                return None;
4871            }
4872        }
4873        if let Some(maximum) = config.max_seed_landmarks_for_activation {
4874            let seed_support = self
4875                .map
4876                .keyframes
4877                .values()
4878                .min_by_key(|keyframe| keyframe.frame.id)
4879                .map(|keyframe| keyframe.observations.len());
4880            if seed_support.is_none_or(|support| support > maximum) {
4881                return None;
4882            }
4883        }
4884
4885        let map_keyframe_count = self.map.keyframes.len();
4886        if map_keyframe_count < config.min_keyframes.max(1) {
4887            return None;
4888        }
4889        if config
4890            .max_keyframes
4891            .is_some_and(|maximum| map_keyframe_count > maximum)
4892        {
4893            return None;
4894        }
4895
4896        let trigger_every = config.trigger_every_new_keyframes.max(1);
4897        if !map_keyframe_count.is_multiple_of(trigger_every) {
4898            return None;
4899        }
4900
4901        let started = Instant::now();
4902        // The clone-and-check write-back path activates when any conditioning
4903        // gate is configured. It solves on a cloned map, evaluates every
4904        // configured gate against the solved candidate, and only commits the
4905        // clone into the live map if none fire. If any gate rejects, the live
4906        // map is left untouched (safe no-op) and the rejection reason is
4907        // surfaced on the returned stats' `error`.
4908        let conditioning_gate_active = config.max_outlier_observation_ratio.is_some()
4909            || config.max_behind_camera_landmark_ratio.is_some()
4910            || config.min_fixed_to_optimized_ratio.is_some()
4911            || config.max_pose_translation_correction_m.is_some()
4912            || config.max_pose_rotation_correction_rad.is_some();
4913        let factor_neighbor_allowlist = self
4914            .sparse_factor_graph_state
4915            .as_ref()
4916            .map(|graph| graph.active_neighbor_keyframe_ids(frame.id));
4917        let result = if conditioning_gate_active {
4918            let mut candidate_map = self.map.clone();
4919            let result = refine_visual_map_with_covisibility_ba_and_neighbor_allowlist(
4920                &mut candidate_map,
4921                frame.id,
4922                &config.ba,
4923                factor_neighbor_allowlist.as_ref(),
4924            );
4925            if let Ok(ref result) = result {
4926                let outlier_ratio = outlier_observation_ratio(
4927                    result.outlier_observation_count,
4928                    result.selection.observation_count,
4929                );
4930                let make_rejection =
4931                    |error: CovisibilityLocalBaError, quality_gate_rejected: bool| {
4932                        let pose_correction_gate_rejected = matches!(
4933                            error,
4934                            CovisibilityLocalBaError::PoseCorrectionGateRejected { .. }
4935                        );
4936                        OnlineSlamCovisibilityLocalBaStats {
4937                            active_keyframe_id: frame.id,
4938                            map_keyframe_count,
4939                            factor_graph_neighbor_count: factor_neighbor_allowlist
4940                                .as_ref()
4941                                .map(|neighbors| neighbors.len()),
4942                            elapsed_ms: started.elapsed().as_secs_f64() * 1000.0,
4943                            success: false,
4944                            error: Some(error),
4945                            selection: Some(result.selection.clone()),
4946                            ba_result: Some(result.ba_result.clone()),
4947                            mean_reprojection_before_px: Some(result.mean_reprojection_before_px),
4948                            mean_reprojection_after_px: Some(result.mean_reprojection_after_px),
4949                            max_pose_translation_correction_m: Some(
4950                                result.max_pose_translation_correction_m,
4951                            ),
4952                            max_pose_rotation_correction_rad: Some(
4953                                result.max_pose_rotation_correction_rad,
4954                            ),
4955                            updated_keyframe_count: 0,
4956                            updated_landmark_count: 0,
4957                            outlier_observation_count: result.outlier_observation_count,
4958                            observation_count: result.selection.observation_count,
4959                            outlier_observation_ratio: outlier_ratio,
4960                            quality_gate_rejected,
4961                            pose_correction_gate_rejected,
4962                            removed_observation_count: 0,
4963                        }
4964                    };
4965
4966                let optimized_keyframe_count = result.selection.optimized_keyframe_ids.len();
4967                let fixed_keyframe_count = result.selection.fixed_keyframe_ids.len();
4968
4969                let translation_exceeded = config
4970                    .max_pose_translation_correction_m
4971                    .is_some_and(|limit| result.max_pose_translation_correction_m > limit);
4972                let rotation_exceeded = config
4973                    .max_pose_rotation_correction_rad
4974                    .is_some_and(|limit| result.max_pose_rotation_correction_rad > limit);
4975                if translation_exceeded || rotation_exceeded {
4976                    return Some(make_rejection(
4977                        CovisibilityLocalBaError::PoseCorrectionGateRejected {
4978                            translation_correction_m: result.max_pose_translation_correction_m,
4979                            rotation_correction_rad: result.max_pose_rotation_correction_rad,
4980                            max_translation_correction_m: config.max_pose_translation_correction_m,
4981                            max_rotation_correction_rad: config.max_pose_rotation_correction_rad,
4982                        },
4983                        false,
4984                    ));
4985                }
4986
4987                // Fixed-anchor adequacy (ratio form).
4988                if let Some(min_ratio) = config.min_fixed_to_optimized_ratio {
4989                    if !fixed_to_optimized_ratio_satisfied(
4990                        optimized_keyframe_count,
4991                        fixed_keyframe_count,
4992                        min_ratio,
4993                    ) {
4994                        return Some(make_rejection(
4995                            CovisibilityLocalBaError::FixedSupportRatioRejected {
4996                                optimized_keyframe_count,
4997                                fixed_keyframe_count,
4998                                required_fixed_keyframes: required_fixed_keyframes(
4999                                    optimized_keyframe_count,
5000                                    min_ratio,
5001                                ),
5002                                min_fixed_to_optimized_ratio: min_ratio,
5003                            },
5004                            false,
5005                        ));
5006                    }
5007                }
5008
5009                // Behind-camera degeneracy (evaluated on the solved clone).
5010                if let Some(max_behind) = config.max_behind_camera_landmark_ratio {
5011                    let behind_ratio =
5012                        behind_camera_optimized_landmark_ratio(&candidate_map, &result.selection)
5013                            .unwrap_or(0.0);
5014                    if behind_ratio > max_behind {
5015                        return Some(make_rejection(
5016                            CovisibilityLocalBaError::BehindCameraGateRejected {
5017                                behind_camera_landmark_ratio: behind_ratio,
5018                                max_behind_camera_landmark_ratio: max_behind,
5019                            },
5020                            false,
5021                        ));
5022                    }
5023                }
5024
5025                // Outlier-observation ratio (legacy quality gate).
5026                if let Some(max_ratio) = config.max_outlier_observation_ratio {
5027                    if outlier_ratio.unwrap_or(0.0) > max_ratio {
5028                        return Some(make_rejection(
5029                            CovisibilityLocalBaError::QualityGateRejected {
5030                                outlier_observation_count: result.outlier_observation_count,
5031                                observation_count: result.selection.observation_count,
5032                                max_outlier_observation_ratio: max_ratio,
5033                            },
5034                            true,
5035                        ));
5036                    }
5037                }
5038
5039                self.map = candidate_map;
5040            }
5041            result
5042        } else {
5043            refine_visual_map_with_covisibility_ba_and_neighbor_allowlist(
5044                &mut self.map,
5045                frame.id,
5046                &config.ba,
5047                factor_neighbor_allowlist.as_ref(),
5048            )
5049        };
5050        let elapsed_ms = started.elapsed().as_secs_f64() * 1000.0;
5051
5052        match result {
5053            Ok(result) => {
5054                let observation_count = result.selection.observation_count;
5055                Some(OnlineSlamCovisibilityLocalBaStats {
5056                    active_keyframe_id: frame.id,
5057                    map_keyframe_count,
5058                    factor_graph_neighbor_count: factor_neighbor_allowlist
5059                        .as_ref()
5060                        .map(|neighbors| neighbors.len()),
5061                    elapsed_ms,
5062                    success: true,
5063                    error: None,
5064                    selection: Some(result.selection),
5065                    ba_result: Some(result.ba_result),
5066                    mean_reprojection_before_px: Some(result.mean_reprojection_before_px),
5067                    mean_reprojection_after_px: Some(result.mean_reprojection_after_px),
5068                    max_pose_translation_correction_m: Some(
5069                        result.max_pose_translation_correction_m,
5070                    ),
5071                    max_pose_rotation_correction_rad: Some(result.max_pose_rotation_correction_rad),
5072                    updated_keyframe_count: result.updated_keyframe_count,
5073                    updated_landmark_count: result.updated_landmark_count,
5074                    outlier_observation_count: result.outlier_observation_count,
5075                    observation_count,
5076                    outlier_observation_ratio: outlier_observation_ratio(
5077                        result.outlier_observation_count,
5078                        observation_count,
5079                    ),
5080                    quality_gate_rejected: false,
5081                    pose_correction_gate_rejected: false,
5082                    removed_observation_count: result.removed_observation_count,
5083                })
5084            }
5085            Err(error) => Some(OnlineSlamCovisibilityLocalBaStats {
5086                active_keyframe_id: frame.id,
5087                map_keyframe_count,
5088                factor_graph_neighbor_count: factor_neighbor_allowlist
5089                    .as_ref()
5090                    .map(|neighbors| neighbors.len()),
5091                elapsed_ms,
5092                success: false,
5093                error: Some(error),
5094                selection: None,
5095                ba_result: None,
5096                mean_reprojection_before_px: None,
5097                mean_reprojection_after_px: None,
5098                max_pose_translation_correction_m: None,
5099                max_pose_rotation_correction_rad: None,
5100                updated_keyframe_count: 0,
5101                updated_landmark_count: 0,
5102                outlier_observation_count: 0,
5103                observation_count: 0,
5104                outlier_observation_ratio: None,
5105                quality_gate_rejected: false,
5106                pose_correction_gate_rejected: false,
5107                removed_observation_count: 0,
5108            }),
5109        }
5110    }
5111
5112    fn stage_imu_factor_on_new_keyframe(
5113        &mut self,
5114        frame: &Frame,
5115        applied_update: Option<&AppliedMapUpdate>,
5116    ) -> Option<ImuPreintegrationFactor> {
5117        let state = self.imu_state.as_mut()?;
5118        let added_new_keyframe = applied_update.is_some_and(|a| a.keyframe_count > 0);
5119        if !added_new_keyframe {
5120            return None;
5121        }
5122        let new_keyframe_id = frame.id;
5123        let factor = match state.last_keyframe_id {
5124            Some(prev_id) if prev_id != new_keyframe_id => {
5125                let delta = state.preintegrator.delta();
5126                let factor = ImuPreintegrationFactor {
5127                    keyframe_id_from: prev_id,
5128                    keyframe_id_to: new_keyframe_id,
5129                    delta,
5130                    gravity_world: state.config.gravity_world,
5131                    weight_position: state.config.weight_position,
5132                    weight_velocity: state.config.weight_velocity,
5133                    weight_rotation: state.config.weight_rotation,
5134                };
5135                state.preintegrator.reset();
5136                Some(factor)
5137            }
5138            _ => None,
5139        };
5140        state.last_keyframe_id = Some(new_keyframe_id);
5141
5142        // Stale-factor gate. Until the auto-bootstrap stage has fired
5143        // (or has given up with `KeepExistingSeed`), factors carry the
5144        // caller's placeholder bias linearisation and are discarded
5145        // rather than exposed downstream. `discarded_stale_factor_count`
5146        // is reported on the `Succeeded` event so callers can audit.
5147        // Opt-in `OnlineSlamConfig.keep_pre_promotion_imu_factors`
5148        // bypasses the discard so factors still flow into the local
5149        // BA's factor history (carrying placeholder biases; the BA's
5150        // own iterations are expected to absorb the linearisation
5151        // error). `discarded_stale_factor_count` is still incremented
5152        // in that branch so auditors can see how many factors were
5153        // forwarded with stale biases.
5154        if let Some(vi) = self.vi_init_state.as_mut() {
5155            if vi.is_active() {
5156                if factor.is_some() {
5157                    vi.discarded_stale_factor_count += 1;
5158                }
5159                if !self.config.keep_pre_promotion_imu_factors {
5160                    state.pending_factor = None;
5161                    return None;
5162                }
5163            }
5164        }
5165
5166        state.pending_factor = factor.clone();
5167        factor
5168    }
5169
5170    /// Run a single try-initialise step on the VI init buffer when a new
5171    /// keyframe has just been registered. Returns the state-transition
5172    /// event for [`OnlineSlamResult::vi_init`]; `None` when nothing
5173    /// changed this frame (no new keyframe, already terminal, or VI init
5174    /// disabled).
5175    fn run_vi_init_step(
5176        &mut self,
5177        frame: &Frame,
5178        applied_update: Option<&AppliedMapUpdate>,
5179    ) -> Option<ViInitializationEvent> {
5180        // Cheap pre-checks that don't need to borrow `vi_init_state`
5181        // mutably yet.
5182        if self.vi_init_state.as_ref().is_none_or(|s| !s.is_active()) {
5183            return None;
5184        }
5185        let added_new_keyframe = applied_update.is_some_and(|a| a.keyframe_count > 0);
5186        let try_on_every_frame = self
5187            .vi_init_state
5188            .as_ref()
5189            .is_some_and(|s| s.config.try_initialize_on_every_frame);
5190        if !added_new_keyframe && !try_on_every_frame {
5191            return None;
5192        }
5193
5194        // Try the standalone initialiser. We don't need to mutate
5195        // `vi_init_state` for this read, just borrow it.
5196        let try_result = {
5197            let state = self.vi_init_state.as_ref().unwrap();
5198            state.initializer.try_initialize()
5199        };
5200
5201        match try_result {
5202            Ok(result) => {
5203                // Bind promotion to the just-registered keyframe if there
5204                // is one this frame; otherwise (`try_on_every_frame` path
5205                // on a non-KF frame) bind to the most recent existing
5206                // keyframe so the rotation rewrite + local-VI-BA seed
5207                // still target a valid map entry. If the map has no
5208                // keyframes yet, promote anchorlessly — Step 3 + 4 in
5209                // `promote_vi_init_result` will skip when the binding is
5210                // `None`.
5211                let binding_keyframe_id = if added_new_keyframe {
5212                    Some(frame.id)
5213                } else {
5214                    self.map.keyframes.keys().copied().max()
5215                };
5216                Some(self.promote_vi_init_result(binding_keyframe_id, result))
5217            }
5218            Err(reason) => {
5219                // Record the rejection and check whether we've exceeded
5220                // a cap; either fall through with `StillBuffering` or
5221                // trigger the configured fallback.
5222                let vi = self.vi_init_state.as_mut().unwrap();
5223                vi.last_rejection = Some(reason.clone());
5224                if vi.cap_exceeded() {
5225                    Some(self.apply_vi_init_fallback(reason))
5226                } else {
5227                    Some(ViInitializationEvent::StillBuffering { reason })
5228                }
5229            }
5230        }
5231    }
5232
5233    /// Atomic promotion of a successful VI init result into the
5234    /// pipeline's running state. The ordering follows the design
5235    /// contract (see `docs/vi_initialization_integration.md`):
5236    ///   1. Reset `imu_state.preintegrator` with the new bias linearisation.
5237    ///   2. Mirror `imu_state.config.{bias_gyro, bias_acc}`.
5238    ///   3. Rewrite the just-registered keyframe's `Pose` (rotation
5239    ///      only, camera centre preserved) if requested.
5240    ///   4. Seed `local_vi_ba_state.keyframe_state[first_keyframe_id]`
5241    ///      with `velocity_world = 0, bias = (b_g, b_a)`.
5242    ///   5. Mark `vi_init_state.completed` so the stale-factor gate is
5243    ///      lifted from this frame onwards.
5244    fn promote_vi_init_result(
5245        &mut self,
5246        binding_keyframe_id: Option<u64>,
5247        result: VisualInertialInitializationResult,
5248    ) -> ViInitializationEvent {
5249        let bias_gyro = result.bias_gyro;
5250        let bias_acc = result.bias_acc;
5251        let seed_rotation = result.initial_rotation_body_to_world;
5252
5253        // Step 1 + 2: reset preintegrator and mirror config biases.
5254        if let Some(imu) = self.imu_state.as_mut() {
5255            imu.reset_preintegrator_with_bias(bias_gyro, bias_acc);
5256        }
5257        if let Some(imu_cfg) = self.config.imu.as_mut() {
5258            imu_cfg.bias_gyro = bias_gyro;
5259            imu_cfg.bias_acc = bias_acc;
5260        }
5261
5262        // Step 3: rewrite first keyframe rotation, preserving the
5263        // camera centre. `R_w←c = R_w←b · R_b←c`, then
5264        // `Pose.rotation = R_c←w = R_w←c^T`, and
5265        // `Pose.translation = -R_c←w · C_w_old`. Skipped when promotion
5266        // happened on a non-KF frame and the map has no keyframe yet to
5267        // bind to (Phase-19 `try_initialize_on_every_frame` path).
5268        let seed_first_keyframe_rotation = self
5269            .vi_init_state
5270            .as_ref()
5271            .is_some_and(|s| s.config.seed_first_keyframe_rotation);
5272        let body_to_camera = self
5273            .vi_init_state
5274            .as_ref()
5275            .map_or_else(SE3::identity, |s| s.config.body_to_camera.clone());
5276        if seed_first_keyframe_rotation {
5277            if let Some(first_keyframe_id) = binding_keyframe_id {
5278                if let Some(keyframe) = self.map.keyframes.get_mut(&first_keyframe_id) {
5279                    if let Some(pose) = keyframe.frame.pose.as_mut() {
5280                        let r_wb = seed_rotation;
5281                        let r_bc = body_to_camera.rotation;
5282                        let r_wc = r_wb * r_bc;
5283                        let r_cw_new = r_wc.inverse();
5284                        let camera_center_world = -(pose.world_to_camera.rotation.inverse()
5285                            * pose.world_to_camera.translation);
5286                        let t_cw_new = -(r_cw_new * camera_center_world);
5287                        *pose =
5288                            visloc_core::geometry::Pose::from_world_to_camera(r_cw_new, t_cw_new);
5289                    }
5290                }
5291            }
5292        }
5293
5294        // Step 4: seed first-keyframe velocity slot in local VI-BA.
5295        if let Some(local) = self.local_vi_ba_state.as_mut() {
5296            if let Some(first_keyframe_id) = binding_keyframe_id {
5297                local
5298                    .keyframe_state
5299                    .entry(first_keyframe_id)
5300                    .or_insert_with(|| crate::online_slam_vi_ba::KeyframeImuState {
5301                        velocity_world: Vector3::zeros(),
5302                        bias_gyro,
5303                        bias_acc,
5304                    });
5305            }
5306            // Also mirror the new bias linearisation onto the local
5307            // VI-BA config so subsequent keyframe slots inherit it.
5308            local.config.bias_gyro_init = bias_gyro;
5309            local.config.bias_acc_init = bias_acc;
5310        }
5311        if let Some(local_cfg) = self.config.local_vi_ba.as_mut() {
5312            local_cfg.bias_gyro_init = bias_gyro;
5313            local_cfg.bias_acc_init = bias_acc;
5314        }
5315
5316        // Step 5: mark the stage completed.
5317        let discarded_stale_factor_count;
5318        {
5319            let vi = self.vi_init_state.as_mut().unwrap();
5320            vi.completed = Some(result.clone());
5321            discarded_stale_factor_count = vi.discarded_stale_factor_count;
5322        }
5323
5324        ViInitializationEvent::Succeeded {
5325            result,
5326            first_keyframe_id: binding_keyframe_id,
5327            discarded_stale_factor_count,
5328        }
5329    }
5330
5331    /// Apply the configured fallback after the duration / sample cap
5332    /// has been exceeded without a successful `try_initialize`.
5333    fn apply_vi_init_fallback(
5334        &mut self,
5335        last_reason: StationaryRejectionReason,
5336    ) -> ViInitializationEvent {
5337        let fallback = self
5338            .vi_init_state
5339            .as_ref()
5340            .map_or(ViInitFallback::KeepExistingSeed, |s| {
5341                s.config.on_persistent_rejection
5342            });
5343        match fallback {
5344            ViInitFallback::KeepExistingSeed => {
5345                // Stale gate is lifted by clearing `vi_init_state.gave_up`
5346                // -> not active anymore.
5347            }
5348            ViInitFallback::DisableImuStage => {
5349                self.imu_state = None;
5350                self.local_vi_ba_state = None;
5351                self.config.imu = None;
5352                self.config.local_vi_ba = None;
5353            }
5354        }
5355        if let Some(vi) = self.vi_init_state.as_mut() {
5356            vi.gave_up = Some(last_reason.clone());
5357        }
5358        ViInitializationEvent::GaveUp {
5359            last_reason,
5360            fallback,
5361        }
5362    }
5363
5364    /// Run one motion-based VI init step on the current frame. The
5365    /// stage:
5366    ///
5367    /// 1. Banks the freshly-staged IMU factor (if any) onto
5368    ///    `vi_motion_init_state.factor_history` so the trigger has a
5369    ///    body of factors to optimise against.
5370    /// 2. Registers the new keyframe's world-frame camera centre with
5371    ///    the inner `MotionBasedViInitializer`.
5372    /// 3. Calls `try_initialize` once the inner gates allow it. On
5373    ///    success the refined `(velocity, bias)` are mirrored into
5374    ///    `local_vi_ba_state.keyframe_state` and `imu_state`'s
5375    ///    pre-integrator is reset with the new bias linearisation.
5376    ///
5377    /// Returns the state-transition event for
5378    /// [`OnlineSlamResult::vi_motion_init`]. `None` when:
5379    /// * no new keyframe was registered this frame,
5380    /// * the motion-based stage is disabled,
5381    /// * the static VI init stage has neither succeeded nor reached the
5382    ///   explicitly-enabled post-give-up fallback,
5383    /// * or the stage has already reached the terminal `Initialised`
5384    ///   state.
5385    fn run_motion_vi_init_step(
5386        &mut self,
5387        frame: &Frame,
5388        applied_update: Option<&AppliedMapUpdate>,
5389        new_imu_factor: Option<&ImuPreintegrationFactor>,
5390    ) -> Option<MotionViInitializationEvent> {
5391        let added_new_keyframe = applied_update.is_some_and(|a| a.keyframe_count > 0);
5392        if !added_new_keyframe {
5393            return None;
5394        }
5395        if self
5396            .vi_motion_init_state
5397            .as_ref()
5398            .is_none_or(|s| !s.is_active())
5399        {
5400            return None;
5401        }
5402        // Prefer stationary-window bias estimates. For a sequence that starts
5403        // in motion, an explicit opt-in may continue only after the static
5404        // stage has terminally given up; use the still-live IMU configuration's
5405        // calibrated/existing biases rather than fabricating a stationary
5406        // result from a low-variance moving window.
5407        let static_bias_seed = self
5408            .vi_init_state
5409            .as_ref()
5410            .and_then(|state| state.completed.as_ref())
5411            .map(|seed| (seed.bias_gyro, seed.bias_acc));
5412        let allow_after_give_up = self
5413            .vi_motion_init_state
5414            .as_ref()
5415            .is_some_and(|state| state.config.allow_after_static_give_up);
5416        let allow_from_configured_bias_before_static = self
5417            .vi_motion_init_state
5418            .as_ref()
5419            .is_some_and(|state| state.config.allow_from_configured_bias_before_static);
5420        let static_gave_up = self
5421            .vi_init_state
5422            .as_ref()
5423            .is_some_and(|state| state.gave_up.is_some());
5424        let (bias_gyro_seed, bias_acc_seed) = if let Some(seed) = static_bias_seed {
5425            seed
5426        } else if allow_from_configured_bias_before_static
5427            || (allow_after_give_up && static_gave_up)
5428        {
5429            let imu = self.imu_state.as_ref()?;
5430            (imu.config.bias_gyro, imu.config.bias_acc)
5431        } else {
5432            return None;
5433        };
5434
5435        // Bank the new factor + register the keyframe centre.
5436        let camera_center = self
5437            .map
5438            .keyframes
5439            .get(&frame.id)
5440            .and_then(|kf| kf.frame.pose.as_ref().map(|p| p.camera_center_world()))?;
5441        {
5442            let state = self.vi_motion_init_state.as_mut().unwrap();
5443            if let Some(factor) = new_imu_factor {
5444                state.push_factor(factor.clone());
5445            }
5446            state.initializer.register_keyframe(frame.id, camera_center);
5447        }
5448
5449        // Attempt the solve unconditionally. `try_initialize` itself
5450        // performs the keyframe-count + translation gate checks and
5451        // returns a structured rejection on miss without touching the
5452        // map. Snapshot the factor history first so we don't hold a
5453        // borrow into `vi_motion_init_state` while passing `&mut self.map`.
5454        let factors_snapshot: Vec<ImuPreintegrationFactor> = self
5455            .vi_motion_init_state
5456            .as_ref()
5457            .map(|s| s.factor_history.iter().cloned().collect())
5458            .unwrap_or_default();
5459        let outcome = {
5460            let state = self.vi_motion_init_state.as_mut().unwrap();
5461            match state.initializer.try_initialize_with_bias_seed(
5462                &mut self.map,
5463                &factors_snapshot,
5464                bias_gyro_seed,
5465                bias_acc_seed,
5466            ) {
5467                Ok(r) => Ok(r.clone()),
5468                Err(reason) => {
5469                    state.last_rejection = Some(reason.clone());
5470                    Err(reason)
5471                }
5472            }
5473        };
5474        match outcome {
5475            Ok(result) => Some(self.promote_motion_vi_init_result(result)),
5476            Err(reason) => Some(MotionViInitializationEvent::StillWaiting { reason }),
5477        }
5478    }
5479
5480    /// Mirror a successful motion-VI init result into the pipeline's
5481    /// running state.
5482    ///
5483    /// `result.bias_released` distinguishes a terminal firing (the legacy
5484    /// single-stage path, or a [`crate::BiasReleaseSchedule`] Stage B) from a
5485    /// non-terminal [`crate::BiasReleaseSchedule`] Stage A ("velocity
5486    /// stage") firing: the velocity + IMU-bias mirroring below (steps 1-2)
5487    /// always runs — Stage A's biases equal the seed, so mirroring them is
5488    /// value-neutral, while mirroring its refined velocities is the entire
5489    /// point of running Stage A — but step 3 only marks the stage
5490    /// `completed` (terminal) when `bias_released` is `true`. On a `false`
5491    /// result the stage stays active so [`Self::run_motion_vi_init_step`]
5492    /// keeps registering keyframes / translation and can later fire Stage B.
5493    fn promote_motion_vi_init_result(
5494        &mut self,
5495        result: MotionBasedViInitializationResult,
5496    ) -> MotionViInitializationEvent {
5497        let mirror_local = self
5498            .vi_motion_init_state
5499            .as_ref()
5500            .is_none_or(|s| s.config.mirror_into_local_vi_ba);
5501        let mirror_imu = self
5502            .vi_motion_init_state
5503            .as_ref()
5504            .is_none_or(|s| s.config.mirror_into_imu_state);
5505
5506        // Step 1: mirror refined per-keyframe states into local VI-BA.
5507        if mirror_local {
5508            if let Some(local) = self.local_vi_ba_state.as_mut() {
5509                for (kf_id, refined) in &result.keyframe_states {
5510                    local.keyframe_state.insert(*kf_id, refined.clone());
5511                }
5512            }
5513        }
5514
5515        // Step 2: mirror refined biases of the latest keyframe onto the
5516        // running IMU pre-integrator and config. ORB-SLAM3 uses the most
5517        // recent VIBA1-refined bias as the running linearisation point
5518        // for the next pre-integration window.
5519        if mirror_imu {
5520            if let Some((_, latest)) = result.keyframe_states.iter().next_back() {
5521                let bg = latest.bias_gyro;
5522                let ba = latest.bias_acc;
5523                if let Some(imu) = self.imu_state.as_mut() {
5524                    imu.reset_preintegrator_with_bias(bg, ba);
5525                }
5526                if let Some(imu_cfg) = self.config.imu.as_mut() {
5527                    imu_cfg.bias_gyro = bg;
5528                    imu_cfg.bias_acc = ba;
5529                }
5530                if let Some(local) = self.local_vi_ba_state.as_mut() {
5531                    local.config.bias_gyro_init = bg;
5532                    local.config.bias_acc_init = ba;
5533                }
5534                if let Some(local_cfg) = self.config.local_vi_ba.as_mut() {
5535                    local_cfg.bias_gyro_init = bg;
5536                    local_cfg.bias_acc_init = ba;
5537                }
5538            }
5539        }
5540
5541        // Step 3: mirror `estimate_gravity`'s recovered gravity vector (if
5542        // any) into every sink that reads gravity for FUTURE factor
5543        // staging / VI solves. The map itself is NEVER rotated to match —
5544        // only the gravity ASSUMPTION used by future solves moves. See
5545        // `docs/motion_based_vi_alignment.md`'s "Gravity-direction
5546        // recovery" section. Mirrored sinks:
5547        // (1) `imu_state.config.gravity_world` — the running IMU stage
5548        //     that stamps `gravity_world` onto every newly-staged
5549        //     `ImuPreintegrationFactor` (`stage_imu_factor_on_new_keyframe`);
5550        // (2) `config.imu.gravity_world` — the persisted config mirror of (1);
5551        // (3) `local_vi_ba_state.config.gravity_world` and (4)
5552        //     `config.local_vi_ba.gravity_world` — the local VI-BA stage's
5553        //     own gravity copy (seeds bias slot initial values);
5554        // (5) `vi_motion_init_state.initializer`'s own config, via
5555        //     [`MotionBasedViInitializer::set_gravity_world`], so a LATER
5556        //     motion-VI window (a subsequent `BiasReleaseSchedule` Stage B,
5557        //     or a fresh sequence after `reset_sequence_state`) starts from
5558        //     the corrected assumption instead of the original config
5559        //     value;
5560        // (6) `config.vi_motion_init.initializer.gravity_world`, the
5561        //     persisted mirror of (5); and
5562        // (7) `config.vi_init.initializer.gravity_world` — the STATIC
5563        //     stage's persisted config. [`OnlineSlamConfig::validate`]
5564        //     requires this to agree with `config.imu.gravity_world`
5565        //     (`GravityMismatch`), so leaving it stale would make a
5566        //     later `OnlineSlamPipeline::new(_, _, _, config.clone())`
5567        //     panic (this is exactly how a real rebootstrap that
5568        //     reconstructs the pipeline from `slam.config.clone()`
5569        //     surfaced the bug). The live `vi_init_state.initializer` is
5570        //     deliberately left untouched: by the time motion-VI can
5571        //     fire the static stage has already reached a terminal
5572        //     `completed`/`gave_up` snapshot (see
5573        //     [`OnlineSlamConfigError::MotionViInitRequiresStaticViInit`]
5574        //     and its sibling checks), so it never runs `try_initialize`
5575        //     again in THIS pipeline instance; restarting it with the
5576        //     estimated gravity on a fresh submap (a NEW pipeline built
5577        //     from this config) is semantically fine — it will
5578        //     re-estimate/reject as usual.
5579        if let Some(g) = result.estimated_gravity_world {
5580            if let Some(imu) = self.imu_state.as_mut() {
5581                imu.config.gravity_world = g;
5582            }
5583            if let Some(imu_cfg) = self.config.imu.as_mut() {
5584                imu_cfg.gravity_world = g;
5585            }
5586            if let Some(local) = self.local_vi_ba_state.as_mut() {
5587                local.config.gravity_world = g;
5588            }
5589            if let Some(local_cfg) = self.config.local_vi_ba.as_mut() {
5590                local_cfg.gravity_world = g;
5591            }
5592            if let Some(state) = self.vi_motion_init_state.as_mut() {
5593                state.initializer.set_gravity_world(g);
5594            }
5595            if let Some(motion_cfg) = self.config.vi_motion_init.as_mut() {
5596                motion_cfg.initializer.gravity_world = g;
5597            }
5598            if let Some(vi_init_cfg) = self.config.vi_init.as_mut() {
5599                vi_init_cfg.initializer.gravity_world = g;
5600            }
5601        }
5602
5603        // Step 4: mark the stage completed — but ONLY on a terminal firing
5604        // (`result.bias_released`). A `BiasReleaseSchedule` Stage A result
5605        // leaves `state.completed` at `None` so `is_active()` stays `true`
5606        // and the next `run_motion_vi_init_step` call keeps feeding this
5607        // stage new keyframes/factors toward the eventual Stage B release.
5608        // (`initializer.try_initialize` mirrors the same non-terminal
5609        // behaviour on its own `completed` slot for a Stage A result.)
5610        if let Some(state) = self.vi_motion_init_state.as_mut() {
5611            if result.bias_released {
5612                state.completed = Some(result.clone());
5613            }
5614            state.last_rejection = None;
5615        }
5616
5617        MotionViInitializationEvent::Succeeded { result }
5618    }
5619
5620    pub fn reset_sequence_state(&mut self) {
5621        self.tracker.reset();
5622        self.mapper.reset();
5623        if let Some(state) = self.imu_state.as_mut() {
5624            state.reset();
5625        }
5626        if let Some(state) = self.local_vi_ba_state.as_mut() {
5627            state.reset();
5628        }
5629        if let Some(state) = self.vi_init_state.as_mut() {
5630            state.reset();
5631        }
5632        if let Some(state) = self.vi_motion_init_state.as_mut() {
5633            state.reset();
5634        }
5635        if let Some(state) = self.pose_graph_state.as_mut() {
5636            state.reset();
5637        }
5638        if let Some(state) = self.relocalization_state.as_mut() {
5639            state.reset();
5640        }
5641    }
5642}
5643
5644fn motion_vi_raw_residual_activation_satisfied(
5645    config: MotionViRawResidualActivationConfig,
5646    reason: &MotionBasedViRejectionReason,
5647) -> bool {
5648    let MotionBasedViRejectionReason::ImuRawResidualOutOfRange {
5649        rotation_residual_rms_rad: Some(rotation),
5650        velocity_residual_rms_mps: Some(velocity),
5651        position_residual_rms_meters: Some(position),
5652        ..
5653    } = reason
5654    else {
5655        return false;
5656    };
5657    config.max_rotation_residual_rms_rad.is_finite()
5658        && config.max_rotation_residual_rms_rad > 0.0
5659        && config.max_velocity_residual_rms_mps.is_finite()
5660        && config.max_velocity_residual_rms_mps > 0.0
5661        && config.max_position_residual_rms_meters.is_finite()
5662        && config.max_position_residual_rms_meters > 0.0
5663        && rotation.is_finite()
5664        && velocity.is_finite()
5665        && position.is_finite()
5666        && *rotation <= config.max_rotation_residual_rms_rad
5667        && *velocity <= config.max_velocity_residual_rms_mps
5668        && *position <= config.max_position_residual_rms_meters
5669}
5670
5671#[cfg(test)]
5672mod motion_vi_raw_residual_activation_tests {
5673    use super::*;
5674
5675    fn raw_rejection(rotation: f64, velocity: f64, position: f64) -> MotionBasedViRejectionReason {
5676        MotionBasedViRejectionReason::ImuRawResidualOutOfRange {
5677            rotation_residual_rms_rad: Some(rotation),
5678            velocity_residual_rms_mps: Some(velocity),
5679            position_residual_rms_meters: Some(position),
5680            max_rotation_residual_rms_rad: Some(0.01),
5681            max_velocity_residual_rms_mps: Some(0.25),
5682            max_position_residual_rms_meters: Some(0.08),
5683        }
5684    }
5685
5686    #[test]
5687    fn activates_only_for_complete_near_conditioned_raw_residuals() {
5688        let config = MotionViRawResidualActivationConfig {
5689            max_rotation_residual_rms_rad: 0.03,
5690            max_velocity_residual_rms_mps: 0.6,
5691            max_position_residual_rms_meters: 0.15,
5692        };
5693        assert!(motion_vi_raw_residual_activation_satisfied(
5694            config,
5695            &raw_rejection(0.02, 0.46, 0.12)
5696        ));
5697        assert!(!motion_vi_raw_residual_activation_satisfied(
5698            config,
5699            &raw_rejection(0.038, 0.46, 0.12)
5700        ));
5701        assert!(!motion_vi_raw_residual_activation_satisfied(
5702            config,
5703            &MotionBasedViRejectionReason::InsufficientKeyframes { have: 5, need: 10 }
5704        ));
5705    }
5706}
5707
5708/// Unit tests for [`OnlineSlamPipeline::promote_motion_vi_init_result`]'s
5709/// `bias_released`-conditional Step 3, exercised directly (rather than via
5710/// `process_frame`) so a synthetic
5711/// [`crate::MotionBasedViInitializationResult`] can pin the Stage A / Stage B
5712/// contract without standing up a full tracker + IMU + static-VI fixture.
5713/// See `docs/motion_based_vi_alignment.md`'s "Staged bias release" section.
5714#[cfg(test)]
5715mod bias_release_promotion_tests {
5716    use super::*;
5717
5718    fn zero_cost_breakdown() -> crate::bundle::BaCostBreakdown {
5719        crate::bundle::BaCostBreakdown {
5720            total: 0.0,
5721            visual: 0.0,
5722            imu: 0.0,
5723            bias_random_walk: 0.0,
5724            navigation_prior: 0.0,
5725            other_structural: 0.0,
5726            imu_normalized_squared_residual_per_dof: None,
5727            imu_rotation_residual_rms_rad: None,
5728            imu_velocity_residual_rms_mps: None,
5729            imu_position_residual_rms_meters: None,
5730        }
5731    }
5732
5733    /// Build a synthetic single-keyframe motion-VI result. Biases are
5734    /// always zero here (Stage A never moves them off the seed, and this
5735    /// helper reuses the same shape for both stages) — only `velocity` and
5736    /// `bias_released` vary between calls.
5737    fn fake_result(
5738        kf_id: u64,
5739        velocity: Vector3<f64>,
5740        bias_released: bool,
5741    ) -> MotionBasedViInitializationResult {
5742        let mut keyframe_states = BTreeMap::new();
5743        keyframe_states.insert(
5744            kf_id,
5745            KeyframeImuState {
5746                velocity_world: velocity,
5747                bias_gyro: Vector3::zeros(),
5748                bias_acc: Vector3::zeros(),
5749            },
5750        );
5751        MotionBasedViInitializationResult {
5752            keyframe_states,
5753            keyframe_ids: vec![kf_id],
5754            imu_factors_used: 1,
5755            scale: 1.0,
5756            scale_history: Vec::new(),
5757            viba2_iterations_run: 0,
5758            trigger_translation_meters: 2.0,
5759            ba_result: BaResult {
5760                initial_cost: 1.0,
5761                final_cost: 0.5,
5762                iterations: Vec::new(),
5763                converged: true,
5764            },
5765            initial_cost_breakdown: zero_cost_breakdown(),
5766            final_cost_breakdown: zero_cost_breakdown(),
5767            bias_released,
5768            estimated_gravity_world: None,
5769            estimated_gyro_bias: None,
5770        }
5771    }
5772
5773    fn minimal_pipeline_with_motion_vi_state(
5774    ) -> OnlineSlamPipeline<Tracker<LocalizationPipeline>, LocalMappingPipeline> {
5775        let mut slam = OnlineSlamPipeline::new(
5776            VisualMap::new(),
5777            Tracker::new(LocalizationPipeline::default(), TrackingConfig::default()),
5778            LocalMappingPipeline::default(),
5779            OnlineSlamConfig::default(),
5780        );
5781        slam.local_vi_ba_state = Some(OnlineSlamLocalBaState::new(
5782            OnlineSlamLocalBaConfig::default(),
5783        ));
5784        slam.vi_motion_init_state = Some(OnlineSlamMotionViInitState::new(
5785            OnlineSlamMotionViInitConfig::default(),
5786        ));
5787        slam
5788    }
5789
5790    #[test]
5791    fn stage_a_mirrors_velocity_but_leaves_stage_active_then_stage_b_completes_it() {
5792        let mut slam = minimal_pipeline_with_motion_vi_state();
5793
5794        // Stage A ("velocity stage"): `bias_released = false`.
5795        let stage_a = fake_result(1, Vector3::new(1.0, 0.0, 0.0), false);
5796        match slam.promote_motion_vi_init_result(stage_a) {
5797            MotionViInitializationEvent::Succeeded { result } => assert!(!result.bias_released),
5798            other => panic!("expected Succeeded, got {other:?}"),
5799        }
5800        let mirrored_after_stage_a = slam
5801            .local_vi_ba_state
5802            .as_ref()
5803            .expect("configured above")
5804            .keyframe_state
5805            .get(&1)
5806            .expect("Stage A must mirror velocity into local_vi_ba_state")
5807            .velocity_world;
5808        assert!((mirrored_after_stage_a - Vector3::new(1.0, 0.0, 0.0)).norm() < 1.0e-12);
5809        let motion_state = slam
5810            .vi_motion_init_state
5811            .as_ref()
5812            .expect("configured above");
5813        assert!(
5814            motion_state.completed.is_none(),
5815            "Stage A must NOT mark the motion-VI stage completed"
5816        );
5817        assert!(
5818            motion_state.is_active(),
5819            "Stage A must leave the motion-VI stage active"
5820        );
5821
5822        // Stage B ("bias release"): `bias_released = true`, a different
5823        // velocity so the mirror can be told apart from Stage A's.
5824        let stage_b = fake_result(1, Vector3::new(2.0, 0.0, 0.0), true);
5825        match slam.promote_motion_vi_init_result(stage_b) {
5826            MotionViInitializationEvent::Succeeded { result } => assert!(result.bias_released),
5827            other => panic!("expected Succeeded, got {other:?}"),
5828        }
5829        let mirrored_after_stage_b = slam
5830            .local_vi_ba_state
5831            .as_ref()
5832            .expect("configured above")
5833            .keyframe_state
5834            .get(&1)
5835            .expect("Stage B must mirror velocity into local_vi_ba_state")
5836            .velocity_world;
5837        assert!((mirrored_after_stage_b - Vector3::new(2.0, 0.0, 0.0)).norm() < 1.0e-12);
5838        let motion_state = slam
5839            .vi_motion_init_state
5840            .as_ref()
5841            .expect("configured above");
5842        assert!(
5843            motion_state.completed.is_some(),
5844            "Stage B must mark the motion-VI stage completed (terminal)"
5845        );
5846        assert!(
5847            !motion_state.is_active(),
5848            "Stage B must leave the motion-VI stage inactive (terminal)"
5849        );
5850    }
5851
5852    /// [`OnlineSlamPipeline::promote_motion_vi_init_result`]'s Step 3
5853    /// (gravity-sink mirroring, see that method's doc comment for the full
5854    /// enumerated list). Populates every sink the doc comment names —
5855    /// `imu_state`, `config.imu`, `local_vi_ba_state`, `config.local_vi_ba`,
5856    /// the motion initializer's own config, `config.vi_motion_init`, and
5857    /// `config.vi_init` — then asserts a `Some(estimated_gravity_world)`
5858    /// result moves every one of them, and the map/keyframe poses are
5859    /// untouched (gauge is never rotated). See
5860    /// `docs/motion_based_vi_alignment.md`'s "Gravity-direction recovery"
5861    /// section.
5862    #[test]
5863    fn estimated_gravity_mirrors_into_every_documented_sink() {
5864        let mut slam = minimal_pipeline_with_motion_vi_state();
5865        slam.imu_state = Some(OnlineSlamImuState::new(OnlineSlamImuConfig::default()));
5866        slam.config.imu = Some(OnlineSlamImuConfig::default());
5867        slam.config.local_vi_ba = Some(OnlineSlamLocalBaConfig::default());
5868        slam.config.vi_motion_init = Some(OnlineSlamMotionViInitConfig::default());
5869        slam.config.vi_init = Some(OnlineSlamViInitConfig::default());
5870
5871        let original_gravity = OnlineSlamImuConfig::default().gravity_world;
5872        let new_gravity = Vector3::new(0.0, 0.0, 9.81);
5873        assert!(
5874            (original_gravity - new_gravity).norm() > 1.0,
5875            "fixture must actually move the gravity assumption"
5876        );
5877
5878        let mut result = fake_result(1, Vector3::zeros(), true);
5879        result.estimated_gravity_world = Some(new_gravity);
5880        match slam.promote_motion_vi_init_result(result) {
5881            MotionViInitializationEvent::Succeeded { result } => {
5882                assert_eq!(result.estimated_gravity_world, Some(new_gravity));
5883            }
5884            other => panic!("expected Succeeded, got {other:?}"),
5885        }
5886
5887        assert!(
5888            (slam.imu_state.as_ref().unwrap().config.gravity_world - new_gravity).norm() < 1.0e-12,
5889            "sink (1): imu_state.config.gravity_world must mirror the estimate"
5890        );
5891        assert!(
5892            (slam.config.imu.as_ref().unwrap().gravity_world - new_gravity).norm() < 1.0e-12,
5893            "sink (2): config.imu.gravity_world must mirror the estimate"
5894        );
5895        assert!(
5896            (slam
5897                .local_vi_ba_state
5898                .as_ref()
5899                .unwrap()
5900                .config
5901                .gravity_world
5902                - new_gravity)
5903                .norm()
5904                < 1.0e-12,
5905            "sink (3): local_vi_ba_state.config.gravity_world must mirror the estimate"
5906        );
5907        assert!(
5908            (slam.config.local_vi_ba.as_ref().unwrap().gravity_world - new_gravity).norm()
5909                < 1.0e-12,
5910            "sink (4): config.local_vi_ba.gravity_world must mirror the estimate"
5911        );
5912        assert!(
5913            (slam
5914                .vi_motion_init_state
5915                .as_ref()
5916                .unwrap()
5917                .initializer
5918                .config()
5919                .gravity_world
5920                - new_gravity)
5921                .norm()
5922                < 1.0e-12,
5923            "sink (5): the motion initializer's own config must mirror the estimate"
5924        );
5925        assert!(
5926            (slam
5927                .config
5928                .vi_motion_init
5929                .as_ref()
5930                .unwrap()
5931                .initializer
5932                .gravity_world
5933                - new_gravity)
5934                .norm()
5935                < 1.0e-12,
5936            "sink (6): config.vi_motion_init.initializer.gravity_world must mirror the estimate"
5937        );
5938        assert!(
5939            (slam
5940                .config
5941                .vi_init
5942                .as_ref()
5943                .unwrap()
5944                .initializer
5945                .gravity_world
5946                - new_gravity)
5947                .norm()
5948                < 1.0e-12,
5949            "sink (7): config.vi_init.initializer.gravity_world must mirror the estimate"
5950        );
5951    }
5952
5953    /// Real-data regression (see the `sp_full75` moving-start bench run):
5954    /// the motion-VI initializer promoted a Stage A result with a non-
5955    /// default `estimated_gravity_world` on frame 4. `promote_motion_vi_init_result`
5956    /// mirrored the estimate into `config.imu.gravity_world` and
5957    /// `config.vi_motion_init.initializer.gravity_world` but NOT
5958    /// `config.vi_init.initializer.gravity_world`. A later rebootstrap that
5959    /// reconstructs the pipeline via
5960    /// `OnlineSlamPipeline::new(map, tracker, mapper, slam.config.clone())`
5961    /// (the independent-submap path in
5962    /// `examples/euroc_online_slam_vi_image_demo/`) then hit
5963    /// `OnlineSlamConfig::validate`'s `GravityMismatch` panic, because
5964    /// `config.vi_init.initializer.gravity_world` still held the original
5965    /// seed while `config.imu.gravity_world` held the estimate. This test
5966    /// builds a real (non-default) config via the public constructor,
5967    /// drives a synthetic Stage-B result with a non-default estimated
5968    /// gravity through `promote_motion_vi_init_result`, then reconstructs
5969    /// the pipeline from the mutated config's clone — this must NOT panic,
5970    /// and every gravity-agreement invariant `validate` checks must hold.
5971    #[test]
5972    fn gravity_mirror_keeps_config_reconstructible_after_rebootstrap() {
5973        // `OnlineSlamImuConfig::default().gravity_world` is `(0, 9.81, 0)`,
5974        // not the `(0, 0, -9.81)` that `VisualInertialInitializerConfig`
5975        // and `MotionBasedViInitializerConfig` default to — so build a
5976        // config where every gravity-bearing field starts in agreement
5977        // (required for `OnlineSlamPipeline::new` to succeed at all).
5978        let seed_gravity = OnlineSlamImuConfig::default().gravity_world;
5979
5980        let vi_init_config = OnlineSlamViInitConfig {
5981            initializer: VisualInertialInitializerConfig {
5982                gravity_world: seed_gravity,
5983                ..VisualInertialInitializerConfig::default()
5984            },
5985            ..OnlineSlamViInitConfig::default()
5986        };
5987
5988        let motion_config = OnlineSlamMotionViInitConfig {
5989            initializer: MotionBasedViInitializerConfig {
5990                gravity_world: seed_gravity,
5991                ..MotionBasedViInitializerConfig::default()
5992            },
5993            ..OnlineSlamMotionViInitConfig::default()
5994        };
5995
5996        let config = OnlineSlamConfig {
5997            imu: Some(OnlineSlamImuConfig::default()),
5998            local_vi_ba: Some(OnlineSlamLocalBaConfig::default()),
5999            vi_init: Some(vi_init_config),
6000            vi_motion_init: Some(motion_config),
6001            ..OnlineSlamConfig::default()
6002        };
6003
6004        // Sanity check: the seed config must actually be constructible
6005        // before we exercise the mutation under test.
6006        let mut slam = OnlineSlamPipeline::new(
6007            VisualMap::new(),
6008            Tracker::new(LocalizationPipeline::default(), TrackingConfig::default()),
6009            LocalMappingPipeline::default(),
6010            config,
6011        );
6012
6013        let estimated_gravity = Vector3::new(0.1678, 9.3632, 2.9222);
6014        assert!(
6015            (estimated_gravity - seed_gravity).norm() > 1.0,
6016            "fixture must actually move the gravity assumption"
6017        );
6018        let mut result = fake_result(1, Vector3::zeros(), true);
6019        result.estimated_gravity_world = Some(estimated_gravity);
6020        match slam.promote_motion_vi_init_result(result) {
6021            MotionViInitializationEvent::Succeeded { result } => {
6022                assert_eq!(result.estimated_gravity_world, Some(estimated_gravity));
6023            }
6024            other => panic!("expected Succeeded, got {other:?}"),
6025        }
6026
6027        // Every gravity-agreement invariant `OnlineSlamConfig::validate`
6028        // checks must hold on the mutated config.
6029        assert_eq!(
6030            slam.config.imu.as_ref().unwrap().gravity_world,
6031            estimated_gravity
6032        );
6033        assert_eq!(
6034            slam.config
6035                .vi_init
6036                .as_ref()
6037                .unwrap()
6038                .initializer
6039                .gravity_world,
6040            estimated_gravity
6041        );
6042        assert_eq!(
6043            slam.config
6044                .vi_motion_init
6045                .as_ref()
6046                .unwrap()
6047                .initializer
6048                .gravity_world,
6049            estimated_gravity
6050        );
6051        assert!(slam.config.validate().is_ok());
6052
6053        // The real crash: a rebootstrap reconstructs the pipeline from
6054        // `slam.config.clone()`. This must not panic.
6055        let _rebuilt = OnlineSlamPipeline::new(
6056            VisualMap::new(),
6057            Tracker::new(LocalizationPipeline::default(), TrackingConfig::default()),
6058            LocalMappingPipeline::default(),
6059            slam.config.clone(),
6060        );
6061    }
6062
6063    /// A result with `estimated_gravity_world: None` (the
6064    /// `estimate_gravity = false` legacy path) must leave every gravity
6065    /// sink untouched — the mirroring in Step 3 is entirely gated on the
6066    /// `Some(...)` case.
6067    #[test]
6068    fn no_estimated_gravity_leaves_every_sink_untouched() {
6069        let mut slam = minimal_pipeline_with_motion_vi_state();
6070        slam.imu_state = Some(OnlineSlamImuState::new(OnlineSlamImuConfig::default()));
6071        slam.config.imu = Some(OnlineSlamImuConfig::default());
6072        let original_gravity = OnlineSlamImuConfig::default().gravity_world;
6073
6074        let result = fake_result(1, Vector3::zeros(), true);
6075        assert!(result.estimated_gravity_world.is_none());
6076        slam.promote_motion_vi_init_result(result);
6077
6078        assert_eq!(
6079            slam.imu_state.as_ref().unwrap().config.gravity_world,
6080            original_gravity
6081        );
6082        assert_eq!(
6083            slam.config.imu.as_ref().unwrap().gravity_world,
6084            original_gravity
6085        );
6086    }
6087
6088    /// A [`crate::BiasReleaseSchedule`] Stage A ("velocity stage")
6089    /// promotion (`bias_released = false`) must unblock
6090    /// [`OnlineSlamPipeline::vi_initialization_pending`] even though the
6091    /// motion-VI stage stays non-terminal (`vi_motion_init_state.completed`
6092    /// stays `None`) — see that method's doc comment for the full
6093    /// rationale. Regression for the bug where local VI-BA never fired
6094    /// after a Stage A promotion on the real bench (3 Stage A promotions,
6095    /// `local_vi_ba_triggers = 0`).
6096    #[test]
6097    fn stage_a_promotion_unblocks_vi_initialization_pending() {
6098        let mut slam = minimal_pipeline_with_motion_vi_state();
6099        slam.vi_init_state = Some(OnlineSlamViInitState::new(OnlineSlamViInitConfig::default()));
6100
6101        // Static init incomplete + motion-VI stage never fired: pending.
6102        assert!(
6103            slam.vi_initialization_pending(),
6104            "with no Stage A fired and static init incomplete, local VI-BA must stay gated"
6105        );
6106
6107        // Drive a synthetic Stage A promotion. `promote_motion_vi_init_result`
6108        // alone only exercises the pipeline-side mirroring (as the other
6109        // tests in this module do); the inner initializer's own
6110        // `velocity_stage` cache — what `velocity_stage_fired()` actually
6111        // reads — is populated by `MotionBasedViInitializer::try_initialize_with_bias_seed`
6112        // itself as a side effect of the real numeric solve (see
6113        // `run_motion_vi_init_step`). Use the test-only seam to inject the
6114        // same result there without replaying that solve; the solve path
6115        // is covered separately by `vi_motion_initializer`'s own
6116        // `bias_release_schedule_stage_a_fires_then_awaits_release_gate`.
6117        let stage_a = fake_result(1, Vector3::new(1.0, 0.0, 0.0), false);
6118        slam.vi_motion_init_state
6119            .as_mut()
6120            .expect("configured above")
6121            .initializer
6122            .set_velocity_stage_result_for_test(stage_a.clone());
6123        match slam.promote_motion_vi_init_result(stage_a) {
6124            MotionViInitializationEvent::Succeeded { result } => assert!(!result.bias_released),
6125            other => panic!("expected Succeeded, got {other:?}"),
6126        }
6127        let motion_state = slam
6128            .vi_motion_init_state
6129            .as_ref()
6130            .expect("configured above");
6131        assert!(
6132            motion_state.completed.is_none(),
6133            "Stage A must NOT mark the motion-VI stage completed"
6134        );
6135        assert!(
6136            motion_state.velocity_stage_fired(),
6137            "Stage A must be visible via velocity_stage_fired()"
6138        );
6139
6140        assert!(
6141            !slam.vi_initialization_pending(),
6142            "a Stage A promotion must unblock vi_initialization_pending even though the \
6143             motion-VI stage remains non-terminal"
6144        );
6145    }
6146
6147    /// Regression: with no Stage A fired and static init incomplete,
6148    /// local VI-BA must remain gated. Guards against a future change
6149    /// accidentally loosening `vi_initialization_pending` beyond the
6150    /// documented Stage-A carve-out.
6151    #[test]
6152    fn no_stage_a_and_incomplete_static_init_keeps_vi_initialization_pending() {
6153        let mut slam = minimal_pipeline_with_motion_vi_state();
6154        slam.vi_init_state = Some(OnlineSlamViInitState::new(OnlineSlamViInitConfig::default()));
6155
6156        assert!(
6157            slam.vi_initialization_pending(),
6158            "static init incomplete + motion-VI stage never fired must stay pending"
6159        );
6160
6161        // Even a `StillWaiting` rejection (no promotion at all) must leave
6162        // the gate engaged.
6163        assert!(slam
6164            .vi_motion_init_state
6165            .as_ref()
6166            .unwrap()
6167            .completed
6168            .is_none());
6169        assert!(!slam
6170            .vi_motion_init_state
6171            .as_ref()
6172            .unwrap()
6173            .velocity_stage_fired());
6174        assert!(slam.vi_initialization_pending());
6175    }
6176}
6177
6178#[derive(Debug, Clone, PartialEq)]
6179pub struct OnlineSlamResult {
6180    pub tracking: TrackingResult,
6181    pub mapping: Option<LocalMappingResult>,
6182    pub applied_update: Option<AppliedMapUpdate>,
6183    pub loop_closure_candidates: Vec<LoopClosureCandidate>,
6184    /// IMU pre-integration factor closed against the keyframe registered
6185    /// by this `process_frame` call. `Some` only when [`OnlineSlamConfig::imu`]
6186    /// is `Some`, this frame produced a new keyframe, and at least one
6187    /// previous keyframe exists to anchor the integration window's left
6188    /// endpoint. Downstream pose-graph / BA glue consumes the factor; the
6189    /// `OnlineSlamPipeline` itself does not optimise against it.
6190    pub imu_factor: Option<ImuPreintegrationFactor>,
6191    /// Local VI-BA refinement outcome when
6192    /// [`OnlineSlamConfig::local_vi_ba`] is enabled and the current
6193    /// `process_frame` call triggered the sliding-window solve. `None`
6194    /// otherwise (disabled, no new factor, or the window was too short
6195    /// to refine).
6196    pub local_vi_ba: Option<OnlineSlamLocalBaStats>,
6197    /// Sparse visual factor lifecycle update for the newly committed
6198    /// keyframe. `None` when disabled or no keyframe was added.
6199    pub sparse_factor_graph: Option<SparseFactorGraphUpdateStats>,
6200    /// Visual-only covisibility local BA outcome when
6201    /// [`OnlineSlamConfig::covisibility_local_ba`] is enabled and the
6202    /// current `process_frame` call triggered the solve. `None`
6203    /// otherwise (disabled, no newly-applied keyframe, below the
6204    /// configured minimum keyframe count, or skipped by the trigger
6205    /// interval).
6206    pub covisibility_local_ba: Option<OnlineSlamCovisibilityLocalBaStats>,
6207    pub map_keyframe_count: usize,
6208    pub map_landmark_count: usize,
6209    /// State-transition event from the auto-bootstrap stage. `Some`
6210    /// only on the frame where the VI initialiser actually changed
6211    /// state — `Succeeded`, `StillBuffering`, or `GaveUp`. `None` on
6212    /// every other frame (no new keyframe registered, VI init
6213    /// disabled, or the stage has already reached a terminal event).
6214    /// Durable state is exposed via
6215    /// [`OnlineSlamPipeline::vi_initialization_status`].
6216    pub vi_init: Option<ViInitializationEvent>,
6217    /// State-transition event from the motion-based VI init stage.
6218    /// `Some` only on the frame where the motion-based initialiser
6219    /// actually changed state (`Succeeded` or `StillWaiting`); `None`
6220    /// otherwise (no new keyframe, stage disabled, static seed not yet
6221    /// available, or already in the terminal `Initialised` state).
6222    /// Durable state is exposed via
6223    /// [`OnlineSlamPipeline::motion_vi_initialization_status`].
6224    pub vi_motion_init: Option<MotionViInitializationEvent>,
6225    /// Per-frame outcome of the online loop-closure + pose-graph
6226    /// refinement stage. `Some` only when
6227    /// [`OnlineSlamConfig::pose_graph_refinement`] is enabled AND the
6228    /// verifier was actually run this frame (i.e. the current frame
6229    /// produced a keyframe AND there was at least one candidate). `None`
6230    /// otherwise — the stage being disabled, no candidate this frame,
6231    /// or no new keyframe to attach the verifier output to.
6232    pub pose_graph_refinement: Option<OnlineSlamLoopClosureRefinementStats>,
6233    /// Per-frame outcome of the relocalization-on-tracker-death stage.
6234    /// `Some` only on frames where primary tracking failed AND the
6235    /// stage was enabled — `stats.attempted` is always `true` when this
6236    /// field is `Some`, and `stats.succeeded` reflects whether the
6237    /// recovery PnP solution cleared the acceptance gates. `None` on
6238    /// every other frame (stage disabled, or primary tracking already
6239    /// succeeded so no relocalization was needed).
6240    pub relocalization: Option<OnlineSlamRelocalizationStats>,
6241}
6242
6243impl OnlineSlamResult {
6244    pub const fn tracking_succeeded(&self) -> bool {
6245        self.tracking.localization.success
6246    }
6247
6248    pub const fn map_was_updated(&self) -> bool {
6249        self.applied_update.is_some()
6250    }
6251
6252    pub fn has_loop_closure_candidate(&self) -> bool {
6253        !self.loop_closure_candidates.is_empty()
6254    }
6255}
6256
6257/// [`OnlineSlamLoopClosureRefinementConfig::propagate_corrections`]'s
6258/// landmark-propagation pass. For every landmark in `map.landmarks`,
6259/// derives its ANCHOR keyframe — the first (lowest-id) keyframe in
6260/// `map.keyframes` whose `observations` reference that landmark id — and,
6261/// when that anchor's id is a key in `corrections`, moves the landmark
6262/// rigidly by the anchor's correction:
6263/// `landmark.position = correction.transform_point(&landmark.position)`.
6264///
6265/// `corrections` maps a solved keyframe id to its world-frame rigid
6266/// correction `C_k = T_cw_new⁻¹ ∘ T_cw_old` (new camera-to-world composed
6267/// with old world-to-camera), i.e. the transform such that for any point
6268/// `p` observed by keyframe `k`,
6269/// `T_wc_old.transform_point(&p) == T_wc_new.transform_point(&correction.transform_point(&p))`
6270/// — the point's projection into keyframe `k` is invariant across the
6271/// correction. This is exactly the rigid motion a landmark anchored to
6272/// `k` must undergo to stay consistent with `k`'s corrected pose.
6273///
6274/// Landmarks whose anchor keyframe is NOT a key in `corrections` (i.e.
6275/// the anchor either was not part of this solve or had no previously-
6276/// known pose to diff against) are left untouched, matching ORB-SLAM3's
6277/// "only points anchored to a corrected keyframe move" propagation rule.
6278///
6279/// The anchor index is rebuilt from scratch every call by scanning every
6280/// keyframe's `observations` in ascending keyframe-id order — this is
6281/// `O(total observations across the map)`, which for the maps this stage
6282/// targets (on the order of 1-3k keyframes / 50-200k landmarks) is cheap
6283/// relative to the pose-graph solve that triggered the call. Returns
6284/// `(landmarks_moved, max_displacement_meters, mean_displacement_meters)`;
6285/// the latter two are `None` when no landmark moved.
6286fn propagate_pose_graph_corrections(
6287    map: &mut VisualMap,
6288    corrections: &HashMap<u64, SE3>,
6289) -> (usize, Option<f64>, Option<f64>) {
6290    let mut anchor_keyframe_of_landmark: HashMap<u64, u64> = HashMap::new();
6291    let mut keyframe_ids: Vec<u64> = map.keyframes.keys().copied().collect();
6292    keyframe_ids.sort_unstable();
6293    for keyframe_id in keyframe_ids {
6294        let Some(keyframe) = map.keyframes.get(&keyframe_id) else {
6295            continue;
6296        };
6297        for observation in &keyframe.observations {
6298            anchor_keyframe_of_landmark
6299                .entry(observation.landmark_id)
6300                .or_insert(keyframe_id);
6301        }
6302    }
6303
6304    let mut moved = 0usize;
6305    let mut max_displacement = 0.0_f64;
6306    let mut sum_displacement = 0.0_f64;
6307    for (landmark_id, anchor_keyframe_id) in &anchor_keyframe_of_landmark {
6308        let Some(correction) = corrections.get(anchor_keyframe_id) else {
6309            continue;
6310        };
6311        let Some(landmark) = map.landmarks.get_mut(landmark_id) else {
6312            continue;
6313        };
6314        let old_position = landmark.position;
6315        landmark.position = correction.transform_point(&old_position);
6316        let displacement = (landmark.position - old_position).norm();
6317        if let Some(covariance) = map.landmark_position_covariances.get_mut(landmark_id) {
6318            let rotation = correction.rotation.to_rotation_matrix().into_inner();
6319            *covariance = rotation * *covariance * rotation.transpose();
6320        }
6321        moved += 1;
6322        sum_displacement += displacement;
6323        if displacement > max_displacement {
6324            max_displacement = displacement;
6325        }
6326    }
6327
6328    if moved == 0 {
6329        (0, None, None)
6330    } else {
6331        (
6332            moved,
6333            Some(max_displacement),
6334            Some(sum_displacement / moved as f64),
6335        )
6336    }
6337}
6338
6339/// Embed a rigid `SE(3)` transform as a `Sim(3)` value at scale `1.0`. Used
6340/// to seed the [`Sim3PoseGraph`] mirror's nodes/edges from the same
6341/// (metric) poses and relative measurements the `Se3` path uses, and to
6342/// re-embed a keyframe's PRE-solve pose when computing its Sim3
6343/// correction (see [`LoopRefinementSolver::Sim3`]'s doc comment).
6344const fn sim3_at_unit_scale(se3: &SE3) -> Sim3 {
6345    Sim3::new(se3.rotation, se3.translation, 1.0)
6346}
6347
6348/// Estimate the relative scale of two independently triangulated keyframe
6349/// regions from descriptor-matched 3D landmarks. Pairwise-distance ratios are
6350/// invariant to the loop rotation and translation, so their median supplies
6351/// the scale of the `from-camera -> to-camera` Sim3 measurement without
6352/// coupling it to the PnP translation already used by the rigid graph.
6353#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6354enum Sim3ScaleEstimationFailure {
6355    InsufficientPoints,
6356    InsufficientMatches,
6357    NoConsensus,
6358}
6359
6360fn estimate_loop_sim3_scale_3d3d(
6361    map: &VisualMap,
6362    from_keyframe_id: u64,
6363    to_keyframe_id: u64,
6364    pnp_query_landmark_pairs: &[(usize, u64)],
6365    metric_points_camera: &HashMap<usize, Point3<f64>>,
6366) -> Result<f64, Sim3ScaleEstimationFailure> {
6367    let from = map
6368        .keyframes
6369        .get(&from_keyframe_id)
6370        .ok_or(Sim3ScaleEstimationFailure::InsufficientPoints)?;
6371    let to = map
6372        .keyframes
6373        .get(&to_keyframe_id)
6374        .ok_or(Sim3ScaleEstimationFailure::InsufficientPoints)?;
6375    let from_pose = from
6376        .frame
6377        .pose
6378        .as_ref()
6379        .ok_or(Sim3ScaleEstimationFailure::InsufficientPoints)?;
6380    let to_pose = to
6381        .frame
6382        .pose
6383        .as_ref()
6384        .ok_or(Sim3ScaleEstimationFailure::InsufficientPoints)?;
6385
6386    let collect = |keyframe: &Keyframe, pose: &Pose, prefer_frame_descriptor: bool| {
6387        keyframe
6388            .observations
6389            .iter()
6390            .filter_map(|observation| {
6391                let landmark = map.landmarks.get(&observation.landmark_id)?;
6392                // Fresh stereo/replenished landmarks do not always have a
6393                // descriptor promoted into the map slot yet, while their
6394                // observing keyframe still owns the exact feature descriptor
6395                // that PnP used. Reuse it instead of discarding an otherwise
6396                // valid 3D point from the Sim3 correspondence pool.
6397                let frame_descriptor = || {
6398                    keyframe
6399                        .frame
6400                        .descriptors
6401                        .get(observation.keypoint_index)
6402                        .cloned()
6403                };
6404                let descriptor = if prefer_frame_descriptor {
6405                    frame_descriptor().or_else(|| landmark.descriptor.clone())
6406                } else {
6407                    landmark.descriptor.clone().or_else(frame_descriptor)
6408                }?;
6409                Some((
6410                    observation.landmark_id,
6411                    descriptor,
6412                    pose.transform_world_point(&landmark.position),
6413                ))
6414            })
6415            .collect::<Vec<_>>()
6416    };
6417    // Match in the same direction as appearance PnP: current/query frame
6418    // features against the older keyframe's map-landmark descriptors. The
6419    // current observation's 3D landmark then supplies the second endpoint.
6420    let from_points = collect(from, from_pose, false);
6421    let to_points = collect(to, to_pose, true);
6422    if from_points.len() < 4 || to_points.len() < 4 {
6423        return Err(Sim3ScaleEstimationFailure::InsufficientPoints);
6424    }
6425    let mut matched = Vec::new();
6426    if pnp_query_landmark_pairs.is_empty() {
6427        let from_descriptors: Vec<Vec<f32>> =
6428            from_points.iter().map(|(_, d, _)| d.clone()).collect();
6429        let to_descriptors: Vec<Vec<f32>> = to_points.iter().map(|(_, d, _)| d.clone()).collect();
6430        let matcher = visloc_vision::matching::BruteForceMatcher::default();
6431        let forward = matcher.match_descriptors(&from_descriptors, &to_descriptors);
6432        let reverse = matcher.match_descriptors(&to_descriptors, &from_descriptors);
6433        for m in forward {
6434            let reciprocal = reverse
6435                .iter()
6436                .any(|r| r.query_index == m.train_index && r.train_index == m.query_index);
6437            if reciprocal && from_points[m.query_index].0 != to_points[m.train_index].0 {
6438                matched.push((from_points[m.query_index].2, to_points[m.train_index].2));
6439            }
6440        }
6441    } else if !metric_points_camera.is_empty() {
6442        for &(query_index, old_landmark_id) in pnp_query_landmark_pairs {
6443            let Some(current_point) = metric_points_camera.get(&query_index) else {
6444                continue;
6445            };
6446            let Some(old_landmark) = map.landmarks.get(&old_landmark_id) else {
6447                continue;
6448            };
6449            matched.push((
6450                from_pose.transform_world_point(&old_landmark.position),
6451                *current_point,
6452            ));
6453        }
6454    } else {
6455        let current_landmark_by_keypoint: HashMap<usize, u64> = to
6456            .observations
6457            .iter()
6458            .map(|observation| (observation.keypoint_index, observation.landmark_id))
6459            .collect();
6460        for &(query_index, old_landmark_id) in pnp_query_landmark_pairs {
6461            let Some(&current_landmark_id) = current_landmark_by_keypoint.get(&query_index) else {
6462                continue;
6463            };
6464            if current_landmark_id == old_landmark_id {
6465                continue;
6466            }
6467            let Some(old_landmark) = map.landmarks.get(&old_landmark_id) else {
6468                continue;
6469            };
6470            let Some(current_landmark) = map.landmarks.get(&current_landmark_id) else {
6471                continue;
6472            };
6473            matched.push((
6474                from_pose.transform_world_point(&old_landmark.position),
6475                to_pose.transform_world_point(&current_landmark.position),
6476            ));
6477        }
6478    }
6479    if matched.len() < 6 {
6480        return Err(Sim3ScaleEstimationFailure::InsufficientMatches);
6481    }
6482
6483    // ORB-SLAM's Sim3Solver uses minimal-set RANSAC and accepts a hypothesis
6484    // only when many MapPoint correspondences agree geometrically. Mirror
6485    // that safety property here with deterministic triplet enumeration.
6486    let mut scene_distances = Vec::new();
6487    for i in 0..matched.len() {
6488        for j in (i + 1)..matched.len() {
6489            scene_distances.push((matched[i].1 - matched[j].1).norm());
6490        }
6491    }
6492    scene_distances.sort_by(f64::total_cmp);
6493    let scene_scale = scene_distances[scene_distances.len() / 2];
6494    // Rectified stereo depth uncertainty grows quadratically with range;
6495    // ORB-SLAM therefore gates Sim3 correspondences in image reprojection
6496    // space rather than demanding centimetre-level 3D agreement. This
6497    // dependency-free approximation scales the metric tolerance with scene
6498    // extent while retaining a finite cap against arbitrary matches.
6499    let inlier_threshold = (scene_scale * 0.10).clamp(0.05, 1.0);
6500
6501    let mut best_inliers = Vec::new();
6502    let mut best_rmse = f64::INFINITY;
6503    let mut hypotheses = 0usize;
6504    'triplets: for i in 0..matched.len() - 2 {
6505        for j in (i + 1)..matched.len() - 1 {
6506            for k in (j + 1)..matched.len() {
6507                if hypotheses >= 256 {
6508                    break 'triplets;
6509                }
6510                hypotheses += 1;
6511                let source = [matched[i].0, matched[j].0, matched[k].0];
6512                let target = [matched[i].1, matched[j].1, matched[k].1];
6513                let Some(model) =
6514                    visloc_tracking::umeyama_similarity_transform(&source, &target, true)
6515                else {
6516                    continue;
6517                };
6518                if !model.scale.is_finite() || !(0.5..=2.0).contains(&model.scale) {
6519                    continue;
6520                }
6521                let mut inliers = Vec::new();
6522                let mut squared_error = 0.0;
6523                for (index, (from_point, to_point)) in matched.iter().enumerate() {
6524                    let error = (model.apply(from_point) - to_point).norm();
6525                    if error <= inlier_threshold {
6526                        inliers.push(index);
6527                        squared_error += error * error;
6528                    }
6529                }
6530                let rmse = if inliers.is_empty() {
6531                    f64::INFINITY
6532                } else {
6533                    (squared_error / inliers.len() as f64).sqrt()
6534                };
6535                if inliers.len() > best_inliers.len()
6536                    || (inliers.len() == best_inliers.len() && rmse < best_rmse)
6537                {
6538                    best_inliers = inliers;
6539                    best_rmse = rmse;
6540                }
6541            }
6542        }
6543    }
6544    let min_inliers = 6usize.max(matched.len().div_ceil(2));
6545    if best_inliers.len() < min_inliers || best_rmse > inlier_threshold * 0.75 {
6546        return Err(Sim3ScaleEstimationFailure::NoConsensus);
6547    }
6548    let source: Vec<Point3<f64>> = best_inliers.iter().map(|&i| matched[i].0).collect();
6549    let target: Vec<Point3<f64>> = best_inliers.iter().map(|&i| matched[i].1).collect();
6550    let refined = visloc_tracking::umeyama_similarity_transform(&source, &target, true)
6551        .ok_or(Sim3ScaleEstimationFailure::NoConsensus)?;
6552    (refined.scale.is_finite() && (0.5..=2.0).contains(&refined.scale))
6553        .then_some(refined.scale)
6554        .ok_or(Sim3ScaleEstimationFailure::NoConsensus)
6555}
6556
6557/// `(min, max)` per-node scale across a solved [`Sim3PoseGraph`]'s nodes.
6558/// `None` when the graph has no nodes (never observed in practice — the
6559/// graph always has at least the anchor before a solve can fire).
6560fn sim3_pose_scale_spread(graph: &Sim3PoseGraph) -> Option<(f64, f64)> {
6561    let mut scales = graph.poses.values().map(|pose| pose.scale);
6562    let first = scales.next()?;
6563    let (min, max) = scales.fold((first, first), |(min, max), scale| {
6564        (min.min(scale), max.max(scale))
6565    });
6566    Some((min, max))
6567}
6568
6569/// [`LoopRefinementSolver::Sim3`]'s counterpart to
6570/// [`propagate_pose_graph_corrections`]: for every landmark, derives its
6571/// ANCHOR keyframe exactly as the `Se3` path does and, when that anchor's
6572/// id is a key in `corrections`, moves the landmark by the anchor's
6573/// **similarity** correction: `landmark.position =
6574/// correction.transform_point(&landmark.position)`.
6575///
6576/// `corrections` maps a solved keyframe id to its world-frame `Sim(3)`
6577/// correction `C_k = Siw_new⁻¹ ∘ Siw_old` — the direct `Sim(3)`
6578/// generalisation of the `Se3` path's `C_k = T_cw_new⁻¹ ∘ T_cw_old`, where
6579/// `Siw_old`/`Siw_new` are the keyframe's PRE-/POST-solve `Sim3` nodes
6580/// (see [`sim3_at_unit_scale`] and [`LoopRefinementSolver::Sim3`]'s doc
6581/// comment for the full derivation and why this keeps a landmark's
6582/// reprojection *ray* into keyframe `k` invariant — a positive rescale of
6583/// camera-frame depth does not move the pinhole-projected pixel).
6584///
6585/// Returns `(landmarks_moved, max_displacement_meters, mean_displacement_meters)`,
6586/// mirroring [`propagate_pose_graph_corrections`]'s contract exactly.
6587fn propagate_pose_graph_corrections_sim3(
6588    map: &mut VisualMap,
6589    corrections: &HashMap<u64, Sim3>,
6590) -> (usize, Option<f64>, Option<f64>) {
6591    let mut anchor_keyframe_of_landmark: HashMap<u64, u64> = HashMap::new();
6592    let mut keyframe_ids: Vec<u64> = map.keyframes.keys().copied().collect();
6593    keyframe_ids.sort_unstable();
6594    for keyframe_id in keyframe_ids {
6595        let Some(keyframe) = map.keyframes.get(&keyframe_id) else {
6596            continue;
6597        };
6598        for observation in &keyframe.observations {
6599            anchor_keyframe_of_landmark
6600                .entry(observation.landmark_id)
6601                .or_insert(keyframe_id);
6602        }
6603    }
6604
6605    let mut moved = 0usize;
6606    let mut max_displacement = 0.0_f64;
6607    let mut sum_displacement = 0.0_f64;
6608    for (landmark_id, anchor_keyframe_id) in &anchor_keyframe_of_landmark {
6609        let Some(correction) = corrections.get(anchor_keyframe_id) else {
6610            continue;
6611        };
6612        let Some(landmark) = map.landmarks.get_mut(landmark_id) else {
6613            continue;
6614        };
6615        let old_position = landmark.position;
6616        landmark.position = correction.transform_point(&old_position);
6617        let displacement = (landmark.position - old_position).norm();
6618        if let Some(covariance) = map.landmark_position_covariances.get_mut(landmark_id) {
6619            let rotation = correction.rotation.to_rotation_matrix().into_inner();
6620            *covariance = rotation * *covariance * rotation.transpose() * correction.scale.powi(2);
6621        }
6622        moved += 1;
6623        sum_displacement += displacement;
6624        if displacement > max_displacement {
6625            max_displacement = displacement;
6626        }
6627    }
6628
6629    if moved == 0 {
6630        (0, None, None)
6631    } else {
6632        (
6633            moved,
6634            Some(max_displacement),
6635            Some(sum_displacement / moved as f64),
6636        )
6637    }
6638}
6639
6640fn apply_loop_edge_scale(information: Matrix6<f64>, loop_edge_scale: f64) -> Matrix6<f64> {
6641    information * loop_edge_scale
6642}
6643
6644#[cfg(test)]
6645#[allow(clippy::items_after_test_module)]
6646mod sim3_scale_estimation_tests {
6647    use super::*;
6648    use nalgebra::{Point2, Point3};
6649    use visloc_core::types::Landmark;
6650
6651    #[test]
6652    fn bias_promotion_reset_preserves_preintegration_noise_model() {
6653        let noise = ImuNoiseModel {
6654            gyroscope_noise_density: 1.0e-3,
6655            accelerometer_noise_density: 2.0e-2,
6656        };
6657        let mut state = OnlineSlamImuState::new(OnlineSlamImuConfig {
6658            noise_model: Some(noise),
6659            ..OnlineSlamImuConfig::default()
6660        });
6661        let bias_gyro = Vector3::new(0.01, -0.02, 0.03);
6662        let bias_acc = Vector3::new(0.1, -0.2, 0.3);
6663        state.reset_preintegrator_with_bias(bias_gyro, bias_acc);
6664        state
6665            .preintegrator
6666            .integrate_sample(Vector3::zeros(), Vector3::new(0.0, 0.0, 9.81), 0.01);
6667        let delta = state.preintegrator.delta();
6668        assert_eq!(delta.bias_gyro_linearisation, bias_gyro);
6669        assert_eq!(delta.bias_acc_linearisation, bias_acc);
6670        assert!(delta.covariance.trace() > 0.0);
6671    }
6672
6673    #[test]
6674    fn loop_edge_scale_preserves_information_anisotropy() {
6675        let information = Matrix6::from_diagonal(&nalgebra::SVector::<f64, 6>::new(
6676            1.0, 2.0, 4.0, 8.0, 16.0, 32.0,
6677        ));
6678        let scaled = apply_loop_edge_scale(information, 0.1);
6679        assert!((scaled - information * 0.1).norm() < 1.0e-15);
6680        assert!((scaled[(5, 5)] / scaled[(0, 0)] - 32.0).abs() < 1.0e-15);
6681    }
6682
6683    #[test]
6684    fn loop_observation_fusion_reassigns_both_map_indices_idempotently() {
6685        let mut map = VisualMap::new();
6686        map.cameras
6687            .insert(1, Camera::pinhole(1, 640, 480, 500.0, 500.0, 320.0, 240.0));
6688        let mut old_frame = Frame::new(10, 1);
6689        old_frame.pose = Some(Pose::identity());
6690        old_frame.keypoints.push(Point2::new(320.0, 240.0));
6691        let old_observation = Observation {
6692            frame_id: 10,
6693            landmark_id: 1,
6694            keypoint_index: 0,
6695            xy: old_frame.keypoints[0],
6696        };
6697        map.keyframes.insert(
6698            10,
6699            Keyframe {
6700                frame: old_frame,
6701                observations: vec![old_observation.clone()],
6702            },
6703        );
6704        let mut frame = Frame::new(20, 1);
6705        frame.pose = Some(Pose::identity());
6706        frame.keypoints.push(Point2::new(320.0, 240.0));
6707        let previous = Observation {
6708            frame_id: 20,
6709            landmark_id: 2,
6710            keypoint_index: 0,
6711            xy: frame.keypoints[0],
6712        };
6713        map.keyframes.insert(
6714            20,
6715            Keyframe {
6716                frame,
6717                observations: vec![previous.clone()],
6718            },
6719        );
6720        let mut old_landmark = Landmark::new(1, Point3::new(0.0, 0.0, 5.0));
6721        old_landmark.observations.push(old_observation);
6722        map.landmarks.insert(1, old_landmark);
6723        let mut duplicate = Landmark::new(2, Point3::new(0.1, 0.0, 5.0));
6724        duplicate.observations.push(previous);
6725        map.landmarks.insert(2, duplicate);
6726
6727        let camera = map.cameras[&1].clone();
6728        let first = fuse_loop_observations(&mut map, &camera, 20, &[(0, 1)], 4.0);
6729        assert_eq!(
6730            first,
6731            LoopObservationFusionStats {
6732                pairs_considered: 1,
6733                observations_inserted: 1,
6734                observations_reassigned: 1,
6735                pairs_skipped: 0,
6736                reprojection_rejected: 0,
6737            }
6738        );
6739        assert_eq!(map.keyframes[&20].observations[0].landmark_id, 1);
6740        assert_eq!(map.landmarks[&1].observations.len(), 2);
6741        assert!(map.landmarks[&2].observations.is_empty());
6742        assert!(map.validate().is_valid());
6743
6744        let selection = select_covisibility_local_ba_window(
6745            &map,
6746            20,
6747            &CovisibilityLocalBaConfig {
6748                max_neighbor_keyframes: 1,
6749                min_shared_landmarks: 1,
6750                max_boundary_keyframes: 0,
6751                min_boundary_observations: 1,
6752                min_observations_per_landmark: 2,
6753                min_active_observations: 1,
6754                ..CovisibilityLocalBaConfig::default()
6755            },
6756        )
6757        .expect("fused loop observation should connect both welding regions");
6758        assert_eq!(selection.optimized_keyframe_ids, vec![20, 10]);
6759        assert_eq!(selection.landmark_ids, vec![1]);
6760
6761        let second = fuse_loop_observations(&mut map, &camera, 20, &[(0, 1)], 4.0);
6762        assert_eq!(second.pairs_considered, 1);
6763        assert_eq!(second.observations_inserted, 0);
6764        assert_eq!(second.observations_reassigned, 0);
6765        assert_eq!(second.pairs_skipped, 0);
6766        assert_eq!(map.keyframes[&20].observations.len(), 1);
6767        assert_eq!(map.landmarks[&1].observations.len(), 2);
6768
6769        map.keyframes
6770            .get_mut(&20)
6771            .unwrap()
6772            .frame
6773            .keypoints
6774            .push(Point2::new(100.0, 100.0));
6775        map.landmarks
6776            .insert(3, Landmark::new(3, Point3::new(0.0, 0.0, 5.0)));
6777        let rejected = fuse_loop_observations(&mut map, &camera, 20, &[(1, 3)], 4.0);
6778        assert_eq!(rejected.pairs_considered, 1);
6779        assert_eq!(rejected.observations_inserted, 0);
6780        assert_eq!(rejected.pairs_skipped, 1);
6781        assert_eq!(rejected.reprojection_rejected, 1);
6782        assert!(map.keyframes[&20]
6783            .observations
6784            .iter()
6785            .all(|observation| observation.keypoint_index != 1));
6786    }
6787
6788    #[test]
6789    fn loop_welding_region_correction_preserves_local_reprojection() {
6790        let camera = Camera::pinhole(1, 640, 480, 500.0, 500.0, 320.0, 240.0);
6791        let mut map = VisualMap::new();
6792        map.cameras.insert(1, camera.clone());
6793
6794        let mut matched = Frame::new(10, 1);
6795        matched.pose = Some(Pose::identity());
6796        map.keyframes.insert(
6797            10,
6798            Keyframe {
6799                frame: matched,
6800                observations: Vec::new(),
6801            },
6802        );
6803
6804        let drifted_pose = Pose::from_world_to_camera(
6805            nalgebra::UnitQuaternion::identity(),
6806            Vector3::new(1.0, 0.0, 0.0),
6807        );
6808        let local_point = Point3::new(0.0, 0.0, 5.0);
6809        let local_xy = camera
6810            .project(&drifted_pose.transform_world_point(&local_point))
6811            .unwrap();
6812        let mut local_landmark = Landmark::new(2, local_point);
6813        for id in [20_u64, 21_u64] {
6814            let mut frame = Frame::new(id, 1);
6815            frame.pose = Some(drifted_pose.clone());
6816            frame.keypoints.push(local_xy);
6817            let observation = Observation {
6818                frame_id: id,
6819                landmark_id: 2,
6820                keypoint_index: 0,
6821                xy: local_xy,
6822            };
6823            map.keyframes.insert(
6824                id,
6825                Keyframe {
6826                    frame,
6827                    observations: vec![observation.clone()],
6828                },
6829            );
6830            local_landmark.observations.push(observation);
6831        }
6832        map.landmarks.insert(2, local_landmark);
6833
6834        let corrected = correct_loop_welding_region(
6835            &mut map,
6836            10,
6837            20,
6838            &SE3::identity(),
6839            &CovisibilityLocalBaConfig {
6840                max_neighbor_keyframes: 1,
6841                min_shared_landmarks: 1,
6842                max_boundary_keyframes: 0,
6843                min_boundary_observations: 1,
6844                min_observations_per_landmark: 2,
6845                min_active_observations: 1,
6846                ..CovisibilityLocalBaConfig::default()
6847            },
6848        )
6849        .unwrap();
6850
6851        assert_eq!(corrected.keyframe_ids, vec![20, 21]);
6852        assert!((corrected.translation_meters - 1.0).abs() < 1.0e-9);
6853        assert!(corrected.rotation_radians < 1.0e-9);
6854        for id in corrected.keyframe_ids {
6855            let pose = map.keyframes[&id].frame.pose.as_ref().unwrap();
6856            let projected = camera
6857                .project(&pose.transform_world_point(&map.landmarks[&2].position))
6858                .unwrap();
6859            assert!((projected - local_xy).norm() < 1.0e-9);
6860        }
6861        assert!(
6862            map.keyframes[&20]
6863                .frame
6864                .pose
6865                .as_ref()
6866                .unwrap()
6867                .world_to_camera
6868                .translation
6869                .norm()
6870                < 1.0e-9
6871        );
6872        assert!((map.landmarks[&2].position - Point3::new(1.0, 0.0, 5.0)).norm() < 1.0e-9);
6873    }
6874
6875    fn covariance_propagation_map() -> VisualMap {
6876        let mut map = VisualMap::new();
6877        map.landmarks
6878            .insert(1, Landmark::new(1, Point3::new(1.0, 0.0, 2.0)));
6879        map.landmark_position_covariances.insert(
6880            1,
6881            nalgebra::Matrix3::from_diagonal(&Vector3::new(1.0, 4.0, 9.0)),
6882        );
6883        let frame = Frame::new(10, 1);
6884        map.keyframes.insert(
6885            10,
6886            Keyframe {
6887                frame,
6888                observations: vec![Observation {
6889                    frame_id: 10,
6890                    landmark_id: 1,
6891                    keypoint_index: 0,
6892                    xy: Point2::new(0.0, 0.0),
6893                }],
6894            },
6895        );
6896        map
6897    }
6898
6899    #[test]
6900    fn se3_landmark_propagation_rotates_position_covariance() {
6901        let mut map = covariance_propagation_map();
6902        let correction = SE3::new(
6903            nalgebra::UnitQuaternion::from_axis_angle(
6904                &Vector3::z_axis(),
6905                std::f64::consts::FRAC_PI_2,
6906            ),
6907            Vector3::new(0.5, 0.0, 0.0),
6908        );
6909        propagate_pose_graph_corrections(&mut map, &HashMap::from([(10, correction)]));
6910        let covariance = map.landmark_position_covariances.get(&1).unwrap();
6911        let expected = nalgebra::Matrix3::from_diagonal(&Vector3::new(4.0, 1.0, 9.0));
6912        assert!((*covariance - expected).norm() < 1.0e-10);
6913    }
6914
6915    #[test]
6916    fn sim3_landmark_propagation_rotates_and_scales_position_covariance() {
6917        let mut map = covariance_propagation_map();
6918        let correction = Sim3::new(nalgebra::UnitQuaternion::identity(), Vector3::zeros(), 2.0);
6919        propagate_pose_graph_corrections_sim3(&mut map, &HashMap::from([(10, correction)]));
6920        let covariance = map.landmark_position_covariances.get(&1).unwrap();
6921        let expected = nalgebra::Matrix3::from_diagonal(&Vector3::new(4.0, 16.0, 36.0));
6922        assert!((*covariance - expected).norm() < 1.0e-10);
6923    }
6924
6925    fn verified_appearance_candidate(query_frame_id: u64) -> LoopClosureCandidate {
6926        verified_appearance_candidate_with_pose(query_frame_id, 10, SE3::identity())
6927    }
6928
6929    fn verified_appearance_candidate_with_pose(
6930        query_frame_id: u64,
6931        matched_keyframe_id: u64,
6932        relative_pose: SE3,
6933    ) -> LoopClosureCandidate {
6934        LoopClosureCandidate {
6935            query_frame_id,
6936            matched_keyframe_id,
6937            shared_landmark_count: 40,
6938            query_inlier_count: 40,
6939            keyframe_observation_count: 40,
6940            shared_landmark_ratio: 1.0,
6941            score: 10.0,
6942            geometrically_verified: true,
6943            verification: Some(LoopClosureVerification {
6944                verified: true,
6945                correspondence_count: 40,
6946                inlier_count: 40,
6947                inlier_ratio: 1.0,
6948                mean_sampson_error: 0.0,
6949                score: 10.0,
6950                failure_reason: None,
6951                relative_pose: Some(relative_pose),
6952                mean_reprojection_error_px: Some(0.0),
6953            }),
6954            pnp_query_landmark_pairs: Vec::new(),
6955        }
6956    }
6957
6958    #[test]
6959    fn pending_appearance_region_is_carried_by_projection_without_retrieval() {
6960        use nalgebra::{UnitQuaternion, Vector3};
6961
6962        let camera = Camera::pinhole(1, 640, 480, 420.0, 415.0, 320.0, 240.0);
6963        let mut map = VisualMap::new();
6964        map.cameras.insert(camera.id, camera.clone());
6965        let mut root_frame = Frame::new(10, camera.id);
6966        root_frame.pose = Some(Pose::identity());
6967        let mut root_observations = Vec::new();
6968        let mut current_frame = Frame::new(110, camera.id);
6969        let current_pose =
6970            Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::new(0.05, -0.02, 0.01));
6971        current_frame.pose = Some(current_pose.clone());
6972
6973        for index in 0..64usize {
6974            let row = index / 8;
6975            let column = index % 8;
6976            let point = Point3::new(
6977                (column as f64 - 3.5) * 0.22,
6978                (row as f64 - 3.5) * 0.18,
6979                4.0 + (index % 7) as f64 * 0.35,
6980            );
6981            let mut descriptor = vec![0.0_f32; 64];
6982            descriptor[index] = 1.0;
6983            let landmark_id = index as u64 + 1;
6984            let mut landmark = Landmark::new(landmark_id, point);
6985            landmark.descriptor = Some(descriptor.clone());
6986            let root_xy = camera.project(&point).unwrap();
6987            let observation = Observation {
6988                frame_id: root_frame.id,
6989                landmark_id,
6990                keypoint_index: index,
6991                xy: root_xy,
6992            };
6993            root_frame.keypoints.push(root_xy);
6994            root_frame.descriptors.push(descriptor.clone());
6995            root_observations.push(observation.clone());
6996            landmark.observations.push(observation);
6997            current_frame.keypoints.push(
6998                camera
6999                    .project(&current_pose.transform_world_point(&point))
7000                    .unwrap(),
7001            );
7002            current_frame.descriptors.push(descriptor);
7003            map.landmarks.insert(landmark_id, landmark);
7004        }
7005        map.keyframes.insert(
7006            root_frame.id,
7007            Keyframe {
7008                frame: root_frame,
7009                observations: root_observations,
7010            },
7011        );
7012        let mut last_frame = Frame::new(100, camera.id);
7013        last_frame.pose = Some(Pose::identity());
7014        map.keyframes.insert(
7015            last_frame.id,
7016            Keyframe {
7017                frame: last_frame,
7018                observations: Vec::new(),
7019            },
7020        );
7021        map.keyframes.insert(
7022            current_frame.id,
7023            Keyframe {
7024                frame: current_frame.clone(),
7025                observations: Vec::new(),
7026            },
7027        );
7028        let pending = AppearancePendingRegion {
7029            root_keyframe_id: 10,
7030            last_current_keyframe_id: 100,
7031            root_to_last_current: SE3::identity(),
7032            confirmation_count: 1,
7033            miss_count: 0,
7034        };
7035        let config = LoopAppearanceCandidateConfig {
7036            min_candidate_landmark_count: 30,
7037            min_projection_correspondence_count: 50,
7038            projection_search_radius_px: Some(15.0),
7039            ..LoopAppearanceCandidateConfig::default()
7040        };
7041
7042        let result = verify_pending_appearance_region_by_projection(
7043            &map,
7044            &current_frame,
7045            &camera,
7046            &config,
7047            &pending,
7048        );
7049
7050        assert!(result.attempted);
7051        assert!(result.correspondence_count >= 50);
7052        assert!(result.inlier_count >= config.pnp_verifier.min_inliers);
7053        let candidate = result.candidate.expect("projection carry should verify");
7054        assert_eq!(candidate.matched_keyframe_id, 10);
7055        assert_eq!(candidate.query_frame_id, 110);
7056        assert!(candidate.pnp_query_landmark_pairs.len() >= config.pnp_verifier.min_inliers);
7057    }
7058
7059    #[test]
7060    fn confirms_the_same_appearance_region_across_three_keyframes() {
7061        let mut map = VisualMap::new();
7062        for frame_id in [10, 100, 110, 120] {
7063            let mut frame = Frame::new(frame_id, 1);
7064            frame.pose = Some(Pose::identity());
7065            map.keyframes.insert(
7066                frame_id,
7067                Keyframe {
7068                    frame,
7069                    observations: Vec::new(),
7070                },
7071            );
7072        }
7073        let config = LoopAppearanceCandidateConfig {
7074            region_confirmation_required_keyframes: 3,
7075            ..LoopAppearanceCandidateConfig::default()
7076        };
7077        let mut pending = None;
7078
7079        let (first, waiting, confirmed) = confirm_appearance_region_across_keyframes(
7080            &map,
7081            100,
7082            vec![verified_appearance_candidate(100)],
7083            &config,
7084            &mut pending,
7085        );
7086        assert!(first.is_empty() && waiting && !confirmed);
7087        let (second, waiting, confirmed) = confirm_appearance_region_across_keyframes(
7088            &map,
7089            110,
7090            vec![verified_appearance_candidate(110)],
7091            &config,
7092            &mut pending,
7093        );
7094        assert!(second.is_empty() && waiting && !confirmed);
7095        let (third, waiting, confirmed) = confirm_appearance_region_across_keyframes(
7096            &map,
7097            120,
7098            vec![verified_appearance_candidate(120)],
7099            &config,
7100            &mut pending,
7101        );
7102        assert_eq!(third.len(), 1);
7103        assert!(!waiting && confirmed);
7104        assert!(pending.is_none());
7105    }
7106
7107    #[test]
7108    fn confirms_overlapping_region_with_nontrivial_pose_composition() {
7109        use nalgebra::{UnitQuaternion, Vector3};
7110        use visloc_core::types::Observation;
7111
7112        let pose = |x: f64| {
7113            Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::new(x, 0.0, 0.0))
7114        };
7115        let observation = |frame_id| Observation {
7116            frame_id,
7117            landmark_id: 7,
7118            keypoint_index: 0,
7119            xy: Point2::origin(),
7120        };
7121        let mut map = VisualMap::new();
7122        for (frame_id, x) in [(10, 0.0), (20, 1.0), (100, 10.0), (110, 11.0), (120, 12.0)] {
7123            let mut frame = Frame::new(frame_id, 1);
7124            frame.pose = Some(pose(x));
7125            let observations = if matches!(frame_id, 10 | 20) {
7126                vec![observation(frame_id)]
7127            } else {
7128                Vec::new()
7129            };
7130            map.keyframes.insert(
7131                frame_id,
7132                Keyframe {
7133                    frame,
7134                    observations,
7135                },
7136            );
7137        }
7138        let config = LoopAppearanceCandidateConfig {
7139            covisibility_min_shared_landmarks: 1,
7140            region_confirmation_required_keyframes: 3,
7141            ..LoopAppearanceCandidateConfig::default()
7142        };
7143        let mut pending = None;
7144
7145        let first_edge = SE3::new(UnitQuaternion::identity(), Vector3::new(10.0, 0.0, 0.0));
7146        let second_edge = SE3::new(UnitQuaternion::identity(), Vector3::new(10.0, 0.0, 0.0));
7147        let third_edge = SE3::new(UnitQuaternion::identity(), Vector3::new(12.0, 0.0, 0.0));
7148        let (first, waiting, confirmed) = confirm_appearance_region_across_keyframes(
7149            &map,
7150            100,
7151            vec![verified_appearance_candidate_with_pose(100, 10, first_edge)],
7152            &config,
7153            &mut pending,
7154        );
7155        assert!(first.is_empty() && waiting && !confirmed);
7156        let (second, waiting, confirmed) = confirm_appearance_region_across_keyframes(
7157            &map,
7158            110,
7159            vec![verified_appearance_candidate_with_pose(
7160                110,
7161                20,
7162                second_edge,
7163            )],
7164            &config,
7165            &mut pending,
7166        );
7167        assert!(second.is_empty() && waiting && !confirmed);
7168        let (third, waiting, confirmed) = confirm_appearance_region_across_keyframes(
7169            &map,
7170            120,
7171            vec![verified_appearance_candidate_with_pose(120, 10, third_edge)],
7172            &config,
7173            &mut pending,
7174        );
7175        assert_eq!(third.len(), 1);
7176        assert_eq!(third[0].matched_keyframe_id, 10);
7177        assert!(!waiting && confirmed);
7178        assert!(pending.is_none());
7179    }
7180
7181    #[test]
7182    fn recovers_scale_from_duplicate_landmark_regions() {
7183        let mut map = VisualMap::new();
7184        let mut from_frame = Frame::new(10, 1);
7185        let mut to_frame = Frame::new(20, 1);
7186        from_frame.pose = Some(Pose::identity());
7187        to_frame.pose = Some(Pose::identity());
7188        let mut from_observations = Vec::new();
7189        let mut to_observations = Vec::new();
7190        let points = [
7191            Point3::new(0.0, 0.0, 4.0),
7192            Point3::new(1.0, 0.0, 4.2),
7193            Point3::new(0.0, 1.0, 4.4),
7194            Point3::new(1.0, 1.0, 4.8),
7195            Point3::new(-0.5, 0.3, 5.0),
7196            Point3::new(0.4, -0.7, 5.3),
7197            Point3::new(1.2, 0.6, 5.6),
7198            Point3::new(-0.8, -0.4, 4.6),
7199        ];
7200        for (index, point) in points.into_iter().enumerate() {
7201            let descriptor = vec![index as f32, 1.0, -(index as f32)];
7202            from_frame.descriptors.push(descriptor.clone());
7203            to_frame.descriptors.push(descriptor.clone());
7204            let from_id = index as u64 + 1;
7205            let to_id = index as u64 + 101;
7206            let mut from_landmark = Landmark::new(from_id, point);
7207            if index % 2 == 0 {
7208                from_landmark.descriptor = Some(descriptor.clone());
7209            }
7210            let transformed = if index < 6 {
7211                point.coords * 1.7 + Vector3::new(2.0, -1.0, 0.5)
7212            } else {
7213                Vector3::new(20.0 + index as f64, -15.0, 2.0)
7214            };
7215            let mut to_landmark = Landmark::new(to_id, Point3::from(transformed));
7216            // The query-side map descriptor may be stale/aggregated; the
7217            // observing frame descriptor above must take precedence.
7218            to_landmark.descriptor = Some(vec![100.0 + index as f32, -50.0, 25.0]);
7219            map.landmarks.insert(from_id, from_landmark);
7220            map.landmarks.insert(to_id, to_landmark);
7221            from_observations.push(Observation {
7222                frame_id: 10,
7223                landmark_id: from_id,
7224                keypoint_index: index,
7225                xy: Point2::origin(),
7226            });
7227            to_observations.push(Observation {
7228                frame_id: 20,
7229                landmark_id: to_id,
7230                keypoint_index: index,
7231                xy: Point2::origin(),
7232            });
7233        }
7234        map.keyframes.insert(
7235            10,
7236            Keyframe {
7237                frame: from_frame,
7238                observations: from_observations,
7239            },
7240        );
7241        map.keyframes.insert(
7242            20,
7243            Keyframe {
7244                frame: to_frame,
7245                observations: to_observations,
7246            },
7247        );
7248
7249        let pnp_pairs: Vec<(usize, u64)> = (0..points.len())
7250            .map(|index| (index, index as u64 + 1))
7251            .collect();
7252        let scale =
7253            estimate_loop_sim3_scale_3d3d(&map, 10, 20, &pnp_pairs, &HashMap::new()).unwrap();
7254        assert!((scale - 1.7).abs() < 1.0e-9, "scale={scale}");
7255    }
7256}
7257
7258fn outlier_observation_ratio(outlier_count: usize, observation_count: usize) -> Option<f64> {
7259    if observation_count == 0 {
7260        None
7261    } else {
7262        Some(outlier_count as f64 / observation_count as f64)
7263    }
7264}
7265
7266/// Rigidly place the current covisible region at the absolute query pose
7267/// implied by an accepted loop measurement. This is the SE(3), metric-stereo
7268/// counterpart of ORB-SLAM's corrected-Sim3 welding initialization: all
7269/// selected current-region poses and landmarks receive one common world-frame
7270/// transform, preserving their internal reprojections before cross-loop
7271/// observations are fused and bundle adjustment begins.
7272#[derive(Debug, Clone, PartialEq)]
7273struct LoopWeldingRegionCorrection {
7274    keyframe_ids: Vec<u64>,
7275    translation_meters: f64,
7276    rotation_radians: f64,
7277}
7278
7279/// Re-run the essential graph after a successful local weld so the rigid
7280/// current-region correction is distributed across sequential constraints
7281/// instead of leaving a one-edge rotation/translation seam. The operation is
7282/// speculative and rolls both graph and map back if the solved map is invalid
7283/// or loses the welding window's pre-BA reprojection quality.
7284fn refine_pose_graph_after_welding(
7285    map: &mut VisualMap,
7286    graph: &mut PoseGraph,
7287    config: &PoseGraphSe3Config,
7288    gnc: Option<&gnc::GncConfig>,
7289    active_keyframe_id: u64,
7290    welding_config: &CovisibilityLocalBaConfig,
7291    max_mean_reprojection_px: f64,
7292) -> (
7293    bool,
7294    Option<f64>,
7295    Option<CovisibilityLocalBaError>,
7296    Option<f64>,
7297) {
7298    let original_map = map.clone();
7299    let original_graph = graph.clone();
7300    let mut post_config = config.clone();
7301    // Preserve the geometrically welded initialization. A second chordal seed
7302    // would discard it and reproduce the pre-welding pose-only solution.
7303    post_config.chordal_init = false;
7304    let solved = if let Some(gnc) = gnc {
7305        graph.optimize_se3_gnc(&post_config, gnc).is_ok()
7306    } else {
7307        graph.optimize_se3_iterative(&post_config).is_ok()
7308    };
7309    if !solved {
7310        *map = original_map;
7311        *graph = original_graph;
7312        return (false, None, None, None);
7313    }
7314
7315    let mut corrections = HashMap::new();
7316    for (id, new_pose) in &graph.poses {
7317        let Some(old_pose) = map
7318            .keyframes
7319            .get(id)
7320            .and_then(|keyframe| keyframe.frame.pose.as_ref())
7321        else {
7322            continue;
7323        };
7324        corrections.insert(
7325            *id,
7326            new_pose
7327                .world_to_camera
7328                .inverse()
7329                .compose(&old_pose.world_to_camera),
7330        );
7331    }
7332    for (id, new_pose) in &graph.poses {
7333        if let Some(keyframe) = map.keyframes.get_mut(id) {
7334            keyframe.frame.pose = Some(new_pose.clone());
7335        }
7336    }
7337    propagate_pose_graph_corrections(map, &corrections);
7338    // Essential-graph optimization is pose-only and can temporarily pull the
7339    // newly fused observations far off their pixels. Mirror ORB-SLAM's final
7340    // BA stage from that globally distributed initialization. Unlike the
7341    // pre-PGO seam BA, rotations are free here: the graph has already removed
7342    // the discrete region boundary that required temporary anchoring.
7343    let mut post_welding_config = welding_config.clone();
7344    post_welding_config.ba_config.max_iterations =
7345        post_welding_config.ba_config.max_iterations.max(20);
7346    // Use the same pixel scale as the welding window's default outlier gate.
7347    // A 20 px transition kept too much leverage on cross-loop residuals and
7348    // measurably rotated the short-baseline trajectory after an otherwise
7349    // successful weld.
7350    post_welding_config.ba_config.robust_kernel = RobustKernel::Huber { delta: 5.0 };
7351    let post_ba =
7352        match refine_visual_map_with_covisibility_ba(map, active_keyframe_id, &post_welding_config)
7353        {
7354            Ok(result) => result,
7355            Err(error) => {
7356                *map = original_map;
7357                *graph = original_graph;
7358                return (false, None, Some(error), None);
7359            }
7360        };
7361    for id in &post_ba.selection.optimized_keyframe_ids {
7362        if let Some(pose) = map
7363            .keyframes
7364            .get(id)
7365            .and_then(|keyframe| keyframe.frame.pose.clone())
7366        {
7367            if graph.poses.contains_key(id) {
7368                graph.poses.insert(*id, pose);
7369            }
7370        }
7371    }
7372    let mean_reprojection = mean_selected_reprojection_px(map, &post_ba.selection);
7373    let behind_camera_ratio = behind_camera_optimized_landmark_ratio(map, &post_ba.selection);
7374    let reprojection_ok = mean_reprojection
7375        .is_some_and(|error| error.is_finite() && error <= max_mean_reprojection_px + 1.0e-9);
7376    let behind_camera_ok = behind_camera_ratio.is_some_and(|ratio| ratio <= 0.01);
7377    if !reprojection_ok || !behind_camera_ok || !map.validate().is_valid() {
7378        *map = original_map;
7379        *graph = original_graph;
7380        return (false, mean_reprojection, None, behind_camera_ratio);
7381    }
7382    (true, mean_reprojection, None, behind_camera_ratio)
7383}
7384
7385fn correct_loop_welding_region(
7386    map: &mut VisualMap,
7387    matched_keyframe_id: u64,
7388    query_keyframe_id: u64,
7389    matched_to_query: &SE3,
7390    config: &CovisibilityLocalBaConfig,
7391) -> Option<LoopWeldingRegionCorrection> {
7392    if matched_keyframe_id == query_keyframe_id {
7393        return None;
7394    }
7395    let matched_pose = map
7396        .keyframes
7397        .get(&matched_keyframe_id)?
7398        .frame
7399        .pose
7400        .as_ref()?
7401        .clone();
7402    let query_pose = map
7403        .keyframes
7404        .get(&query_keyframe_id)?
7405        .frame
7406        .pose
7407        .as_ref()?
7408        .clone();
7409    let selection = select_covisibility_local_ba_window(map, query_keyframe_id, config).ok()?;
7410
7411    let desired_query_world_to_camera = matched_to_query.compose(&matched_pose.world_to_camera);
7412    let world_correction = desired_query_world_to_camera
7413        .inverse()
7414        .compose(&query_pose.world_to_camera);
7415    if !world_correction
7416        .translation
7417        .iter()
7418        .all(|value| value.is_finite())
7419    {
7420        return None;
7421    }
7422
7423    let mut corrected_keyframe_ids = selection.optimized_keyframe_ids.clone();
7424    corrected_keyframe_ids.extend(selection.fixed_keyframe_ids.iter().copied());
7425    corrected_keyframe_ids.retain(|id| *id != matched_keyframe_id);
7426    corrected_keyframe_ids.sort_unstable();
7427    corrected_keyframe_ids.dedup();
7428    if !corrected_keyframe_ids.contains(&query_keyframe_id) {
7429        return None;
7430    }
7431    let inverse_correction = world_correction.inverse();
7432    for id in &corrected_keyframe_ids {
7433        let pose = map.keyframes.get_mut(id)?.frame.pose.as_mut()?;
7434        pose.world_to_camera = pose.world_to_camera.compose(&inverse_correction);
7435    }
7436
7437    let rotation = world_correction.rotation.to_rotation_matrix().into_inner();
7438    for landmark_id in selection.landmark_ids {
7439        let landmark = map.landmarks.get_mut(&landmark_id)?;
7440        landmark.position = world_correction.transform_point(&landmark.position);
7441        if let Some(covariance) = map.landmark_position_covariances.get_mut(&landmark_id) {
7442            *covariance = rotation * *covariance * rotation.transpose();
7443        }
7444    }
7445    Some(LoopWeldingRegionCorrection {
7446        keyframe_ids: corrected_keyframe_ids,
7447        translation_meters: world_correction.translation.norm(),
7448        rotation_radians: world_correction.rotation.angle(),
7449    })
7450}
7451
7452#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
7453struct LoopObservationFusionStats {
7454    pairs_considered: usize,
7455    observations_inserted: usize,
7456    observations_reassigned: usize,
7457    pairs_skipped: usize,
7458    reprojection_rejected: usize,
7459}
7460
7461/// Persist geometrically verified appearance-loop correspondences on both
7462/// mirrored map indices. One query keypoint may describe only one landmark.
7463/// If local mapping associated it with a duplicated recent landmark, move that
7464/// single observation relation to the older loop landmark; do not delete or
7465/// geometrically merge the duplicate's other track here.
7466fn fuse_loop_observations(
7467    map: &mut VisualMap,
7468    camera: &Camera,
7469    query_keyframe_id: u64,
7470    pairs: &[(usize, u64)],
7471    max_reprojection_error_px: f64,
7472) -> LoopObservationFusionStats {
7473    let mut stats = LoopObservationFusionStats::default();
7474    for &(keypoint_index, loop_landmark_id) in pairs {
7475        stats.pairs_considered += 1;
7476        let Some(keyframe) = map.keyframes.get(&query_keyframe_id) else {
7477            stats.pairs_skipped += 1;
7478            continue;
7479        };
7480        let Some(&xy) = keyframe.frame.keypoints.get(keypoint_index) else {
7481            stats.pairs_skipped += 1;
7482            continue;
7483        };
7484        let Some(loop_landmark) = map.landmarks.get(&loop_landmark_id) else {
7485            stats.pairs_skipped += 1;
7486            continue;
7487        };
7488        let Some(query_pose) = keyframe.frame.pose.as_ref() else {
7489            stats.pairs_skipped += 1;
7490            continue;
7491        };
7492        let Some(predicted) =
7493            camera.project(&query_pose.transform_world_point(&loop_landmark.position))
7494        else {
7495            stats.pairs_skipped += 1;
7496            stats.reprojection_rejected += 1;
7497            continue;
7498        };
7499        if !max_reprojection_error_px.is_finite()
7500            || max_reprojection_error_px <= 0.0
7501            || (predicted - xy).norm() > max_reprojection_error_px
7502        {
7503            stats.pairs_skipped += 1;
7504            stats.reprojection_rejected += 1;
7505            continue;
7506        }
7507
7508        let existing = keyframe
7509            .observations
7510            .iter()
7511            .find(|observation| observation.keypoint_index == keypoint_index)
7512            .cloned();
7513        if existing
7514            .as_ref()
7515            .is_some_and(|observation| observation.landmark_id == loop_landmark_id)
7516        {
7517            continue;
7518        }
7519        // A single landmark must not acquire two different keypoints in one
7520        // frame. Such a case needs an explicit duplicate/track merge instead
7521        // of silently manufacturing a second measurement.
7522        if map.landmarks[&loop_landmark_id]
7523            .observations
7524            .iter()
7525            .any(|observation| {
7526                observation.frame_id == query_keyframe_id
7527                    && observation.keypoint_index != keypoint_index
7528            })
7529        {
7530            stats.pairs_skipped += 1;
7531            continue;
7532        }
7533
7534        let observation = Observation {
7535            frame_id: query_keyframe_id,
7536            landmark_id: loop_landmark_id,
7537            keypoint_index,
7538            xy,
7539        };
7540        let keyframe = map
7541            .keyframes
7542            .get_mut(&query_keyframe_id)
7543            .expect("query keyframe existence checked above");
7544        keyframe
7545            .observations
7546            .retain(|candidate| candidate.keypoint_index != keypoint_index);
7547        keyframe.observations.push(observation.clone());
7548
7549        if let Some(previous) = existing {
7550            if previous.landmark_id != loop_landmark_id {
7551                // The stored score described the original descriptor match.
7552                // A loop-verification reassignment is a different geometric
7553                // edge and must not inherit that frontend confidence.
7554                map.remove_observation_confidence(&previous);
7555                if let Some(previous_landmark) = map.landmarks.get_mut(&previous.landmark_id) {
7556                    previous_landmark.observations.retain(|candidate| {
7557                        !(candidate.frame_id == query_keyframe_id
7558                            && candidate.keypoint_index == keypoint_index)
7559                    });
7560                }
7561                let loop_stereo_exists = map.stereo_observations.iter().any(|stereo| {
7562                    stereo.frame_id == query_keyframe_id && stereo.landmark_id == loop_landmark_id
7563                });
7564                if loop_stereo_exists {
7565                    map.stereo_observations.retain(|stereo| {
7566                        !(stereo.frame_id == query_keyframe_id
7567                            && stereo.landmark_id == previous.landmark_id)
7568                    });
7569                } else if let Some(stereo) = map.stereo_observations.iter_mut().find(|stereo| {
7570                    stereo.frame_id == query_keyframe_id
7571                        && stereo.landmark_id == previous.landmark_id
7572                }) {
7573                    stereo.landmark_id = loop_landmark_id;
7574                }
7575                stats.observations_reassigned += 1;
7576            }
7577        }
7578        let loop_landmark = map
7579            .landmarks
7580            .get_mut(&loop_landmark_id)
7581            .expect("loop landmark existence checked above");
7582        loop_landmark.observations.retain(|candidate| {
7583            !(candidate.frame_id == query_keyframe_id && candidate.keypoint_index == keypoint_index)
7584        });
7585        loop_landmark.observations.push(observation);
7586        stats.observations_inserted += 1;
7587    }
7588    stats
7589}
7590
7591fn keyframe_from_tracking_result(frame: &Frame, tracking: &TrackingResult) -> Keyframe {
7592    let mut frame = frame.clone();
7593    frame.pose = tracking.localization.pose.clone();
7594
7595    let observations = tracking
7596        .localization
7597        .inlier_query_indices
7598        .iter()
7599        .zip(tracking.localization.inlier_landmark_ids.iter())
7600        .filter_map(|(keypoint_index, landmark_id)| {
7601            frame.keypoints.get(*keypoint_index).map(|xy| Observation {
7602                frame_id: frame.id,
7603                landmark_id: *landmark_id,
7604                keypoint_index: *keypoint_index,
7605                xy: *xy,
7606            })
7607        })
7608        .collect();
7609
7610    Keyframe {
7611        frame,
7612        observations,
7613    }
7614}
7615
7616/// Preserve learned matcher confidence after the mapper has accepted a
7617/// tracking-produced keyframe. The geometric observation remains the source of
7618/// truth; missing/invalid confidence simply leaves the observation uniformly
7619/// weighted in downstream BA.
7620fn record_tracking_observation_confidences(
7621    map: &mut VisualMap,
7622    frame_id: u64,
7623    tracking: &TrackingResult,
7624) -> usize {
7625    let accepted = tracking
7626        .localization
7627        .inlier_query_indices
7628        .iter()
7629        .copied()
7630        .zip(tracking.localization.inlier_landmark_ids.iter().copied())
7631        .zip(tracking.localization.inlier_confidences.iter().copied())
7632        .filter_map(|((keypoint_index, landmark_id), confidence)| {
7633            confidence.map(|confidence| (keypoint_index, landmark_id, confidence))
7634        })
7635        .collect::<Vec<_>>();
7636
7637    let Some(keyframe) = map.keyframes.get(&frame_id) else {
7638        return 0;
7639    };
7640    let observations = keyframe.observations.clone();
7641    let mut recorded = 0usize;
7642    for (keypoint_index, landmark_id, confidence) in accepted {
7643        let Some(observation) = observations.iter().find(|observation| {
7644            observation.keypoint_index == keypoint_index && observation.landmark_id == landmark_id
7645        }) else {
7646            continue;
7647        };
7648        if map.set_observation_confidence(observation, confidence) {
7649            recorded += 1;
7650        }
7651    }
7652    recorded
7653}
7654
7655#[cfg(test)]
7656mod observation_confidence_transfer_tests {
7657    use super::*;
7658    use nalgebra::Point2;
7659    use visloc_core::types::{LocalizationResult, LocalizationSuccess};
7660    use visloc_localization::MapProviderStats;
7661    use visloc_tracking::{TrackingEvent, TrackingState};
7662
7663    #[test]
7664    fn accepted_keyframe_keeps_frontend_inlier_confidence() {
7665        let mut frame = Frame::new(7, 1);
7666        frame.keypoints.push(Point2::new(12.0, 34.0));
7667        let localization = LocalizationResult::success(LocalizationSuccess {
7668            pose: Pose::identity(),
7669            candidate_landmark_count: 1,
7670            match_count: 1,
7671            correspondence_count: 1,
7672            inliers: vec![0],
7673            inlier_query_indices: vec![0],
7674            inlier_landmark_ids: vec![42],
7675            inlier_confidences: vec![Some(0.3)],
7676            inlier_reprojection_errors: vec![0.0],
7677            mean_reprojection_error: 0.0,
7678            median_reprojection_error: 0.0,
7679            max_reprojection_error: 0.0,
7680        });
7681        let tracking = TrackingResult {
7682            frame_id: frame.id,
7683            state: TrackingState::Tracking,
7684            event: TrackingEvent::Tracked,
7685            successive_failures: 0,
7686            pose_prior: None,
7687            used_pose_prior: false,
7688            used_external_localization_prior: false,
7689            external_localization_prior_radius: None,
7690            tracking_failure_reason: None,
7691            map_landmark_count: 1,
7692            map_stats: MapProviderStats::default(),
7693            localization,
7694            covisibility_local_map_size: None,
7695        };
7696        let keyframe = keyframe_from_tracking_result(&frame, &tracking);
7697        let observation = keyframe.observations[0].clone();
7698        let mut map = VisualMap::new();
7699        map.keyframes.insert(frame.id, keyframe);
7700
7701        assert_eq!(
7702            record_tracking_observation_confidences(&mut map, frame.id, &tracking),
7703            1
7704        );
7705        assert_eq!(map.observation_confidence(&observation), Some(0.3));
7706    }
7707}