Skip to main content

visloc_slam/
covisibility_ba.rs

1//! Covisibility-selected local bundle adjustment over an existing `VisualMap`.
2//!
3//! This is the ORB-SLAM-style local BA shape, but kept as an explicit API so it
4//! can be A/B tested against temporal-window BA without changing the online
5//! pipeline default. A caller supplies the active keyframe id; the selector
6//! pulls in high-covisibility neighbor keyframes as variables, fixed boundary
7//! keyframes that observe the same local landmarks, and the shared landmark set.
8
9use std::collections::{BTreeMap, BTreeSet};
10
11use nalgebra::Vector3;
12use visloc_core::types::{Camera, FrameId, LandmarkId, Observation, VisualMap};
13
14use crate::{
15    bundle::relative_observation_confidence_weights, BaConfig, BaError, BaGeneralStereoObservation,
16    BaObservation, BaResult, BundleAdjustment, LinearSolver, PositionPrior,
17    PositionPriorObservation, RobustKernel,
18};
19
20/// A keyframe ranked by how many selected landmarks it shares.
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub struct CovisibilityKeyframeScore {
23    pub keyframe_id: FrameId,
24    pub shared_landmark_count: usize,
25}
26
27/// Selection diagnostics for one covisibility local-BA problem.
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub struct CovisibilityLocalBaSelection {
30    /// Keyframe that seeded the local BA problem.
31    pub active_keyframe_id: FrameId,
32    /// Variable keyframes. The active keyframe is always first, followed by
33    /// high-covisibility neighbors.
34    pub optimized_keyframe_ids: Vec<FrameId>,
35    /// Fixed keyframes outside the optimized set that observe local landmarks.
36    pub fixed_keyframe_ids: Vec<FrameId>,
37    /// Landmarks included in the local BA.
38    pub landmark_ids: Vec<LandmarkId>,
39    /// Number of monocular reprojection observations added to BA.
40    pub observation_count: usize,
41    /// Ranked covisible candidates before the neighbor cap is applied.
42    pub neighbor_candidates: Vec<CovisibilityKeyframeScore>,
43    /// Ranked boundary candidates before the boundary cap is applied.
44    pub boundary_candidates: Vec<CovisibilityKeyframeScore>,
45    /// `true` when the selector had to retry boundary-keyframe selection with
46    /// [`CovisibilityLocalBaConfig::fallback_min_boundary_observations`] after
47    /// the primary boundary threshold produced no eligible local landmarks.
48    pub boundary_fallback_used: bool,
49}
50
51impl CovisibilityLocalBaSelection {
52    fn all_keyframe_ids(&self) -> Vec<FrameId> {
53        let mut ids = self.optimized_keyframe_ids.clone();
54        ids.extend(self.fixed_keyframe_ids.iter().copied());
55        ids.sort_unstable();
56        ids.dedup();
57        ids
58    }
59}
60
61/// Configuration for [`refine_visual_map_with_covisibility_ba`].
62#[derive(Debug, Clone, PartialEq)]
63pub struct CovisibilityLocalBaConfig {
64    /// Maximum number of variable neighbor keyframes, excluding the active
65    /// keyframe. Set to `0` for active-only pose/landmark refinement.
66    pub max_neighbor_keyframes: usize,
67    /// Minimum shared landmarks for a keyframe to become a variable neighbor.
68    pub min_shared_landmarks: usize,
69    /// Maximum fixed boundary keyframes. These keyframes anchor local map scale
70    /// and pose gauge while their poses stay unchanged.
71    pub max_boundary_keyframes: usize,
72    /// Minimum observations of local landmarks for a keyframe to become a fixed
73    /// boundary keyframe.
74    pub min_boundary_observations: usize,
75    /// Optional lower boundary-keyframe threshold used only when the primary
76    /// boundary threshold produces no local landmarks. This is an A/B lever for
77    /// weak covisibility windows; `None` preserves the strict single-pass
78    /// selector.
79    pub fallback_min_boundary_observations: Option<usize>,
80    /// Minimum number of selected-keyframe observations a landmark needs before
81    /// it contributes to BA. `2` rejects single-view points.
82    pub min_observations_per_landmark: usize,
83    /// Minimum number of selected local-landmark observations required on the
84    /// active keyframe before BA runs. This avoids optimizing a newly promoted
85    /// but weak active keyframe that does not actually constrain the local
86    /// problem.
87    pub min_active_observations: usize,
88    /// Optional guard for large optimized windows with too little fixed
89    /// boundary support. When `Some(n)`, windows with at least `n` optimized
90    /// keyframes must also have at least
91    /// [`Self::boundary_support_min_fixed_keyframes`] fixed boundary keyframes.
92    pub boundary_support_min_optimized_keyframes: Option<usize>,
93    /// Fixed-boundary keyframe floor used with
94    /// [`Self::boundary_support_min_optimized_keyframes`].
95    pub boundary_support_min_fixed_keyframes: usize,
96    /// Optional runtime cap on local landmarks. Landmarks are ranked by how many
97    /// optimized and total local keyframes observe them.
98    pub max_landmarks: Option<usize>,
99    /// Optional reprojection threshold for post-BA outlier diagnostics.
100    pub outlier_reprojection_threshold_px: Option<f64>,
101    /// When `true`, observations above
102    /// [`Self::outlier_reprojection_threshold_px`] are removed from both
103    /// keyframes and landmarks after a successful BA.
104    pub remove_outlier_observations: bool,
105    /// Replace a monocular left factor with the calibrated 4D
106    /// `(u_l,v_l,u_r,v_r)` factor when a matching right-image sidecar exists.
107    /// `false` preserves the historical local-BA objective.
108    pub use_general_stereo_observations: bool,
109    /// Optional pre-solve right-image reprojection gate for general stereo
110    /// sidecars. Stale or incorrectly associated right measurements fall back
111    /// to the ordinary monocular factor instead of entering BA.
112    pub general_stereo_max_initial_right_reprojection_error_px: Option<f64>,
113    /// Consume optional frontend matcher confidence stored on map
114    /// observations. Disable for the classical-only side of a weighting
115    /// ablation; observations without a score always remain weight `1`.
116    pub use_observation_confidence_weights: bool,
117    /// Optional gauge/global-anchoring prior weight. When `Some(w)` with a
118    /// finite `w > 0`, every optimized (non-fixed) keyframe in the window gets
119    /// an absolute camera-center prior pulling it toward its pre-BA (tracking)
120    /// estimate with per-axis weight `w` (cost `Σ w·‖C − C_pre‖²`). This pins
121    /// the local window's gauge to the global map so a locally-consistent solve
122    /// cannot drift the whole window — the EuRoC MH_05 covisibility-BA failure
123    /// mode. `None` (default) leaves the solve anchored only by its fixed
124    /// boundary keyframes (legacy behavior).
125    pub pose_anchor_prior_weight: Option<f64>,
126    /// Underlying Schur-complement BA configuration.
127    pub ba_config: BaConfig,
128}
129
130impl Default for CovisibilityLocalBaConfig {
131    fn default() -> Self {
132        Self {
133            max_neighbor_keyframes: 10,
134            min_shared_landmarks: 15,
135            max_boundary_keyframes: 10,
136            min_boundary_observations: 5,
137            fallback_min_boundary_observations: None,
138            min_observations_per_landmark: 2,
139            min_active_observations: 1,
140            boundary_support_min_optimized_keyframes: None,
141            boundary_support_min_fixed_keyframes: 0,
142            max_landmarks: None,
143            outlier_reprojection_threshold_px: Some(5.0),
144            remove_outlier_observations: false,
145            use_general_stereo_observations: false,
146            general_stereo_max_initial_right_reprojection_error_px: Some(5.0),
147            use_observation_confidence_weights: false,
148            pose_anchor_prior_weight: None,
149            ba_config: BaConfig {
150                max_iterations: 12,
151                robust_kernel: RobustKernel::Huber { delta: 3.0 },
152                linear_solver: LinearSolver::Sparse,
153                ..BaConfig::default()
154            },
155        }
156    }
157}
158
159/// Result of one covisibility local-BA solve.
160#[derive(Debug, Clone, PartialEq)]
161pub struct CovisibilityLocalBaResult {
162    pub selection: CovisibilityLocalBaSelection,
163    pub ba_result: BaResult,
164    pub mean_reprojection_before_px: f64,
165    pub mean_reprojection_after_px: f64,
166    /// Largest camera-centre displacement applied to an optimized keyframe.
167    pub max_pose_translation_correction_m: f64,
168    /// Largest world-to-camera rotation change applied to an optimized keyframe.
169    pub max_pose_rotation_correction_rad: f64,
170    pub updated_keyframe_count: usize,
171    pub updated_landmark_count: usize,
172    pub outlier_observation_count: usize,
173    pub removed_observation_count: usize,
174}
175
176#[derive(Debug, Clone, PartialEq)]
177pub enum CovisibilityLocalBaError {
178    ActiveKeyframeMissing(FrameId),
179    MissingPose(FrameId),
180    MissingCamera(FrameId),
181    UnsupportedCameraModel,
182    NoReferenceLandmarks(FrameId),
183    NoLocalLandmarks,
184    NoObservations,
185    InsufficientActiveObservations {
186        keyframe_id: FrameId,
187        observation_count: usize,
188        min_observations: usize,
189        boundary_fallback_used: bool,
190    },
191    InsufficientBoundaryKeyframes {
192        optimized_keyframe_count: usize,
193        fixed_keyframe_count: usize,
194        min_optimized_keyframes: usize,
195        min_fixed_keyframes: usize,
196        boundary_fallback_used: bool,
197    },
198    QualityGateRejected {
199        outlier_observation_count: usize,
200        observation_count: usize,
201        max_outlier_observation_ratio: f64,
202    },
203    /// Write-back rejected because too large a fraction of the solved
204    /// optimized landmarks landed behind (or on) an observing optimized
205    /// camera. Signals a degenerate/under-constrained solve; see
206    /// [`behind_camera_optimized_landmark_ratio`].
207    BehindCameraGateRejected {
208        behind_camera_landmark_ratio: f64,
209        max_behind_camera_landmark_ratio: f64,
210    },
211    /// Write-back rejected because the selected window did not carry enough
212    /// fixed boundary keyframes relative to its optimized keyframes; see
213    /// [`fixed_to_optimized_ratio_satisfied`].
214    FixedSupportRatioRejected {
215        optimized_keyframe_count: usize,
216        fixed_keyframe_count: usize,
217        required_fixed_keyframes: usize,
218        min_fixed_to_optimized_ratio: f64,
219    },
220    /// Write-back rejected because the solved keyframe poses moved farther
221    /// than the configured transactional safety bounds.
222    PoseCorrectionGateRejected {
223        translation_correction_m: f64,
224        rotation_correction_rad: f64,
225        max_translation_correction_m: Option<f64>,
226        max_rotation_correction_rad: Option<f64>,
227    },
228    Ba(BaError),
229}
230
231impl std::fmt::Display for CovisibilityLocalBaError {
232    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
233        match self {
234            Self::ActiveKeyframeMissing(id) => write!(f, "active keyframe {id} is missing"),
235            Self::MissingPose(id) => write!(f, "keyframe {id} has no pose"),
236            Self::MissingCamera(id) => write!(f, "camera for keyframe {id} is missing"),
237            Self::UnsupportedCameraModel => write!(f, "camera model is not supported by BA"),
238            Self::NoReferenceLandmarks(id) => {
239                write!(f, "active keyframe {id} observes no known landmarks")
240            }
241            Self::NoLocalLandmarks => write!(f, "covisibility selection produced no landmarks"),
242            Self::NoObservations => write!(f, "covisibility selection produced no observations"),
243            Self::InsufficientActiveObservations {
244                keyframe_id,
245                observation_count,
246                min_observations,
247                ..
248            } => write!(
249                f,
250                "active keyframe {keyframe_id} has {observation_count} selected observations, below required {min_observations}"
251            ),
252            Self::InsufficientBoundaryKeyframes {
253                optimized_keyframe_count,
254                fixed_keyframe_count,
255                min_optimized_keyframes,
256                min_fixed_keyframes,
257                ..
258            } => write!(
259                f,
260                "covisibility local BA selected {optimized_keyframe_count} optimized keyframes but only {fixed_keyframe_count} fixed boundary keyframes; at least {min_fixed_keyframes} are required once optimized keyframes reach {min_optimized_keyframes}"
261            ),
262            Self::QualityGateRejected {
263                outlier_observation_count,
264                observation_count,
265                max_outlier_observation_ratio,
266            } => write!(
267                f,
268                "covisibility local BA rejected by quality gate: {outlier_observation_count}/{observation_count} outlier observations exceeds ratio {max_outlier_observation_ratio}"
269            ),
270            Self::BehindCameraGateRejected {
271                behind_camera_landmark_ratio,
272                max_behind_camera_landmark_ratio,
273            } => write!(
274                f,
275                "covisibility local BA rejected by behind-camera gate: {behind_camera_landmark_ratio} behind-camera landmark ratio exceeds max {max_behind_camera_landmark_ratio}"
276            ),
277            Self::FixedSupportRatioRejected {
278                optimized_keyframe_count,
279                fixed_keyframe_count,
280                required_fixed_keyframes,
281                min_fixed_to_optimized_ratio,
282            } => write!(
283                f,
284                "covisibility local BA rejected by fixed-support ratio gate: {fixed_keyframe_count} fixed boundary keyframes below required {required_fixed_keyframes} for {optimized_keyframe_count} optimized keyframes at ratio {min_fixed_to_optimized_ratio}"
285            ),
286            Self::PoseCorrectionGateRejected {
287                translation_correction_m,
288                rotation_correction_rad,
289                max_translation_correction_m,
290                max_rotation_correction_rad,
291            } => write!(
292                f,
293                "covisibility local BA rejected by pose-correction gate: translation {translation_correction_m} m (max {max_translation_correction_m:?}), rotation {rotation_correction_rad} rad (max {max_rotation_correction_rad:?})"
294            ),
295            Self::Ba(err) => write!(f, "bundle adjustment failed: {err}"),
296        }
297    }
298}
299
300impl std::error::Error for CovisibilityLocalBaError {}
301
302impl From<BaError> for CovisibilityLocalBaError {
303    fn from(value: BaError) -> Self {
304        Self::Ba(value)
305    }
306}
307
308#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
309struct ObservationKey {
310    frame_id: FrameId,
311    landmark_id: LandmarkId,
312    keypoint_index: usize,
313}
314
315#[derive(Debug, Clone, Copy)]
316struct LandmarkScore {
317    landmark_id: LandmarkId,
318    optimized_observation_count: usize,
319    total_observation_count: usize,
320}
321
322#[derive(Debug)]
323struct LocalLandmarkSelection {
324    boundary_candidates: Vec<CovisibilityKeyframeScore>,
325    fixed_keyframe_ids: Vec<FrameId>,
326    ba_keyframe_ids: Vec<FrameId>,
327    landmark_ids: Vec<LandmarkId>,
328}
329
330struct LocalLandmarkSelectionInput<'a> {
331    map: &'a VisualMap,
332    active_keyframe_id: FrameId,
333    camera_id: u64,
334    seed_landmarks: &'a BTreeSet<LandmarkId>,
335    optimized_keyframe_ids: &'a [FrameId],
336    optimized_set: &'a BTreeSet<FrameId>,
337    config: &'a CovisibilityLocalBaConfig,
338    min_boundary_observations: usize,
339}
340
341/// Select the covisibility local-BA window without running the optimizer.
342pub fn select_covisibility_local_ba_window(
343    map: &VisualMap,
344    active_keyframe_id: FrameId,
345    config: &CovisibilityLocalBaConfig,
346) -> Result<CovisibilityLocalBaSelection, CovisibilityLocalBaError> {
347    select_covisibility_local_ba_window_with_neighbor_allowlist(
348        map,
349        active_keyframe_id,
350        config,
351        None,
352    )
353}
354
355/// Select a local-BA window while restricting variable neighbor keyframes to
356/// an upstream active-factor set. Fixed boundary anchors remain unrestricted.
357pub fn select_covisibility_local_ba_window_with_neighbor_allowlist(
358    map: &VisualMap,
359    active_keyframe_id: FrameId,
360    config: &CovisibilityLocalBaConfig,
361    neighbor_allowlist: Option<&BTreeSet<FrameId>>,
362) -> Result<CovisibilityLocalBaSelection, CovisibilityLocalBaError> {
363    let active_kf = map.keyframes.get(&active_keyframe_id).ok_or(
364        CovisibilityLocalBaError::ActiveKeyframeMissing(active_keyframe_id),
365    )?;
366    if active_kf.frame.pose.is_none() {
367        return Err(CovisibilityLocalBaError::MissingPose(active_keyframe_id));
368    }
369    let camera = map
370        .cameras
371        .get(&active_kf.frame.camera_id)
372        .ok_or(CovisibilityLocalBaError::MissingCamera(active_keyframe_id))?;
373    if camera.intrinsics().is_none() {
374        return Err(CovisibilityLocalBaError::UnsupportedCameraModel);
375    }
376
377    let reference_landmarks = observed_landmark_set(&active_kf.observations, map);
378    if reference_landmarks.is_empty() {
379        return Err(CovisibilityLocalBaError::NoReferenceLandmarks(
380            active_keyframe_id,
381        ));
382    }
383
384    let mut neighbor_candidates = rank_keyframes_by_shared_landmarks(
385        map,
386        active_keyframe_id,
387        active_kf.frame.camera_id,
388        &reference_landmarks,
389        config.min_shared_landmarks,
390        None,
391    );
392    if let Some(allowlist) = neighbor_allowlist {
393        neighbor_candidates.retain(|candidate| allowlist.contains(&candidate.keyframe_id));
394    }
395    let mut neighbor_ids: Vec<FrameId> = neighbor_candidates
396        .iter()
397        .take(config.max_neighbor_keyframes)
398        .map(|score| score.keyframe_id)
399        .collect();
400    neighbor_ids.sort_unstable();
401
402    let mut optimized_keyframe_ids = Vec::with_capacity(neighbor_ids.len() + 1);
403    optimized_keyframe_ids.push(active_keyframe_id);
404    optimized_keyframe_ids.extend(neighbor_ids);
405    optimized_keyframe_ids.dedup();
406    let optimized_set: BTreeSet<FrameId> = optimized_keyframe_ids.iter().copied().collect();
407
408    let seed_landmarks = union_observed_landmarks(map, &optimized_keyframe_ids);
409    if seed_landmarks.is_empty() {
410        return Err(CovisibilityLocalBaError::NoLocalLandmarks);
411    }
412
413    let mut local_selection =
414        select_local_landmarks_with_boundary_threshold(LocalLandmarkSelectionInput {
415            map,
416            active_keyframe_id,
417            camera_id: active_kf.frame.camera_id,
418            seed_landmarks: &seed_landmarks,
419            optimized_keyframe_ids: &optimized_keyframe_ids,
420            optimized_set: &optimized_set,
421            config,
422            min_boundary_observations: config.min_boundary_observations,
423        });
424    let mut boundary_fallback_used = false;
425    if local_selection.landmark_ids.is_empty() {
426        if let Some(fallback_min) = config.fallback_min_boundary_observations {
427            let fallback_min = fallback_min.max(1);
428            if fallback_min < config.min_boundary_observations {
429                let fallback_selection =
430                    select_local_landmarks_with_boundary_threshold(LocalLandmarkSelectionInput {
431                        map,
432                        active_keyframe_id,
433                        camera_id: active_kf.frame.camera_id,
434                        seed_landmarks: &seed_landmarks,
435                        optimized_keyframe_ids: &optimized_keyframe_ids,
436                        optimized_set: &optimized_set,
437                        config,
438                        min_boundary_observations: fallback_min,
439                    });
440                if !fallback_selection.landmark_ids.is_empty() {
441                    local_selection = fallback_selection;
442                    boundary_fallback_used = true;
443                }
444            }
445        }
446    }
447    if local_selection.landmark_ids.is_empty() {
448        return Err(CovisibilityLocalBaError::NoLocalLandmarks);
449    }
450    if let Some(min_optimized) = config.boundary_support_min_optimized_keyframes {
451        let min_fixed = config.boundary_support_min_fixed_keyframes;
452        if min_fixed > 0
453            && optimized_keyframe_ids.len() >= min_optimized.max(1)
454            && local_selection.fixed_keyframe_ids.len() < min_fixed
455        {
456            return Err(CovisibilityLocalBaError::InsufficientBoundaryKeyframes {
457                optimized_keyframe_count: optimized_keyframe_ids.len(),
458                fixed_keyframe_count: local_selection.fixed_keyframe_ids.len(),
459                min_optimized_keyframes: min_optimized.max(1),
460                min_fixed_keyframes: min_fixed,
461                boundary_fallback_used,
462            });
463        }
464    }
465
466    let landmark_set: BTreeSet<LandmarkId> = local_selection.landmark_ids.iter().copied().collect();
467    let observation_count =
468        count_selected_observations(map, &local_selection.ba_keyframe_ids, &landmark_set);
469    if observation_count == 0 {
470        return Err(CovisibilityLocalBaError::NoObservations);
471    }
472    let active_observation_count =
473        count_selected_observations(map, &[active_keyframe_id], &landmark_set);
474    if active_observation_count < config.min_active_observations {
475        return Err(CovisibilityLocalBaError::InsufficientActiveObservations {
476            keyframe_id: active_keyframe_id,
477            observation_count: active_observation_count,
478            min_observations: config.min_active_observations,
479            boundary_fallback_used,
480        });
481    }
482
483    // Keep diagnostics deterministic even if caller maps came from HashMaps.
484    neighbor_candidates.sort_by(score_order);
485    local_selection.boundary_candidates.sort_by(score_order);
486
487    Ok(CovisibilityLocalBaSelection {
488        active_keyframe_id,
489        optimized_keyframe_ids,
490        fixed_keyframe_ids: local_selection.fixed_keyframe_ids,
491        landmark_ids: local_selection.landmark_ids,
492        observation_count,
493        neighbor_candidates,
494        boundary_candidates: local_selection.boundary_candidates,
495        boundary_fallback_used,
496    })
497}
498
499/// Run covisibility-selected local BA and write refined poses/landmarks back to
500/// `map`.
501pub fn refine_visual_map_with_covisibility_ba(
502    map: &mut VisualMap,
503    active_keyframe_id: FrameId,
504    config: &CovisibilityLocalBaConfig,
505) -> Result<CovisibilityLocalBaResult, CovisibilityLocalBaError> {
506    refine_visual_map_with_covisibility_ba_and_neighbor_allowlist(
507        map,
508        active_keyframe_id,
509        config,
510        None,
511    )
512}
513
514/// Run covisibility BA with variable neighbors admitted by the active sparse
515/// factor graph. Boundary anchors outside the allowlist still constrain the
516/// solve and therefore preserve the local/global gauge relationship.
517pub fn refine_visual_map_with_covisibility_ba_and_neighbor_allowlist(
518    map: &mut VisualMap,
519    active_keyframe_id: FrameId,
520    config: &CovisibilityLocalBaConfig,
521    neighbor_allowlist: Option<&BTreeSet<FrameId>>,
522) -> Result<CovisibilityLocalBaResult, CovisibilityLocalBaError> {
523    let selection = select_covisibility_local_ba_window_with_neighbor_allowlist(
524        map,
525        active_keyframe_id,
526        config,
527        neighbor_allowlist,
528    )?;
529    let active_camera = map
530        .keyframes
531        .get(&selection.active_keyframe_id)
532        .ok_or(CovisibilityLocalBaError::ActiveKeyframeMissing(
533            selection.active_keyframe_id,
534        ))?
535        .frame
536        .camera_id;
537    let camera = map
538        .cameras
539        .get(&active_camera)
540        .ok_or(CovisibilityLocalBaError::MissingCamera(
541            selection.active_keyframe_id,
542        ))?
543        .clone();
544
545    let (mut ba, observation_weights) = build_ba_from_selection(map, &camera, &selection, config)?;
546    let mean_reprojection_before_px = mean_reprojection_px(&ba);
547    // `optimize_honoring_matrix_free` is a no-op dispatch unless
548    // `ba_config.matrix_free_ba` (or its environment escape hatch) is set; the
549    // default local-BA solve is unchanged. The matrix-free operator rejects the
550    // weighted objective and non-visual states, so it falls back to the
551    // ordinary solve there.
552    let ba_result =
553        ba.optimize_honoring_matrix_free(&config.ba_config, observation_weights.as_deref())?;
554    let mean_reprojection_after_px = mean_reprojection_px(&ba);
555    let mut max_pose_translation_correction_m = 0.0_f64;
556    let mut max_pose_rotation_correction_rad = 0.0_f64;
557    for keyframe_id in &selection.optimized_keyframe_ids {
558        let (Some(before), Some(after)) = (
559            map.keyframes
560                .get(keyframe_id)
561                .and_then(|keyframe| keyframe.frame.pose.as_ref()),
562            ba.poses.get(keyframe_id),
563        ) else {
564            continue;
565        };
566        max_pose_translation_correction_m = max_pose_translation_correction_m
567            .max((after.camera_center_world() - before.camera_center_world()).norm());
568        let rotation_delta =
569            before.world_to_camera.rotation.inverse() * after.world_to_camera.rotation;
570        max_pose_rotation_correction_rad =
571            max_pose_rotation_correction_rad.max(rotation_delta.angle());
572    }
573
574    let mut updated_keyframe_count = 0usize;
575    for keyframe_id in &selection.optimized_keyframe_ids {
576        if ba.fixed_poses.contains(keyframe_id) {
577            continue;
578        }
579        let Some(refined_pose) = ba.poses.get(keyframe_id).cloned() else {
580            continue;
581        };
582        if let Some(keyframe) = map.keyframes.get_mut(keyframe_id) {
583            keyframe.frame.pose = Some(refined_pose);
584            updated_keyframe_count += 1;
585        }
586    }
587
588    let mut updated_landmark_count = 0usize;
589    for landmark_id in &selection.landmark_ids {
590        if ba.fixed_landmarks.contains(landmark_id) {
591            continue;
592        }
593        let Some(refined_position) = ba.landmarks.get(landmark_id).copied() else {
594            continue;
595        };
596        if let Some(landmark) = map.landmarks.get_mut(landmark_id) {
597            landmark.position = refined_position;
598            // The stored stereo covariance was linearized at the seed point.
599            // Until BA marginal covariance recovery is wired here, dropping a
600            // stale matrix is safer than using it with a moved landmark.
601            map.landmark_position_covariances.remove(landmark_id);
602            updated_landmark_count += 1;
603        }
604    }
605
606    let outlier_keys = match config.outlier_reprojection_threshold_px {
607        Some(threshold) if threshold.is_finite() && threshold > 0.0 => selected_outlier_keys(
608            map,
609            &camera,
610            &selection,
611            threshold,
612            config.use_general_stereo_observations,
613        ),
614        _ => BTreeSet::new(),
615    };
616    let outlier_observation_count = outlier_keys.len();
617    let removed_observation_count = if config.remove_outlier_observations {
618        remove_observations(map, &outlier_keys)
619    } else {
620        0
621    };
622
623    Ok(CovisibilityLocalBaResult {
624        selection,
625        ba_result,
626        mean_reprojection_before_px,
627        mean_reprojection_after_px,
628        max_pose_translation_correction_m,
629        max_pose_rotation_correction_rad,
630        updated_keyframe_count,
631        updated_landmark_count,
632        outlier_observation_count,
633        removed_observation_count,
634    })
635}
636
637fn build_ba_from_selection(
638    map: &VisualMap,
639    camera: &Camera,
640    selection: &CovisibilityLocalBaSelection,
641    config: &CovisibilityLocalBaConfig,
642) -> Result<(BundleAdjustment, Option<Vec<f64>>), CovisibilityLocalBaError> {
643    let mut ba = BundleAdjustment::new(camera.clone());
644    let mut mono_confidences = Vec::new();
645    let mut general_stereo_confidences = Vec::new();
646
647    for keyframe_id in &selection.optimized_keyframe_ids {
648        let keyframe = map.keyframes.get(keyframe_id).ok_or(
649            CovisibilityLocalBaError::ActiveKeyframeMissing(*keyframe_id),
650        )?;
651        let pose = keyframe
652            .frame
653            .pose
654            .clone()
655            .ok_or(CovisibilityLocalBaError::MissingPose(*keyframe_id))?;
656        ba.add_pose(*keyframe_id, pose);
657    }
658
659    for keyframe_id in &selection.fixed_keyframe_ids {
660        let Some(keyframe) = map.keyframes.get(keyframe_id) else {
661            continue;
662        };
663        let Some(pose) = keyframe.frame.pose.clone() else {
664            continue;
665        };
666        ba.add_pose(*keyframe_id, pose);
667        ba.fix_pose(*keyframe_id);
668    }
669
670    let no_boundary_gauge = selection.fixed_keyframe_ids.is_empty();
671    if no_boundary_gauge {
672        if let Some(anchor_id) = selection.optimized_keyframe_ids.first() {
673            ba.fix_pose(*anchor_id);
674        }
675    }
676
677    for landmark_id in &selection.landmark_ids {
678        let Some(landmark) = map.landmarks.get(landmark_id) else {
679            continue;
680        };
681        ba.add_landmark(*landmark_id, landmark.position);
682    }
683    if no_boundary_gauge {
684        if let Some(anchor_landmark) = selection.landmark_ids.first() {
685            ba.fix_landmark(*anchor_landmark);
686        }
687    }
688
689    let landmark_set: BTreeSet<LandmarkId> = selection.landmark_ids.iter().copied().collect();
690    for keyframe_id in selection.all_keyframe_ids() {
691        let Some(keyframe) = map.keyframes.get(&keyframe_id) else {
692            continue;
693        };
694        for obs in &keyframe.observations {
695            if !landmark_set.contains(&obs.landmark_id) {
696                continue;
697            }
698            if ba.poses.contains_key(&obs.frame_id) && ba.landmarks.contains_key(&obs.landmark_id) {
699                let stereo = config
700                    .use_general_stereo_observations
701                    .then(|| {
702                        map.stereo_observations
703                            .iter()
704                            .find(|stereo| {
705                                stereo.frame_id == obs.frame_id
706                                    && stereo.landmark_id == obs.landmark_id
707                            })
708                            .and_then(|stereo| {
709                                map.cameras
710                                    .get(&stereo.right_camera_id)
711                                    .map(|camera| (stereo, camera))
712                            })
713                            .filter(|(stereo, right_camera)| {
714                                let Some(max_error) =
715                                    config.general_stereo_max_initial_right_reprojection_error_px
716                                else {
717                                    return true;
718                                };
719                                if !max_error.is_finite() || max_error <= 0.0 {
720                                    return false;
721                                }
722                                let Some(pose) = ba.poses.get(&obs.frame_id) else {
723                                    return false;
724                                };
725                                let Some(point_world) = ba.landmarks.get(&obs.landmark_id) else {
726                                    return false;
727                                };
728                                let point_left = pose.transform_world_point(point_world);
729                                right_camera
730                                    .project(&stereo.left_to_right.transform_point(&point_left))
731                                    .is_some_and(|predicted| {
732                                        (predicted - stereo.xy_right).norm() <= max_error
733                                    })
734                            })
735                    })
736                    .flatten();
737                if let Some((stereo, right_camera)) = stereo {
738                    ba.add_general_stereo_observation(BaGeneralStereoObservation {
739                        keyframe_id: obs.frame_id,
740                        landmark_id: obs.landmark_id,
741                        xy_left: obs.xy,
742                        xy_right: stereo.xy_right,
743                        right_camera: right_camera.clone(),
744                        left_to_right: stereo.left_to_right.clone(),
745                    });
746                    let confidence = config
747                        .use_observation_confidence_weights
748                        .then(|| map.observation_confidence(obs))
749                        .flatten();
750                    general_stereo_confidences.push(confidence);
751                } else {
752                    ba.add_observation(BaObservation {
753                        keyframe_id: obs.frame_id,
754                        landmark_id: obs.landmark_id,
755                        xy: obs.xy,
756                    });
757                    let confidence = config
758                        .use_observation_confidence_weights
759                        .then(|| map.observation_confidence(obs))
760                        .flatten();
761                    mono_confidences.push(confidence);
762                }
763            }
764        }
765    }
766
767    if let Some(weight) = config.pose_anchor_prior_weight {
768        if weight.is_finite() && weight > 0.0 {
769            let mut prior = PositionPrior::new();
770            for keyframe_id in &selection.optimized_keyframe_ids {
771                if ba.fixed_poses.contains(keyframe_id) {
772                    continue;
773                }
774                let Some(pose) = ba.poses.get(keyframe_id) else {
775                    continue;
776                };
777                prior.push(PositionPriorObservation {
778                    keyframe_id: *keyframe_id,
779                    camera_center_world: pose.camera_center_world(),
780                    axis_weights: Vector3::new(weight, weight, weight),
781                });
782            }
783            if !prior.observations.is_empty() {
784                ba.set_position_prior(prior);
785            }
786        }
787    }
788
789    let observation_weights = relative_observation_confidence_weights(
790        mono_confidences
791            .into_iter()
792            .chain(general_stereo_confidences),
793    );
794    Ok((ba, observation_weights))
795}
796
797fn observed_landmark_set(observations: &[Observation], map: &VisualMap) -> BTreeSet<LandmarkId> {
798    observations
799        .iter()
800        .map(|obs| obs.landmark_id)
801        .filter(|landmark_id| map.landmarks.contains_key(landmark_id))
802        .collect()
803}
804
805fn union_observed_landmarks(map: &VisualMap, keyframe_ids: &[FrameId]) -> BTreeSet<LandmarkId> {
806    let mut out = BTreeSet::new();
807    for keyframe_id in keyframe_ids {
808        let Some(keyframe) = map.keyframes.get(keyframe_id) else {
809            continue;
810        };
811        for obs in &keyframe.observations {
812            if map.landmarks.contains_key(&obs.landmark_id) {
813                out.insert(obs.landmark_id);
814            }
815        }
816    }
817    out
818}
819
820fn select_local_landmarks_with_boundary_threshold(
821    input: LocalLandmarkSelectionInput<'_>,
822) -> LocalLandmarkSelection {
823    let boundary_candidates = rank_keyframes_by_shared_landmarks(
824        input.map,
825        input.active_keyframe_id,
826        input.camera_id,
827        input.seed_landmarks,
828        input.min_boundary_observations.max(1),
829        Some(input.optimized_set),
830    );
831    let fixed_keyframe_ids: Vec<FrameId> = boundary_candidates
832        .iter()
833        .take(input.config.max_boundary_keyframes)
834        .map(|score| score.keyframe_id)
835        .collect();
836
837    let mut ba_keyframe_ids = input.optimized_keyframe_ids.to_vec();
838    ba_keyframe_ids.extend(fixed_keyframe_ids.iter().copied());
839    ba_keyframe_ids.sort_unstable();
840    ba_keyframe_ids.dedup();
841
842    let mut landmark_scores =
843        score_local_landmarks(input.map, input.optimized_set, &ba_keyframe_ids);
844    landmark_scores.retain(|score| {
845        score.optimized_observation_count > 0
846            && score.total_observation_count >= input.config.min_observations_per_landmark
847            && input.map.landmarks.contains_key(&score.landmark_id)
848    });
849    landmark_scores.sort_by(|a, b| {
850        b.optimized_observation_count
851            .cmp(&a.optimized_observation_count)
852            .then_with(|| b.total_observation_count.cmp(&a.total_observation_count))
853            .then_with(|| a.landmark_id.cmp(&b.landmark_id))
854    });
855    if let Some(max_landmarks) = input.config.max_landmarks {
856        landmark_scores.truncate(max_landmarks);
857    }
858    let mut landmark_ids: Vec<LandmarkId> = landmark_scores
859        .iter()
860        .map(|score| score.landmark_id)
861        .collect();
862    landmark_ids.sort_unstable();
863
864    LocalLandmarkSelection {
865        boundary_candidates,
866        fixed_keyframe_ids,
867        ba_keyframe_ids,
868        landmark_ids,
869    }
870}
871
872fn rank_keyframes_by_shared_landmarks(
873    map: &VisualMap,
874    active_keyframe_id: FrameId,
875    camera_id: u64,
876    landmarks: &BTreeSet<LandmarkId>,
877    min_count: usize,
878    excluded: Option<&BTreeSet<FrameId>>,
879) -> Vec<CovisibilityKeyframeScore> {
880    let mut scores = Vec::new();
881    let mut keyframe_ids: Vec<FrameId> = map.keyframes.keys().copied().collect();
882    keyframe_ids.sort_unstable();
883    for keyframe_id in keyframe_ids {
884        if keyframe_id == active_keyframe_id {
885            continue;
886        }
887        if excluded.is_some_and(|set| set.contains(&keyframe_id)) {
888            continue;
889        }
890        let Some(keyframe) = map.keyframes.get(&keyframe_id) else {
891            continue;
892        };
893        if keyframe.frame.camera_id != camera_id || keyframe.frame.pose.is_none() {
894            continue;
895        }
896        let count = keyframe
897            .observations
898            .iter()
899            .map(|obs| obs.landmark_id)
900            .collect::<BTreeSet<_>>()
901            .intersection(landmarks)
902            .count();
903        if count >= min_count {
904            scores.push(CovisibilityKeyframeScore {
905                keyframe_id,
906                shared_landmark_count: count,
907            });
908        }
909    }
910    scores.sort_by(score_order);
911    scores
912}
913
914fn score_order(a: &CovisibilityKeyframeScore, b: &CovisibilityKeyframeScore) -> std::cmp::Ordering {
915    b.shared_landmark_count
916        .cmp(&a.shared_landmark_count)
917        .then_with(|| a.keyframe_id.cmp(&b.keyframe_id))
918}
919
920fn score_local_landmarks(
921    map: &VisualMap,
922    optimized_keyframes: &BTreeSet<FrameId>,
923    ba_keyframe_ids: &[FrameId],
924) -> Vec<LandmarkScore> {
925    let mut scores: BTreeMap<LandmarkId, LandmarkScore> = BTreeMap::new();
926    for keyframe_id in ba_keyframe_ids {
927        let Some(keyframe) = map.keyframes.get(keyframe_id) else {
928            continue;
929        };
930        for obs in &keyframe.observations {
931            if !map.landmarks.contains_key(&obs.landmark_id) {
932                continue;
933            }
934            let slot = scores.entry(obs.landmark_id).or_insert(LandmarkScore {
935                landmark_id: obs.landmark_id,
936                optimized_observation_count: 0,
937                total_observation_count: 0,
938            });
939            slot.total_observation_count += 1;
940            if optimized_keyframes.contains(keyframe_id) {
941                slot.optimized_observation_count += 1;
942            }
943        }
944    }
945    scores.into_values().collect()
946}
947
948fn count_selected_observations(
949    map: &VisualMap,
950    keyframe_ids: &[FrameId],
951    landmark_ids: &BTreeSet<LandmarkId>,
952) -> usize {
953    keyframe_ids
954        .iter()
955        .filter_map(|id| map.keyframes.get(id))
956        .map(|keyframe| {
957            keyframe
958                .observations
959                .iter()
960                .filter(|obs| landmark_ids.contains(&obs.landmark_id))
961                .count()
962        })
963        .sum()
964}
965
966fn mean_reprojection_px(ba: &BundleAdjustment) -> f64 {
967    let mut sum = 0.0;
968    let mut count = 0usize;
969    for obs in &ba.observations {
970        let (Some(pose), Some(point)) = (
971            ba.poses.get(&obs.keyframe_id),
972            ba.landmarks.get(&obs.landmark_id),
973        ) else {
974            continue;
975        };
976        let Some(predicted) = ba.camera.project(&pose.transform_world_point(point)) else {
977            continue;
978        };
979        sum += (predicted - obs.xy).norm();
980        count += 1;
981    }
982    if count == 0 {
983        f64::NAN
984    } else {
985        sum / count as f64
986    }
987}
988
989/// Mean pixel reprojection error of the observations represented by a
990/// covisibility selection in a written-back map. This is intentionally public
991/// so transactional callers can apply an additional pose constraint (for
992/// example loop-welding rotation anchoring) and re-run the same observable
993/// quality check before committing their cloned map.
994pub fn mean_selected_reprojection_px(
995    map: &VisualMap,
996    selection: &CovisibilityLocalBaSelection,
997) -> Option<f64> {
998    let selected_landmarks: BTreeSet<LandmarkId> = selection.landmark_ids.iter().copied().collect();
999    let mut keyframe_ids = selection.optimized_keyframe_ids.clone();
1000    keyframe_ids.extend(selection.fixed_keyframe_ids.iter().copied());
1001    keyframe_ids.sort_unstable();
1002    keyframe_ids.dedup();
1003
1004    let mut sum = 0.0;
1005    let mut count = 0usize;
1006    for keyframe_id in keyframe_ids {
1007        let keyframe = map.keyframes.get(&keyframe_id)?;
1008        let pose = keyframe.frame.pose.as_ref()?;
1009        let camera = map.cameras.get(&keyframe.frame.camera_id)?;
1010        for observation in &keyframe.observations {
1011            if !selected_landmarks.contains(&observation.landmark_id) {
1012                continue;
1013            }
1014            let point = &map.landmarks.get(&observation.landmark_id)?.position;
1015            let Some(predicted) = camera.project(&pose.transform_world_point(point)) else {
1016                continue;
1017            };
1018            sum += (predicted - observation.xy).norm();
1019            count += 1;
1020        }
1021    }
1022    (count > 0).then_some(sum / count as f64)
1023}
1024
1025/// Number of fixed boundary keyframes a solve must carry to satisfy
1026/// [`fixed_to_optimized_ratio_satisfied`].
1027///
1028/// Semantics: `required = ceil(optimized_keyframe_count * ratio)`. A
1029/// non-positive or non-finite ratio disables the requirement (returns `0`).
1030pub fn required_fixed_keyframes(optimized_keyframe_count: usize, ratio: f64) -> usize {
1031    if !ratio.is_finite() || ratio <= 0.0 {
1032        return 0;
1033    }
1034    (optimized_keyframe_count as f64 * ratio).ceil() as usize
1035}
1036
1037/// Write-back adequacy predicate for the fixed-anchor ratio gate.
1038///
1039/// Returns `true` (adequately anchored) when
1040/// `fixed_keyframe_count >= ceil(optimized_keyframe_count * ratio)`.
1041/// This is the *ratio* form of the fixed-boundary requirement; the absolute
1042/// floor form lives on [`CovisibilityLocalBaConfig::boundary_support_min_fixed_keyframes`].
1043pub fn fixed_to_optimized_ratio_satisfied(
1044    optimized_keyframe_count: usize,
1045    fixed_keyframe_count: usize,
1046    ratio: f64,
1047) -> bool {
1048    fixed_keyframe_count >= required_fixed_keyframes(optimized_keyframe_count, ratio)
1049}
1050
1051/// Fraction of the selected optimized landmarks that project behind (or onto)
1052/// at least one observing optimized camera in `map`.
1053///
1054/// Intended to run against the *solved* map (post write-back on a candidate
1055/// clone) so a degenerate/under-constrained solve — where optimized landmarks
1056/// collapse behind the optimized cameras — can be detected and its write-back
1057/// rejected. Uses the same [`Camera::project`] / `Pose::transform_world_point`
1058/// path as `selected_outlier_keys`, but unlike `mean_reprojection_px`,
1059/// which silently skips landmarks that fail to project, a non-positive
1060/// camera-frame depth (or a `None` projection) is counted here as a hard
1061/// degeneracy.
1062///
1063/// Only cameras in [`CovisibilityLocalBaSelection::optimized_keyframe_ids`]
1064/// (the variable-pose set a bad solve corrupts) are scored; fixed boundary
1065/// keyframes anchor the gauge and are ignored. A landmark counts as degenerate
1066/// if it lands behind *any* optimized camera that observes it. Returns `None`
1067/// when no optimized camera observes any selected landmark (nothing to score).
1068pub fn behind_camera_optimized_landmark_ratio(
1069    map: &VisualMap,
1070    selection: &CovisibilityLocalBaSelection,
1071) -> Option<f64> {
1072    let active_kf = map.keyframes.get(&selection.active_keyframe_id)?;
1073    let camera = map.cameras.get(&active_kf.frame.camera_id)?;
1074
1075    let mut considered = 0usize;
1076    let mut degenerate = 0usize;
1077    for landmark_id in &selection.landmark_ids {
1078        let Some(landmark) = map.landmarks.get(landmark_id) else {
1079            continue;
1080        };
1081        let mut observed_by_optimized = false;
1082        let mut behind = false;
1083        for keyframe_id in &selection.optimized_keyframe_ids {
1084            let Some(keyframe) = map.keyframes.get(keyframe_id) else {
1085                continue;
1086            };
1087            let Some(pose) = keyframe.frame.pose.as_ref() else {
1088                continue;
1089            };
1090            if !keyframe
1091                .observations
1092                .iter()
1093                .any(|obs| obs.landmark_id == *landmark_id)
1094            {
1095                continue;
1096            }
1097            observed_by_optimized = true;
1098            let point_cam = pose.transform_world_point(&landmark.position);
1099            if point_cam.z <= 0.0 || camera.project(&point_cam).is_none() {
1100                behind = true;
1101                break;
1102            }
1103        }
1104        if observed_by_optimized {
1105            considered += 1;
1106            if behind {
1107                degenerate += 1;
1108            }
1109        }
1110    }
1111
1112    if considered == 0 {
1113        None
1114    } else {
1115        Some(degenerate as f64 / considered as f64)
1116    }
1117}
1118
1119fn selected_outlier_keys(
1120    map: &VisualMap,
1121    camera: &Camera,
1122    selection: &CovisibilityLocalBaSelection,
1123    threshold_px: f64,
1124    use_general_stereo_observations: bool,
1125) -> BTreeSet<ObservationKey> {
1126    let landmark_ids: BTreeSet<LandmarkId> = selection.landmark_ids.iter().copied().collect();
1127    let mut outliers = BTreeSet::new();
1128    for keyframe_id in selection.all_keyframe_ids() {
1129        let Some(keyframe) = map.keyframes.get(&keyframe_id) else {
1130            continue;
1131        };
1132        let Some(pose) = keyframe.frame.pose.as_ref() else {
1133            continue;
1134        };
1135        for obs in &keyframe.observations {
1136            if !landmark_ids.contains(&obs.landmark_id) {
1137                continue;
1138            }
1139            let Some(landmark) = map.landmarks.get(&obs.landmark_id) else {
1140                continue;
1141            };
1142            let mut residual = camera
1143                .project(&pose.transform_world_point(&landmark.position))
1144                .map_or(f64::INFINITY, |predicted| (predicted - obs.xy).norm());
1145            if let Some((stereo, right_camera)) = use_general_stereo_observations
1146                .then(|| {
1147                    map.stereo_observations
1148                        .iter()
1149                        .find(|stereo| {
1150                            stereo.frame_id == obs.frame_id && stereo.landmark_id == obs.landmark_id
1151                        })
1152                        .and_then(|stereo| {
1153                            map.cameras
1154                                .get(&stereo.right_camera_id)
1155                                .map(|camera| (stereo, camera))
1156                        })
1157                })
1158                .flatten()
1159            {
1160                let point_left = pose.transform_world_point(&landmark.position);
1161                let right_residual = right_camera
1162                    .project(&stereo.left_to_right.transform_point(&point_left))
1163                    .map_or(f64::INFINITY, |predicted| {
1164                        (predicted - stereo.xy_right).norm()
1165                    });
1166                residual = residual.max(right_residual);
1167            }
1168            if !residual.is_finite() || residual > threshold_px {
1169                outliers.insert(ObservationKey {
1170                    frame_id: obs.frame_id,
1171                    landmark_id: obs.landmark_id,
1172                    keypoint_index: obs.keypoint_index,
1173                });
1174            }
1175        }
1176    }
1177    outliers
1178}
1179
1180fn remove_observations(map: &mut VisualMap, outliers: &BTreeSet<ObservationKey>) -> usize {
1181    if outliers.is_empty() {
1182        return 0;
1183    }
1184    let confidence_observations = map
1185        .keyframes
1186        .values()
1187        .flat_map(|keyframe| keyframe.observations.iter())
1188        .filter(|obs| {
1189            outliers.contains(&ObservationKey {
1190                frame_id: obs.frame_id,
1191                landmark_id: obs.landmark_id,
1192                keypoint_index: obs.keypoint_index,
1193            })
1194        })
1195        .cloned()
1196        .collect::<Vec<_>>();
1197    for observation in &confidence_observations {
1198        map.remove_observation_confidence(observation);
1199    }
1200    let mut removed = 0usize;
1201    for keyframe in map.keyframes.values_mut() {
1202        let before = keyframe.observations.len();
1203        keyframe.observations.retain(|obs| {
1204            !outliers.contains(&ObservationKey {
1205                frame_id: obs.frame_id,
1206                landmark_id: obs.landmark_id,
1207                keypoint_index: obs.keypoint_index,
1208            })
1209        });
1210        removed += before - keyframe.observations.len();
1211    }
1212    for landmark in map.landmarks.values_mut() {
1213        landmark.observations.retain(|obs| {
1214            !outliers.contains(&ObservationKey {
1215                frame_id: obs.frame_id,
1216                landmark_id: obs.landmark_id,
1217                keypoint_index: obs.keypoint_index,
1218            })
1219        });
1220    }
1221    map.stereo_observations.retain(|stereo| {
1222        !outliers.iter().any(|outlier| {
1223            outlier.frame_id == stereo.frame_id && outlier.landmark_id == stereo.landmark_id
1224        })
1225    });
1226    removed
1227}
1228
1229#[cfg(test)]
1230mod tests {
1231    use nalgebra::{Point3, UnitQuaternion, Vector3};
1232    use visloc_core::geometry::{Pose, SE3};
1233    use visloc_core::types::{Camera, Frame, Keyframe, Landmark, StereoObservation};
1234
1235    use super::*;
1236
1237    fn pose_at_center(x: f64, y: f64, z: f64) -> Pose {
1238        Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::new(-x, -y, -z))
1239    }
1240
1241    fn add_keyframe(map: &mut VisualMap, id: FrameId, pose: Pose) {
1242        let mut frame = Frame::new(id, 1);
1243        frame.pose = Some(pose);
1244        map.keyframes.insert(
1245            id,
1246            Keyframe {
1247                frame,
1248                observations: Vec::new(),
1249            },
1250        );
1251    }
1252
1253    fn add_observation(map: &mut VisualMap, frame_id: FrameId, landmark_id: LandmarkId) {
1254        let camera = map.cameras.get(&1).unwrap();
1255        let pose = map.keyframes[&frame_id].frame.pose.as_ref().unwrap();
1256        let point = map.landmarks[&landmark_id].position;
1257        let xy = camera.project(&pose.transform_world_point(&point)).unwrap();
1258        let keypoint_index = {
1259            let keyframe = map.keyframes.get_mut(&frame_id).unwrap();
1260            let idx = keyframe.frame.keypoints.len();
1261            keyframe.frame.keypoints.push(xy);
1262            keyframe.frame.descriptors.push(vec![landmark_id as f32]);
1263            idx
1264        };
1265        let obs = Observation {
1266            frame_id,
1267            landmark_id,
1268            keypoint_index,
1269            xy,
1270        };
1271        map.keyframes
1272            .get_mut(&frame_id)
1273            .unwrap()
1274            .observations
1275            .push(obs.clone());
1276        map.landmarks
1277            .get_mut(&landmark_id)
1278            .unwrap()
1279            .observations
1280            .push(obs);
1281    }
1282
1283    fn synthetic_map() -> (VisualMap, Vec<Pose>) {
1284        let camera = Camera::pinhole(1, 640, 480, 320.0, 320.0, 320.0, 240.0);
1285        let mut map = VisualMap::new();
1286        map.cameras.insert(1, camera);
1287        let truth_poses = vec![
1288            pose_at_center(0.0, 0.0, 0.0),
1289            pose_at_center(1.0, 0.0, 0.0),
1290            pose_at_center(2.0, 0.0, 0.0),
1291            pose_at_center(3.0, 0.0, 0.0),
1292        ];
1293        for (id, pose) in truth_poses.iter().enumerate() {
1294            add_keyframe(&mut map, id as u64, pose.clone());
1295        }
1296        for i in 0..24u64 {
1297            let x = (i % 6) as f64 * 0.35 + 0.5;
1298            let y = (i / 6) as f64 * 0.12 - 0.18;
1299            let z = 5.0 + (i % 4) as f64 * 0.4;
1300            map.landmarks
1301                .insert(i, Landmark::new(i, Point3::new(x, y, z)));
1302        }
1303        for frame_id in 0..4u64 {
1304            for landmark_id in 0..24u64 {
1305                add_observation(&mut map, frame_id, landmark_id);
1306            }
1307        }
1308        // Perturb two variable keyframes and the landmarks after measurements
1309        // have been generated from the true geometry.
1310        map.keyframes.get_mut(&0).unwrap().frame.pose = Some(pose_at_center(0.25, 0.02, 0.0));
1311        map.keyframes.get_mut(&2).unwrap().frame.pose = Some(pose_at_center(2.35, -0.04, 0.0));
1312        for (id, landmark) in map.landmarks.iter_mut() {
1313            let s = (*id % 3) as f64 - 1.0;
1314            landmark.position.x += 0.04 * s;
1315            landmark.position.z += 0.08;
1316        }
1317        (map, truth_poses)
1318    }
1319
1320    #[test]
1321    fn selection_picks_neighbors_boundaries_and_local_landmarks() {
1322        let (map, _) = synthetic_map();
1323        let config = CovisibilityLocalBaConfig {
1324            max_neighbor_keyframes: 1,
1325            min_shared_landmarks: 1,
1326            max_boundary_keyframes: 2,
1327            min_boundary_observations: 1,
1328            min_observations_per_landmark: 2,
1329            ..CovisibilityLocalBaConfig::default()
1330        };
1331
1332        let selection = select_covisibility_local_ba_window(&map, 2, &config).unwrap();
1333
1334        assert_eq!(selection.active_keyframe_id, 2);
1335        assert_eq!(selection.optimized_keyframe_ids, vec![2, 0]);
1336        assert_eq!(selection.fixed_keyframe_ids, vec![1, 3]);
1337        assert_eq!(selection.landmark_ids.len(), 24);
1338        assert_eq!(selection.observation_count, 96);
1339        assert!(!selection.boundary_fallback_used);
1340    }
1341
1342    #[test]
1343    fn sparse_factor_allowlist_controls_variable_neighbors_not_fixed_boundary() {
1344        let (map, _) = synthetic_map();
1345        let config = CovisibilityLocalBaConfig {
1346            max_neighbor_keyframes: 3,
1347            min_shared_landmarks: 1,
1348            max_boundary_keyframes: 3,
1349            min_boundary_observations: 1,
1350            min_observations_per_landmark: 2,
1351            ..CovisibilityLocalBaConfig::default()
1352        };
1353        let allowlist = BTreeSet::from([1]);
1354
1355        let selection = select_covisibility_local_ba_window_with_neighbor_allowlist(
1356            &map,
1357            2,
1358            &config,
1359            Some(&allowlist),
1360        )
1361        .unwrap();
1362
1363        assert_eq!(selection.optimized_keyframe_ids, vec![2, 1]);
1364        assert_eq!(selection.neighbor_candidates.len(), 1);
1365        assert_eq!(selection.neighbor_candidates[0].keyframe_id, 1);
1366        assert_eq!(selection.fixed_keyframe_ids, vec![0, 3]);
1367    }
1368
1369    #[test]
1370    fn bundle_builder_uses_general_stereo_instead_of_double_counting_left_pixel() {
1371        let (mut map, _) = synthetic_map();
1372        let right_camera = Camera::pinhole(2, 640, 480, 325.0, 315.0, 318.0, 242.0);
1373        let left_to_right = SE3::new(
1374            UnitQuaternion::from_euler_angles(0.01, -0.02, 0.015),
1375            Vector3::new(-0.11, 0.002, 0.001),
1376        );
1377        let pose = map.keyframes[&2].frame.pose.as_ref().unwrap();
1378        let point_left = pose.transform_world_point(&map.landmarks[&0].position);
1379        let xy_right = right_camera
1380            .project(&left_to_right.transform_point(&point_left))
1381            .unwrap();
1382        map.cameras.insert(2, right_camera);
1383        map.stereo_observations.push(StereoObservation {
1384            frame_id: 2,
1385            landmark_id: 0,
1386            right_camera_id: 2,
1387            xy_right,
1388            left_to_right,
1389        });
1390        let config = CovisibilityLocalBaConfig {
1391            max_neighbor_keyframes: 1,
1392            min_shared_landmarks: 1,
1393            max_boundary_keyframes: 2,
1394            min_boundary_observations: 1,
1395            min_observations_per_landmark: 2,
1396            use_general_stereo_observations: true,
1397            ..CovisibilityLocalBaConfig::default()
1398        };
1399        let selection = select_covisibility_local_ba_window(&map, 2, &config).unwrap();
1400        let (ba, _) =
1401            build_ba_from_selection(&map, map.cameras.get(&1).unwrap(), &selection, &config)
1402                .unwrap();
1403
1404        assert_eq!(ba.general_stereo_observations.len(), 1);
1405        assert_eq!(ba.observations.len(), selection.observation_count - 1);
1406
1407        map.stereo_observations[0].xy_right.x += 100.0;
1408        let (gated, _) =
1409            build_ba_from_selection(&map, map.cameras.get(&1).unwrap(), &selection, &config)
1410                .unwrap();
1411        assert!(gated.general_stereo_observations.is_empty());
1412        assert_eq!(gated.observations.len(), selection.observation_count);
1413    }
1414
1415    #[test]
1416    fn bundle_builder_preserves_map_confidence_in_ba_flattened_order() {
1417        let (mut map, _) = synthetic_map();
1418        let scored_observation = map.keyframes[&2]
1419            .observations
1420            .iter()
1421            .find(|observation| observation.landmark_id == 0)
1422            .cloned()
1423            .unwrap();
1424        let strong_observation = map.keyframes[&2]
1425            .observations
1426            .iter()
1427            .find(|observation| observation.landmark_id == 1)
1428            .cloned()
1429            .unwrap();
1430        assert!(map.set_observation_confidence(&scored_observation, 0.2));
1431        assert!(map.set_observation_confidence(&strong_observation, 0.8));
1432        let config = CovisibilityLocalBaConfig {
1433            max_neighbor_keyframes: 1,
1434            min_shared_landmarks: 1,
1435            max_boundary_keyframes: 2,
1436            min_boundary_observations: 1,
1437            min_observations_per_landmark: 2,
1438            use_observation_confidence_weights: true,
1439            ..CovisibilityLocalBaConfig::default()
1440        };
1441        let selection = select_covisibility_local_ba_window(&map, 2, &config).unwrap();
1442        let (ba, weights) =
1443            build_ba_from_selection(&map, map.cameras.get(&1).unwrap(), &selection, &config)
1444                .unwrap();
1445        let weights = weights.expect("learned confidence should activate weighting");
1446        let index = ba
1447            .observations
1448            .iter()
1449            .position(|observation| observation.keyframe_id == 2 && observation.landmark_id == 0)
1450            .unwrap();
1451        let strong_index = ba
1452            .observations
1453            .iter()
1454            .position(|observation| observation.keyframe_id == 2 && observation.landmark_id == 1)
1455            .unwrap();
1456
1457        assert_eq!(weights.len(), ba.observations.len());
1458        assert!((weights[index] - 0.4).abs() < 1.0e-6);
1459        assert!((weights[strong_index] - 1.6).abs() < 1.0e-6);
1460        assert!(weights.iter().enumerate().all(|(other, weight)| {
1461            other == index || other == strong_index || (*weight - 1.0).abs() < f64::EPSILON
1462        }));
1463
1464        let uniform_config = CovisibilityLocalBaConfig {
1465            use_observation_confidence_weights: false,
1466            ..config
1467        };
1468        let (_, uniform_weights) = build_ba_from_selection(
1469            &map,
1470            map.cameras.get(&1).unwrap(),
1471            &selection,
1472            &uniform_config,
1473        )
1474        .unwrap();
1475        assert_eq!(uniform_weights, None);
1476    }
1477
1478    #[test]
1479    fn selection_rejects_active_keyframe_below_observation_floor() {
1480        let (map, _) = synthetic_map();
1481        let config = CovisibilityLocalBaConfig {
1482            max_neighbor_keyframes: 1,
1483            min_shared_landmarks: 1,
1484            max_boundary_keyframes: 2,
1485            min_boundary_observations: 1,
1486            min_observations_per_landmark: 2,
1487            min_active_observations: 25,
1488            ..CovisibilityLocalBaConfig::default()
1489        };
1490
1491        let err = select_covisibility_local_ba_window(&map, 2, &config).unwrap_err();
1492
1493        assert_eq!(
1494            err,
1495            CovisibilityLocalBaError::InsufficientActiveObservations {
1496                keyframe_id: 2,
1497                observation_count: 24,
1498                min_observations: 25,
1499                boundary_fallback_used: false,
1500            }
1501        );
1502    }
1503
1504    #[test]
1505    fn selection_can_fallback_to_lower_boundary_observation_floor() {
1506        let (map, _) = synthetic_map();
1507        let strict_config = CovisibilityLocalBaConfig {
1508            max_neighbor_keyframes: 0,
1509            min_shared_landmarks: 1,
1510            max_boundary_keyframes: 2,
1511            min_boundary_observations: 25,
1512            fallback_min_boundary_observations: None,
1513            min_observations_per_landmark: 2,
1514            ..CovisibilityLocalBaConfig::default()
1515        };
1516
1517        let strict_err = select_covisibility_local_ba_window(&map, 2, &strict_config).unwrap_err();
1518        assert_eq!(strict_err, CovisibilityLocalBaError::NoLocalLandmarks);
1519
1520        let fallback_config = CovisibilityLocalBaConfig {
1521            fallback_min_boundary_observations: Some(1),
1522            ..strict_config
1523        };
1524        let selection = select_covisibility_local_ba_window(&map, 2, &fallback_config).unwrap();
1525
1526        assert!(selection.boundary_fallback_used);
1527        assert_eq!(selection.optimized_keyframe_ids, vec![2]);
1528        assert_eq!(selection.fixed_keyframe_ids, vec![0, 1]);
1529        assert_eq!(selection.landmark_ids.len(), 24);
1530    }
1531
1532    #[test]
1533    fn selection_rejects_large_window_with_insufficient_boundary_keyframes() {
1534        let (map, _) = synthetic_map();
1535        let config = CovisibilityLocalBaConfig {
1536            max_neighbor_keyframes: 3,
1537            min_shared_landmarks: 1,
1538            max_boundary_keyframes: 1,
1539            min_boundary_observations: 1,
1540            min_observations_per_landmark: 2,
1541            boundary_support_min_optimized_keyframes: Some(3),
1542            boundary_support_min_fixed_keyframes: 2,
1543            ..CovisibilityLocalBaConfig::default()
1544        };
1545
1546        let err = select_covisibility_local_ba_window(&map, 2, &config).unwrap_err();
1547
1548        assert_eq!(
1549            err,
1550            CovisibilityLocalBaError::InsufficientBoundaryKeyframes {
1551                optimized_keyframe_count: 4,
1552                fixed_keyframe_count: 0,
1553                min_optimized_keyframes: 3,
1554                min_fixed_keyframes: 2,
1555                boundary_fallback_used: false,
1556            }
1557        );
1558    }
1559
1560    #[test]
1561    fn covisibility_ba_reduces_reprojection_and_updates_active_pose() {
1562        let (mut map, truth_poses) = synthetic_map();
1563        let before_center = map.keyframes[&2]
1564            .frame
1565            .pose
1566            .as_ref()
1567            .unwrap()
1568            .camera_center_world();
1569        let before_error = (before_center - truth_poses[2].camera_center_world()).norm();
1570        let config = CovisibilityLocalBaConfig {
1571            max_neighbor_keyframes: 1,
1572            min_shared_landmarks: 1,
1573            max_boundary_keyframes: 2,
1574            min_boundary_observations: 1,
1575            min_observations_per_landmark: 2,
1576            outlier_reprojection_threshold_px: Some(10.0),
1577            ..CovisibilityLocalBaConfig::default()
1578        };
1579
1580        let result = refine_visual_map_with_covisibility_ba(&mut map, 2, &config).unwrap();
1581
1582        let after_center = map.keyframes[&2]
1583            .frame
1584            .pose
1585            .as_ref()
1586            .unwrap()
1587            .camera_center_world();
1588        let after_error = (after_center - truth_poses[2].camera_center_world()).norm();
1589
1590        assert!(result.mean_reprojection_after_px < result.mean_reprojection_before_px);
1591        assert!(after_error < before_error);
1592        assert!(result.updated_keyframe_count >= 1);
1593        assert_eq!(result.updated_landmark_count, 24);
1594        assert_eq!(result.outlier_observation_count, 0);
1595    }
1596
1597    #[test]
1598    fn covisibility_ba_can_remove_post_ba_outlier_observations() {
1599        let (mut map, _) = synthetic_map();
1600        let config = CovisibilityLocalBaConfig {
1601            max_neighbor_keyframes: 1,
1602            min_shared_landmarks: 1,
1603            max_boundary_keyframes: 2,
1604            min_boundary_observations: 1,
1605            min_observations_per_landmark: 2,
1606            outlier_reprojection_threshold_px: Some(0.5),
1607            remove_outlier_observations: true,
1608            ..CovisibilityLocalBaConfig::default()
1609        };
1610        // Corrupt one selected observation after the synthetic measurements were
1611        // inserted. The same key is mirrored in the landmark observation list.
1612        let keypoint_index = map.keyframes[&2].observations[0].keypoint_index;
1613        map.keyframes.get_mut(&2).unwrap().observations[0].xy.x += 100.0;
1614        if let Some(obs) = map
1615            .landmarks
1616            .get_mut(&0)
1617            .unwrap()
1618            .observations
1619            .iter_mut()
1620            .find(|obs| obs.frame_id == 2 && obs.keypoint_index == keypoint_index)
1621        {
1622            obs.xy.x += 100.0;
1623        }
1624
1625        let result = refine_visual_map_with_covisibility_ba(&mut map, 2, &config).unwrap();
1626
1627        assert!(result.outlier_observation_count >= 1);
1628        assert!(result.removed_observation_count >= 1);
1629        assert!(!map.keyframes[&2]
1630            .observations
1631            .iter()
1632            .any(|obs| { obs.landmark_id == 0 && obs.keypoint_index == keypoint_index }));
1633        assert!(!map.landmarks[&0]
1634            .observations
1635            .iter()
1636            .any(|obs| { obs.frame_id == 2 && obs.keypoint_index == keypoint_index }));
1637    }
1638
1639    fn behind_camera_test_config() -> CovisibilityLocalBaConfig {
1640        CovisibilityLocalBaConfig {
1641            max_neighbor_keyframes: 1,
1642            min_shared_landmarks: 1,
1643            max_boundary_keyframes: 2,
1644            min_boundary_observations: 1,
1645            min_observations_per_landmark: 2,
1646            ..CovisibilityLocalBaConfig::default()
1647        }
1648    }
1649
1650    #[test]
1651    fn behind_camera_ratio_is_zero_for_healthy_window() {
1652        let (map, _) = synthetic_map();
1653        let config = behind_camera_test_config();
1654        let selection = select_covisibility_local_ba_window(&map, 2, &config).unwrap();
1655
1656        // All synthetic landmarks sit ~5 m in front of the cameras.
1657        let ratio = behind_camera_optimized_landmark_ratio(&map, &selection).unwrap();
1658        assert!(ratio.abs() < 1e-9, "healthy window ratio {ratio}");
1659    }
1660
1661    #[test]
1662    fn behind_camera_ratio_is_high_when_optimized_landmarks_collapse_behind() {
1663        let (mut map, _) = synthetic_map();
1664        let config = behind_camera_test_config();
1665        let selection = select_covisibility_local_ba_window(&map, 2, &config).unwrap();
1666
1667        // Simulate a degenerate solve: drive every selected landmark behind the
1668        // (identity-rotation) optimized cameras, whose centres sit near z = 0.
1669        for landmark_id in &selection.landmark_ids {
1670            if let Some(landmark) = map.landmarks.get_mut(landmark_id) {
1671                landmark.position.z = -10.0;
1672            }
1673        }
1674
1675        let ratio = behind_camera_optimized_landmark_ratio(&map, &selection).unwrap();
1676        assert!(ratio > 0.5, "collapsed window ratio {ratio}");
1677    }
1678
1679    #[test]
1680    fn fixed_to_optimized_ratio_gate_semantics() {
1681        // required = ceil(optimized * ratio); satisfied = fixed >= required.
1682        // optimized=7, r=0.34 -> ceil(2.38)=3, so fixed=1 is rejected.
1683        assert_eq!(required_fixed_keyframes(7, 0.34), 3);
1684        assert!(!fixed_to_optimized_ratio_satisfied(7, 1, 0.34));
1685        // optimized=3, r=0.34 -> ceil(1.02)=2, so fixed=2 is accepted.
1686        assert_eq!(required_fixed_keyframes(3, 0.34), 2);
1687        assert!(fixed_to_optimized_ratio_satisfied(3, 2, 0.34));
1688        // A non-positive ratio disables the requirement (always satisfied).
1689        assert_eq!(required_fixed_keyframes(7, 0.0), 0);
1690        assert!(fixed_to_optimized_ratio_satisfied(7, 0, 0.0));
1691    }
1692
1693    #[test]
1694    fn pose_anchor_prior_pins_window_gauge() {
1695        // `synthetic_map` already perturbs keyframes 0 and 2 away from the true
1696        // geometry before BA runs, so there is real pose motion for an unanchored
1697        // solve to make and for the anchor prior to resist.
1698        let (map, _) = synthetic_map();
1699        let base_config = CovisibilityLocalBaConfig {
1700            max_neighbor_keyframes: 1,
1701            min_shared_landmarks: 1,
1702            max_boundary_keyframes: 2,
1703            min_boundary_observations: 1,
1704            min_observations_per_landmark: 2,
1705            ..CovisibilityLocalBaConfig::default()
1706        };
1707
1708        let initial_centers: BTreeMap<FrameId, Point3<f64>> = map
1709            .keyframes
1710            .iter()
1711            .map(|(id, kf)| (*id, kf.frame.pose.as_ref().unwrap().camera_center_world()))
1712            .collect();
1713
1714        let displacement = |refined_map: &VisualMap, optimized_ids: &[FrameId]| -> f64 {
1715            optimized_ids
1716                .iter()
1717                .map(|id| {
1718                    let after = refined_map.keyframes[id]
1719                        .frame
1720                        .pose
1721                        .as_ref()
1722                        .unwrap()
1723                        .camera_center_world();
1724                    (after - initial_centers[id]).norm()
1725                })
1726                .sum()
1727        };
1728
1729        let mut unanchored_map = map.clone();
1730        let unanchored_config = CovisibilityLocalBaConfig {
1731            pose_anchor_prior_weight: None,
1732            ..base_config
1733        };
1734        let unanchored_result =
1735            refine_visual_map_with_covisibility_ba(&mut unanchored_map, 2, &unanchored_config)
1736                .unwrap();
1737        let unanchored_displacement = displacement(
1738            &unanchored_map,
1739            &unanchored_result.selection.optimized_keyframe_ids,
1740        );
1741
1742        let mut anchored_map = map;
1743        let anchored_config = CovisibilityLocalBaConfig {
1744            pose_anchor_prior_weight: Some(1.0e6),
1745            ..base_config
1746        };
1747        let anchored_result =
1748            refine_visual_map_with_covisibility_ba(&mut anchored_map, 2, &anchored_config).unwrap();
1749        let anchored_displacement = displacement(
1750            &anchored_map,
1751            &anchored_result.selection.optimized_keyframe_ids,
1752        );
1753
1754        assert!(
1755            unanchored_displacement > 1e-6,
1756            "expected the unanchored BA to move the window, got {unanchored_displacement}"
1757        );
1758        assert!(
1759            anchored_displacement < unanchored_displacement,
1760            "anchored displacement {anchored_displacement} should be smaller than unanchored {unanchored_displacement}"
1761        );
1762    }
1763
1764    #[test]
1765    fn matrix_free_opt_in_solves_the_local_window() {
1766        let (mut map, _) = synthetic_map();
1767        let config = CovisibilityLocalBaConfig {
1768            max_neighbor_keyframes: 2,
1769            min_shared_landmarks: 1,
1770            max_boundary_keyframes: 1,
1771            min_boundary_observations: 1,
1772            ba_config: BaConfig {
1773                matrix_free_ba: true,
1774                ..BaConfig::default()
1775            },
1776            ..CovisibilityLocalBaConfig::default()
1777        };
1778
1779        let result = refine_visual_map_with_covisibility_ba(&mut map, 2, &config)
1780            .expect("matrix-free local BA");
1781        assert!(result.mean_reprojection_after_px.is_finite());
1782        assert!(result.mean_reprojection_before_px.is_finite());
1783        assert!(
1784            result.mean_reprojection_after_px <= result.mean_reprojection_before_px + 1e-9,
1785            "matrix-free local BA should not increase the mean reprojection: {} -> {}",
1786            result.mean_reprojection_before_px,
1787            result.mean_reprojection_after_px,
1788        );
1789    }
1790}