Skip to main content

visloc_slam/
sparse_factor_graph.rs

1//! DROID-style lifecycle management for a sparse keyframe factor graph.
2//!
3//! This module deliberately separates factor proposal/lifecycle from the
4//! optimizer.  The current proposer derives temporal, proximity, and stereo
5//! support from a [`VisualMap`].  A future learned frontend can update the
6//! target correction, anisotropic information, and damping on the same factor
7//! records without changing the metric BA/PnP acceptance layer.
8
9use std::collections::{BTreeMap, BTreeSet};
10
11use visloc_core::types::{FrameId, LandmarkId, Observation, VisualMap};
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
14pub enum SparseFactorKind {
15    Temporal,
16    Proximity,
17    Stereo,
18}
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
21pub struct SparseFactorKey {
22    pub from_keyframe_id: FrameId,
23    pub to_keyframe_id: FrameId,
24    pub kind: SparseFactorKind,
25}
26
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub enum SparseFactorState {
29    Active,
30    Inactive,
31}
32
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub enum SparseFactorInactiveReason {
35    LowConfidence,
36    WindowAge,
37    ActiveBudget,
38}
39
40/// Optimizer-facing measurement carried by every edge.  Geometric factors
41/// start with zero correction and isotropic information; learned update
42/// operators may replace these values in-place later.
43#[derive(Debug, Clone, Copy, PartialEq)]
44pub struct SparseFactorMeasurement {
45    pub target_correction_px: [f32; 2],
46    pub information: [f32; 2],
47    pub damping: f32,
48}
49
50impl SparseFactorMeasurement {
51    fn geometric(confidence: f32, damping: f32) -> Self {
52        let confidence = confidence.clamp(0.0, 1.0);
53        Self {
54            target_correction_px: [0.0, 0.0],
55            information: [confidence, confidence],
56            damping,
57        }
58    }
59
60    fn is_valid(self) -> bool {
61        self.target_correction_px.iter().all(|v| v.is_finite())
62            && self.information.iter().all(|v| v.is_finite() && *v >= 0.0)
63            && self.damping.is_finite()
64            && self.damping >= 0.0
65    }
66}
67
68#[derive(Debug, Clone, PartialEq)]
69pub struct SparseKeyframeFactor {
70    pub key: SparseFactorKey,
71    pub state: SparseFactorState,
72    pub inactive_reason: Option<SparseFactorInactiveReason>,
73    pub support_count: usize,
74    pub confidence: f32,
75    pub measurement: SparseFactorMeasurement,
76    pub created_generation: u64,
77    pub last_scored_generation: u64,
78    pub inactive_since_generation: Option<u64>,
79    pub low_confidence_streak: usize,
80    pub update_count: u64,
81}
82
83#[derive(Debug, Clone, PartialEq)]
84pub struct SparseFactorGraphConfig {
85    /// Add bidirectional temporal edges to this many previous keyframes.
86    pub temporal_radius: usize,
87    /// Number of newest keyframes whose incident edges remain frontend-active.
88    pub active_window_keyframes: usize,
89    /// Maximum camera-centre separation for a non-temporal proximity edge.
90    pub proximity_radius_meters: f64,
91    pub proximity_min_shared_landmarks: usize,
92    pub max_proximity_neighbors_per_keyframe: usize,
93    /// Shared/stereo support at which geometric confidence saturates.
94    pub support_saturation_count: usize,
95    pub minimum_active_confidence: f32,
96    pub reactivation_confidence: f32,
97    /// Consecutive low-confidence rescoring passes before an edge is retired.
98    pub low_confidence_patience: usize,
99    pub max_active_factors: usize,
100    /// Inactive factors older than this many keyframe updates are forgotten.
101    pub max_inactive_age_generations: u64,
102    /// Temporal continuity edges are retired by window age, not confidence.
103    pub protect_temporal_from_confidence_pruning: bool,
104    pub geometric_damping: f32,
105}
106
107impl Default for SparseFactorGraphConfig {
108    fn default() -> Self {
109        Self {
110            temporal_radius: 3,
111            active_window_keyframes: 12,
112            proximity_radius_meters: 2.5,
113            proximity_min_shared_landmarks: 15,
114            max_proximity_neighbors_per_keyframe: 8,
115            support_saturation_count: 50,
116            minimum_active_confidence: 0.15,
117            reactivation_confidence: 0.25,
118            low_confidence_patience: 2,
119            max_active_factors: 256,
120            max_inactive_age_generations: 80,
121            protect_temporal_from_confidence_pruning: true,
122            geometric_damping: 1.0e-4,
123        }
124    }
125}
126
127impl SparseFactorGraphConfig {
128    pub fn is_valid(&self) -> bool {
129        self.temporal_radius > 0
130            && self.active_window_keyframes > 1
131            && self.proximity_radius_meters.is_finite()
132            && self.proximity_radius_meters > 0.0
133            && self.proximity_min_shared_landmarks > 0
134            && self.max_proximity_neighbors_per_keyframe > 0
135            && self.support_saturation_count > 0
136            && self.minimum_active_confidence.is_finite()
137            && (0.0..=1.0).contains(&self.minimum_active_confidence)
138            && self.reactivation_confidence.is_finite()
139            && (self.minimum_active_confidence..=1.0).contains(&self.reactivation_confidence)
140            && self.low_confidence_patience > 0
141            && self.max_active_factors > 0
142            && self.max_inactive_age_generations > 0
143            && self.geometric_damping.is_finite()
144            && self.geometric_damping >= 0.0
145    }
146}
147
148#[derive(Debug, Clone, PartialEq, Eq, Default)]
149pub struct SparseFactorGraphUpdateStats {
150    pub keyframe_id: FrameId,
151    pub generation: u64,
152    pub added: usize,
153    pub reactivated: usize,
154    pub inactivated_low_confidence: usize,
155    pub inactivated_window_age: usize,
156    pub inactivated_budget: usize,
157    pub pruned: usize,
158    pub active_temporal: usize,
159    pub active_proximity: usize,
160    pub active_stereo: usize,
161    pub inactive: usize,
162}
163
164#[derive(Debug, Clone, PartialEq)]
165pub struct SparseFactorGraph {
166    config: SparseFactorGraphConfig,
167    generation: u64,
168    keyframe_order: Vec<FrameId>,
169    factors: BTreeMap<SparseFactorKey, SparseKeyframeFactor>,
170}
171
172impl SparseFactorGraph {
173    pub fn new(config: SparseFactorGraphConfig) -> Self {
174        assert!(
175            config.is_valid(),
176            "invalid sparse factor graph configuration"
177        );
178        Self {
179            config,
180            generation: 0,
181            keyframe_order: Vec::new(),
182            factors: BTreeMap::new(),
183        }
184    }
185
186    pub const fn config(&self) -> &SparseFactorGraphConfig {
187        &self.config
188    }
189
190    pub fn factors(&self) -> impl Iterator<Item = &SparseKeyframeFactor> {
191        self.factors.values()
192    }
193
194    pub fn active_factors(&self) -> impl Iterator<Item = &SparseKeyframeFactor> {
195        self.factors
196            .values()
197            .filter(|factor| factor.state == SparseFactorState::Active)
198    }
199
200    pub fn inactive_factors(&self) -> impl Iterator<Item = &SparseKeyframeFactor> {
201        self.factors
202            .values()
203            .filter(|factor| factor.state == SparseFactorState::Inactive)
204    }
205
206    pub fn factor(&self, key: SparseFactorKey) -> Option<&SparseKeyframeFactor> {
207        self.factors.get(&key)
208    }
209
210    /// Replace an edge target/information estimate, e.g. from a learned
211    /// recurrent update operator. Invalid numerical values are rejected.
212    pub fn update_measurement(
213        &mut self,
214        key: SparseFactorKey,
215        measurement: SparseFactorMeasurement,
216    ) -> bool {
217        if !measurement.is_valid() {
218            return false;
219        }
220        let Some(factor) = self.factors.get_mut(&key) else {
221            return false;
222        };
223        factor.measurement = measurement;
224        factor.update_count = factor.update_count.saturating_add(1);
225        true
226    }
227
228    /// Explicitly reactivate an inactive factor selected by a broader
229    /// geometric/learned recovery pass. Ordinary rescoring does not revive
230    /// budget- or age-retired edges, avoiding active-set churn.
231    pub fn reactivate_factor(&mut self, key: SparseFactorKey) -> bool {
232        let Some(factor) = self.factors.get_mut(&key) else {
233            return false;
234        };
235        if factor.state == SparseFactorState::Active
236            || factor.confidence < self.config.reactivation_confidence
237        {
238            return false;
239        }
240        factor.state = SparseFactorState::Active;
241        factor.inactive_reason = None;
242        factor.inactive_since_generation = None;
243        factor.low_confidence_streak = 0;
244        true
245    }
246
247    /// Update proposals and lifecycle after a keyframe has been committed to
248    /// the map. Existing inactive factors are rescored so a broader recovery
249    /// pass can reactivate geometry that becomes supported again.
250    pub fn update_from_map(
251        &mut self,
252        map: &VisualMap,
253        new_keyframe_id: FrameId,
254    ) -> SparseFactorGraphUpdateStats {
255        self.generation = self.generation.saturating_add(1);
256        if !self.keyframe_order.contains(&new_keyframe_id) {
257            self.keyframe_order.push(new_keyframe_id);
258        }
259        self.keyframe_order
260            .retain(|id| map.keyframes.contains_key(id));
261
262        let mut stats = SparseFactorGraphUpdateStats {
263            keyframe_id: new_keyframe_id,
264            generation: self.generation,
265            ..SparseFactorGraphUpdateStats::default()
266        };
267        let proposals = self.propose_new_factors(map, new_keyframe_id);
268        for (key, support_count, confidence) in proposals {
269            match self.factors.get_mut(&key) {
270                Some(factor) => {
271                    factor.support_count = support_count;
272                    factor.confidence = confidence;
273                    factor.last_scored_generation = self.generation;
274                    factor.low_confidence_streak = 0;
275                    factor.update_count = factor.update_count.saturating_add(1);
276                    if factor.state == SparseFactorState::Inactive
277                        && confidence >= self.config.reactivation_confidence
278                    {
279                        factor.state = SparseFactorState::Active;
280                        factor.inactive_reason = None;
281                        factor.inactive_since_generation = None;
282                        stats.reactivated += 1;
283                    }
284                }
285                None => {
286                    self.factors.insert(
287                        key,
288                        SparseKeyframeFactor {
289                            key,
290                            state: SparseFactorState::Active,
291                            inactive_reason: None,
292                            support_count,
293                            confidence,
294                            measurement: SparseFactorMeasurement::geometric(
295                                confidence,
296                                self.config.geometric_damping,
297                            ),
298                            created_generation: self.generation,
299                            last_scored_generation: self.generation,
300                            inactive_since_generation: None,
301                            low_confidence_streak: 0,
302                            update_count: 1,
303                        },
304                    );
305                    stats.added += 1;
306                }
307            }
308        }
309
310        self.rescore_existing(map, &mut stats);
311        self.retire_outside_active_window(&mut stats);
312        self.enforce_active_budget(&mut stats);
313        self.prune_stale_inactive(&mut stats);
314        self.fill_counts(&mut stats);
315        stats
316    }
317
318    /// Highest-confidence inactive edges incident to `query_keyframe_id`.
319    /// These are the first edges a periodic broader/global recovery pass
320    /// should ask its geometric or learned updater to reconsider.
321    pub fn broader_recovery_candidates(
322        &self,
323        query_keyframe_id: FrameId,
324        maximum: usize,
325    ) -> Vec<&SparseKeyframeFactor> {
326        let mut candidates = self
327            .inactive_factors()
328            .filter(|factor| {
329                factor.key.from_keyframe_id == query_keyframe_id
330                    || factor.key.to_keyframe_id == query_keyframe_id
331            })
332            .collect::<Vec<_>>();
333        candidates.sort_by(|left, right| {
334            right
335                .confidence
336                .total_cmp(&left.confidence)
337                .then_with(|| right.support_count.cmp(&left.support_count))
338                .then_with(|| left.key.cmp(&right.key))
339        });
340        candidates.truncate(maximum);
341        candidates
342    }
343
344    /// Active non-self neighbors connected to one keyframe. Both directed
345    /// orientations collapse to one deterministic id set.
346    pub fn active_neighbor_keyframe_ids(&self, keyframe_id: FrameId) -> BTreeSet<FrameId> {
347        let mut neighbors = BTreeSet::new();
348        for factor in self.active_factors() {
349            if factor.key.kind == SparseFactorKind::Stereo {
350                continue;
351            }
352            if factor.key.from_keyframe_id == keyframe_id
353                && factor.key.to_keyframe_id != keyframe_id
354            {
355                neighbors.insert(factor.key.to_keyframe_id);
356            } else if factor.key.to_keyframe_id == keyframe_id
357                && factor.key.from_keyframe_id != keyframe_id
358            {
359                neighbors.insert(factor.key.from_keyframe_id);
360            }
361        }
362        neighbors
363    }
364
365    fn propose_new_factors(
366        &self,
367        map: &VisualMap,
368        new_id: FrameId,
369    ) -> Vec<(SparseFactorKey, usize, f32)> {
370        let Some(new_keyframe) = map.keyframes.get(&new_id) else {
371            return Vec::new();
372        };
373        let Some(new_position) = new_keyframe
374            .frame
375            .pose
376            .as_ref()
377            .map(|pose| pose.camera_center_world())
378        else {
379            return Vec::new();
380        };
381        let previous = self
382            .keyframe_order
383            .iter()
384            .copied()
385            .filter(|id| *id != new_id)
386            .collect::<Vec<_>>();
387        let temporal_ids = previous
388            .iter()
389            .rev()
390            .take(self.config.temporal_radius)
391            .copied()
392            .collect::<BTreeSet<_>>();
393        let mut proposals = Vec::new();
394        for other_id in temporal_ids.iter().copied() {
395            let (support, confidence) = pair_support(map, other_id, new_id, &self.config);
396            for (from, to) in [(other_id, new_id), (new_id, other_id)] {
397                proposals.push((
398                    SparseFactorKey {
399                        from_keyframe_id: from,
400                        to_keyframe_id: to,
401                        kind: SparseFactorKind::Temporal,
402                    },
403                    support,
404                    confidence,
405                ));
406            }
407        }
408
409        let mut proximity = previous
410            .iter()
411            .copied()
412            .filter(|id| !temporal_ids.contains(id))
413            .filter_map(|other_id| {
414                let other = map.keyframes.get(&other_id)?;
415                let distance =
416                    (other.frame.pose.as_ref()?.camera_center_world() - new_position).norm();
417                if distance > self.config.proximity_radius_meters {
418                    return None;
419                }
420                let (support, confidence) = pair_support(map, other_id, new_id, &self.config);
421                (support >= self.config.proximity_min_shared_landmarks)
422                    .then_some((other_id, support, confidence, distance))
423            })
424            .collect::<Vec<_>>();
425        proximity.sort_by(|left, right| {
426            right
427                .2
428                .total_cmp(&left.2)
429                .then_with(|| right.1.cmp(&left.1))
430                .then_with(|| left.3.total_cmp(&right.3))
431                .then_with(|| left.0.cmp(&right.0))
432        });
433        proximity.truncate(self.config.max_proximity_neighbors_per_keyframe);
434        for (other_id, support, confidence, _) in proximity {
435            for (from, to) in [(other_id, new_id), (new_id, other_id)] {
436                proposals.push((
437                    SparseFactorKey {
438                        from_keyframe_id: from,
439                        to_keyframe_id: to,
440                        kind: SparseFactorKind::Proximity,
441                    },
442                    support,
443                    confidence,
444                ));
445            }
446        }
447
448        let stereo = map
449            .stereo_observations
450            .iter()
451            .filter(|observation| observation.frame_id == new_id)
452            .count();
453        if stereo > 0 {
454            let confidence = support_confidence(stereo, 1.0, &self.config);
455            proposals.push((
456                SparseFactorKey {
457                    from_keyframe_id: new_id,
458                    to_keyframe_id: new_id,
459                    kind: SparseFactorKind::Stereo,
460                },
461                stereo,
462                confidence,
463            ));
464        }
465        proposals
466    }
467
468    fn rescore_existing(&mut self, map: &VisualMap, stats: &mut SparseFactorGraphUpdateStats) {
469        let active_window = self.active_keyframe_ids();
470        for factor in self.factors.values_mut() {
471            let (support, confidence) = match factor.key.kind {
472                SparseFactorKind::Stereo => {
473                    let count = map
474                        .stereo_observations
475                        .iter()
476                        .filter(|observation| observation.frame_id == factor.key.from_keyframe_id)
477                        .count();
478                    (count, support_confidence(count, 1.0, &self.config))
479                }
480                SparseFactorKind::Temporal | SparseFactorKind::Proximity => pair_support(
481                    map,
482                    factor.key.from_keyframe_id,
483                    factor.key.to_keyframe_id,
484                    &self.config,
485                ),
486            };
487            factor.support_count = support;
488            factor.confidence = confidence;
489            factor.last_scored_generation = self.generation;
490            if confidence < self.config.minimum_active_confidence {
491                factor.low_confidence_streak = factor.low_confidence_streak.saturating_add(1);
492            } else {
493                factor.low_confidence_streak = 0;
494            }
495            let confidence_prunable = factor.key.kind != SparseFactorKind::Temporal
496                || !self.config.protect_temporal_from_confidence_pruning;
497            if factor.state == SparseFactorState::Active
498                && confidence_prunable
499                && factor.low_confidence_streak >= self.config.low_confidence_patience
500            {
501                factor.state = SparseFactorState::Inactive;
502                factor.inactive_reason = Some(SparseFactorInactiveReason::LowConfidence);
503                factor.inactive_since_generation = Some(self.generation);
504                stats.inactivated_low_confidence += 1;
505            } else if factor.state == SparseFactorState::Inactive
506                && factor.inactive_reason == Some(SparseFactorInactiveReason::LowConfidence)
507                && confidence >= self.config.reactivation_confidence
508                && (active_window.contains(&factor.key.from_keyframe_id)
509                    || active_window.contains(&factor.key.to_keyframe_id))
510            {
511                factor.state = SparseFactorState::Active;
512                factor.inactive_reason = None;
513                factor.inactive_since_generation = None;
514                factor.low_confidence_streak = 0;
515                stats.reactivated += 1;
516            }
517        }
518    }
519
520    fn active_keyframe_ids(&self) -> BTreeSet<FrameId> {
521        self.keyframe_order
522            .iter()
523            .rev()
524            .take(self.config.active_window_keyframes)
525            .copied()
526            .collect()
527    }
528
529    fn retire_outside_active_window(&mut self, stats: &mut SparseFactorGraphUpdateStats) {
530        let active = self.active_keyframe_ids();
531        for factor in self.factors.values_mut() {
532            if factor.state == SparseFactorState::Active
533                && !active.contains(&factor.key.from_keyframe_id)
534                && !active.contains(&factor.key.to_keyframe_id)
535            {
536                factor.state = SparseFactorState::Inactive;
537                factor.inactive_reason = Some(SparseFactorInactiveReason::WindowAge);
538                factor.inactive_since_generation = Some(self.generation);
539                stats.inactivated_window_age += 1;
540            }
541        }
542    }
543
544    fn enforce_active_budget(&mut self, stats: &mut SparseFactorGraphUpdateStats) {
545        let active_count = self.active_factors().count();
546        if active_count <= self.config.max_active_factors {
547            return;
548        }
549        let mut candidates = self
550            .factors
551            .values()
552            .filter(|factor| factor.state == SparseFactorState::Active)
553            .map(|factor| {
554                let protected = matches!(
555                    factor.key.kind,
556                    SparseFactorKind::Temporal | SparseFactorKind::Stereo
557                );
558                (
559                    factor.key,
560                    protected,
561                    factor.confidence,
562                    factor.created_generation,
563                )
564            })
565            .collect::<Vec<_>>();
566        candidates.sort_by(|left, right| {
567            left.1
568                .cmp(&right.1)
569                .then_with(|| left.2.total_cmp(&right.2))
570                .then_with(|| left.3.cmp(&right.3))
571                .then_with(|| left.0.cmp(&right.0))
572        });
573        let retire_count = active_count - self.config.max_active_factors;
574        for (key, _, _, _) in candidates.into_iter().take(retire_count) {
575            if let Some(factor) = self.factors.get_mut(&key) {
576                factor.state = SparseFactorState::Inactive;
577                factor.inactive_reason = Some(SparseFactorInactiveReason::ActiveBudget);
578                factor.inactive_since_generation = Some(self.generation);
579                stats.inactivated_budget += 1;
580            }
581        }
582    }
583
584    fn prune_stale_inactive(&mut self, stats: &mut SparseFactorGraphUpdateStats) {
585        let before = self.factors.len();
586        self.factors.retain(|_, factor| {
587            factor.state == SparseFactorState::Active
588                || factor.inactive_since_generation.is_some_and(|since| {
589                    self.generation.saturating_sub(since)
590                        <= self.config.max_inactive_age_generations
591                })
592        });
593        stats.pruned = before - self.factors.len();
594    }
595
596    fn fill_counts(&self, stats: &mut SparseFactorGraphUpdateStats) {
597        for factor in self.factors.values() {
598            match (factor.state, factor.key.kind) {
599                (SparseFactorState::Inactive, _) => stats.inactive += 1,
600                (SparseFactorState::Active, SparseFactorKind::Temporal) => {
601                    stats.active_temporal += 1
602                }
603                (SparseFactorState::Active, SparseFactorKind::Proximity) => {
604                    stats.active_proximity += 1
605                }
606                (SparseFactorState::Active, SparseFactorKind::Stereo) => stats.active_stereo += 1,
607            }
608        }
609    }
610}
611
612fn pair_support(
613    map: &VisualMap,
614    left_id: FrameId,
615    right_id: FrameId,
616    config: &SparseFactorGraphConfig,
617) -> (usize, f32) {
618    let (Some(left), Some(right)) = (map.keyframes.get(&left_id), map.keyframes.get(&right_id))
619    else {
620        return (0, 0.0);
621    };
622    let left_by_landmark = left
623        .observations
624        .iter()
625        .map(|observation| (observation.landmark_id, observation))
626        .collect::<BTreeMap<LandmarkId, &Observation>>();
627    let mut confidence_sum = 0.0f32;
628    let mut support = 0usize;
629    for right_observation in &right.observations {
630        let Some(left_observation) = left_by_landmark.get(&right_observation.landmark_id) else {
631            continue;
632        };
633        let left_confidence = map.observation_confidence(left_observation).unwrap_or(1.0);
634        let right_confidence = map.observation_confidence(right_observation).unwrap_or(1.0);
635        confidence_sum += (left_confidence * right_confidence).max(0.0).sqrt();
636        support += 1;
637    }
638    let mean_confidence = if support == 0 {
639        0.0
640    } else {
641        confidence_sum / support as f32
642    };
643    (
644        support,
645        support_confidence(support, mean_confidence, config),
646    )
647}
648
649fn support_confidence(
650    support: usize,
651    mean_observation_confidence: f32,
652    config: &SparseFactorGraphConfig,
653) -> f32 {
654    let support_score = (support as f32 / config.support_saturation_count as f32).clamp(0.0, 1.0);
655    (support_score * mean_observation_confidence).clamp(0.0, 1.0)
656}
657
658#[cfg(test)]
659mod tests {
660    use nalgebra::{Point2, Point3, UnitQuaternion, Vector3};
661    use visloc_core::{
662        geometry::{Pose, SE3},
663        types::{Frame, Keyframe, Landmark, Observation, StereoObservation, VisualMap},
664    };
665
666    use super::*;
667
668    fn add_keyframe(map: &mut VisualMap, id: u64, x: f64, landmarks: &[u64]) {
669        let mut frame = Frame::new(id, 0);
670        frame.pose = Some(Pose {
671            world_to_camera: SE3::new(UnitQuaternion::identity(), Vector3::new(-x, 0.0, 0.0)),
672        });
673        let mut keyframe = Keyframe {
674            frame,
675            observations: Vec::new(),
676        };
677        for (keypoint_index, landmark_id) in landmarks.iter().copied().enumerate() {
678            keyframe.observations.push(Observation {
679                frame_id: id,
680                landmark_id,
681                keypoint_index,
682                xy: Point2::new(keypoint_index as f64, 0.0),
683            });
684            let landmark = map
685                .landmarks
686                .entry(landmark_id)
687                .or_insert_with(|| Landmark::new(landmark_id, Point3::new(0.0, 0.0, 4.0)));
688            landmark
689                .observations
690                .push(keyframe.observations.last().unwrap().clone());
691        }
692        map.keyframes.insert(id, keyframe);
693    }
694
695    fn config() -> SparseFactorGraphConfig {
696        SparseFactorGraphConfig {
697            temporal_radius: 1,
698            active_window_keyframes: 3,
699            proximity_radius_meters: 5.0,
700            proximity_min_shared_landmarks: 2,
701            max_proximity_neighbors_per_keyframe: 3,
702            support_saturation_count: 2,
703            minimum_active_confidence: 0.25,
704            reactivation_confidence: 0.5,
705            low_confidence_patience: 2,
706            max_active_factors: 32,
707            max_inactive_age_generations: 10,
708            protect_temporal_from_confidence_pruning: true,
709            geometric_damping: 1.0e-4,
710        }
711    }
712
713    #[test]
714    fn proposes_bidirectional_temporal_proximity_and_stereo_factors() {
715        let mut map = VisualMap::new();
716        add_keyframe(&mut map, 0, 0.0, &[1, 2]);
717        add_keyframe(&mut map, 1, 0.1, &[1, 2]);
718        add_keyframe(&mut map, 2, 0.2, &[1, 2]);
719        map.stereo_observations.push(StereoObservation {
720            frame_id: 2,
721            landmark_id: 1,
722            right_camera_id: 1,
723            xy_right: Point2::new(1.0, 1.0),
724            left_to_right: SE3::identity(),
725        });
726        let mut graph = SparseFactorGraph::new(config());
727        graph.update_from_map(&map, 0);
728        graph.update_from_map(&map, 1);
729        let stats = graph.update_from_map(&map, 2);
730        assert_eq!(stats.active_temporal, 4);
731        assert_eq!(stats.active_proximity, 2);
732        assert_eq!(stats.active_stereo, 1);
733        assert!(graph
734            .factor(SparseFactorKey {
735                from_keyframe_id: 0,
736                to_keyframe_id: 2,
737                kind: SparseFactorKind::Proximity,
738            })
739            .is_some());
740    }
741
742    #[test]
743    fn retires_old_edges_but_keeps_them_for_broader_recovery() {
744        let mut map = VisualMap::new();
745        let mut graph = SparseFactorGraph::new(SparseFactorGraphConfig {
746            active_window_keyframes: 2,
747            ..config()
748        });
749        for id in 0..4 {
750            add_keyframe(&mut map, id, id as f64 * 10.0, &[1, 2]);
751            graph.update_from_map(&map, id);
752        }
753        let key = SparseFactorKey {
754            from_keyframe_id: 0,
755            to_keyframe_id: 1,
756            kind: SparseFactorKind::Temporal,
757        };
758        assert_eq!(
759            graph.factor(key).unwrap().state,
760            SparseFactorState::Inactive
761        );
762        assert!(graph
763            .broader_recovery_candidates(0, 4)
764            .iter()
765            .any(|f| f.key == key));
766    }
767
768    #[test]
769    fn low_confidence_proximity_factor_is_inactivated_after_patience() {
770        let mut map = VisualMap::new();
771        add_keyframe(&mut map, 0, 0.0, &[1, 2]);
772        add_keyframe(&mut map, 1, 0.1, &[1, 2]);
773        add_keyframe(&mut map, 2, 0.2, &[1, 2]);
774        let mut graph = SparseFactorGraph::new(config());
775        graph.update_from_map(&map, 0);
776        graph.update_from_map(&map, 1);
777        graph.update_from_map(&map, 2);
778        let key = SparseFactorKey {
779            from_keyframe_id: 0,
780            to_keyframe_id: 2,
781            kind: SparseFactorKind::Proximity,
782        };
783        map.keyframes.get_mut(&0).unwrap().observations.clear();
784        graph.update_from_map(&map, 2);
785        graph.update_from_map(&map, 2);
786        assert_eq!(
787            graph.factor(key).unwrap().state,
788            SparseFactorState::Inactive
789        );
790    }
791
792    #[test]
793    fn measurement_update_is_numeric_and_optimizer_facing() {
794        let mut map = VisualMap::new();
795        add_keyframe(&mut map, 0, 0.0, &[1, 2]);
796        add_keyframe(&mut map, 1, 0.1, &[1, 2]);
797        let mut graph = SparseFactorGraph::new(config());
798        graph.update_from_map(&map, 0);
799        graph.update_from_map(&map, 1);
800        let key = SparseFactorKey {
801            from_keyframe_id: 0,
802            to_keyframe_id: 1,
803            kind: SparseFactorKind::Temporal,
804        };
805        assert!(graph.update_measurement(
806            key,
807            SparseFactorMeasurement {
808                target_correction_px: [0.4, -0.2],
809                information: [0.8, 0.3],
810                damping: 0.01,
811            }
812        ));
813        assert_eq!(
814            graph.factor(key).unwrap().measurement.information,
815            [0.8, 0.3]
816        );
817        assert!(!graph.update_measurement(
818            key,
819            SparseFactorMeasurement {
820                target_correction_px: [f32::NAN, 0.0],
821                information: [1.0, 1.0],
822                damping: 0.0,
823            }
824        ));
825    }
826
827    #[test]
828    fn confidence_uses_shared_observation_scores() {
829        let mut map = VisualMap::new();
830        add_keyframe(&mut map, 0, 0.0, &[1, 2]);
831        add_keyframe(&mut map, 1, 0.1, &[1, 2]);
832        let observations = map.keyframes[&1].observations.clone();
833        for observation in observations {
834            assert!(map.set_observation_confidence(&observation, 0.25));
835        }
836        let mut graph = SparseFactorGraph::new(config());
837        graph.update_from_map(&map, 0);
838        graph.update_from_map(&map, 1);
839        let factor = graph
840            .factor(SparseFactorKey {
841                from_keyframe_id: 0,
842                to_keyframe_id: 1,
843                kind: SparseFactorKind::Temporal,
844            })
845            .unwrap();
846        assert!((factor.confidence - 0.5).abs() < 1.0e-6);
847    }
848
849    #[test]
850    fn budget_retired_factor_does_not_thrash_back_on_ordinary_rescore() {
851        let mut map = VisualMap::new();
852        add_keyframe(&mut map, 0, 0.0, &[1, 2]);
853        add_keyframe(&mut map, 1, 0.1, &[1, 2]);
854        add_keyframe(&mut map, 2, 0.2, &[1, 2]);
855        let mut graph = SparseFactorGraph::new(SparseFactorGraphConfig {
856            max_active_factors: 1,
857            ..config()
858        });
859        graph.update_from_map(&map, 0);
860        graph.update_from_map(&map, 1);
861        let retired_key = graph
862            .inactive_factors()
863            .find(|factor| factor.inactive_reason == Some(SparseFactorInactiveReason::ActiveBudget))
864            .unwrap()
865            .key;
866
867        let stats = graph.update_from_map(&map, 2);
868
869        assert_eq!(stats.reactivated, 0);
870        let retired = graph.factor(retired_key).unwrap();
871        assert_eq!(retired.state, SparseFactorState::Inactive);
872        assert_eq!(
873            retired.inactive_reason,
874            Some(SparseFactorInactiveReason::ActiveBudget)
875        );
876    }
877}