Skip to main content

visloc_slam/bundle/
mod.rs

1//! Bundle adjustment with Schur-complement landmark elimination.
2//!
3//! Optimizes camera poses jointly with landmark positions to minimize the
4//! sum of squared 2D reprojection residuals. Pinhole intrinsics are held
5//! fixed; the variables are pose `T_world_to_camera` (6 DoF, right
6//! perturbation `T 竊・T ツキ Exp(ホセ)` with `ホセ = [マ・ マ云`) per non-fixed pose
7//! and `X_w` (3 DoF) per non-fixed landmark.
8//!
9//! The Schur complement of the block-diagonal landmark Hessian `H_LL`
10//! reduces the linear system to one of pose-only size `(6P) テ・(6P)` per
11//! iteration, regardless of how many landmarks the scene has, then
12//! back-substitutes for the landmark updates. Each iteration is a
13//! Levenberg-Marquardt step with optional cost-rejection.
14//!
15//! Gauge fixing is the caller's responsibility: monocular BA has 7 DoF
16//! gauge freedom (6 SE(3) + 1 scale). At minimum fix the first pose
17//! (anchor) and one of the following to remove scale: a second pose, a
18//! second landmark, or a known-distance pair. Rectified-stereo BA (any
19//! [`BaStereoObservation`] present) has only 6 DoF gauge freedom 窶・the
20//! baseline anchors metric scale 窶・so a single fixed pose is enough.
21//!
22//! # Parallelism
23//!
24//! [`BaConfig::parallel`] (default `false`, so [`BundleAdjustment::optimize`]
25//! and friends are unchanged unless a caller opts in) parallelizes the three
26//! per-item hot loops of [`BundleAdjustment::optimize_weighted`]'s
27//! Levenberg-Marquardt iteration with `rayon`:
28//!
29//! - **Assembly** (`build_normal_equations`'s monocular observation loop):
30//!   each observation's residual/Jacobian is a pure function of the current
31//!   pose and landmark estimate 窶・it touches no shared state 窶・so it is
32//!   computed on the rayon pool in fixed-size chunks
33//!   ([`PARALLEL_OBSERVATION_CHUNK`]), collected into a plain per-chunk
34//!   `Vec`; the actual `+=` scatter into `h_pp` / `b_p` / the per-landmark
35//!   blocks stays a single serial pass over each chunk's precomputed
36//!   contributions, *in the original per-observation order*.
37//! - **Schur reduction** (`solve_step`'s per-landmark `S -= H_PL H_LL竅サツケ
38//!   H_PL盞€` loop): each landmark's `3テ・` factorization is independent and
39//!   computed directly in parallel (disjoint output slots, no merge needed);
40//!   the pose-pair contributions it produces are computed the same chunked
41//!   way as assembly, collecting each landmark's `(Vec<(p,q,block)>,
42//!   Vec<(p,upd)>)` pair per chunk and then flattening/merging into the
43//!   shared reduced system `s` / `b_reduced` by a serial pass over each
44//!   chunk, in landmark-ascending order. Pure-visual sparse BA instead keeps
45//!   this stage serial so parallel observation assembly does not force a
46//!   dense camera Hessian or change the block-sparse O(nnz) memory bound.
47//! - **Back-substitution** (`solve_step`'s per-landmark `δ_L` loop): each
48//!   landmark writes only its own 3 rows of `delta_l`, so this is
49//!   embarrassingly parallel with no merge step at all.
50//!
51//! Unlike [`crate::block_cholesky`]'s intra-column path 窶・which reassociates
52//! a floating-point sum across contributors and is therefore only
53//! deterministic *to rounding* 窶・every merge here reproduces the exact
54//! summation order the serial code would have used, so the parallel path is
55//! bit-identical to the serial one at any thread count or chunk size; the
56//! chunk constants below exist only to cap peak memory (a full-sequence BA
57//! can carry tens of millions of observations, so materializing one
58//! contribution per observation up front is not an option) and to amortize
59//! the per-dispatch rayon overhead, never to change the result. Each path is
60//! also work-gated ([`PARALLEL_MIN_OBSERVATIONS`], [`PARALLEL_MIN_LANDMARKS`])
61//! so small problems stay on the plain serial loop even with the flag on,
62//! matching `block_cholesky`'s `PARALLEL_MIN_BLOCKS` precedent.
63//!
64//! Not parallelized: [`BundleAdjustment::optimize_joint_intrinsics`]'s own
65//! Schur reduction (a separate, less-used code path 窶・self-calibration BA is
66//! opt-in and typically run on far smaller problems than a full-sequence
67//! pose/structure solve) and the cost-evaluation passes (`robust_cost_weighted`
68//! / `reprojection_squared_residuals`, shared by many callers beyond the LM
69//! loop, so gating them on `BaConfig` would require threading the flag
70//! through call sites that have nothing to do with this optimizer).
71
72use std::collections::{BTreeMap, BTreeSet};
73use std::fmt::Write as _;
74use std::ops::{Index, IndexMut};
75
76use nalgebra::{
77    DMatrix, DVector, Matrix2x3, Matrix2x4, Matrix2x6, Matrix3, Matrix3x4, Matrix3x6, Matrix4x3,
78    Matrix4x6, Matrix6, Matrix6x3, Point2, Point3, Vector2, Vector3, Vector4, Vector6,
79};
80
81use visloc_core::geometry::{Pose, SE3, SO3};
82use visloc_core::types::{Camera, CameraModel, VisualMap};
83use visloc_mapping::{
84    LocalMapWindow, LocalRefinementReason, LocalRefinementResult, LocalRefiner, StagedMapUpdate,
85};
86
87use crate::gnc::{GncConfig, GncState};
88use crate::imu_preintegration::ImuPreintegrationFactor;
89use crate::process_memory::log as log_process_memory;
90use crate::{solve_normal_equations, LinearSolver, PoseGraphError, RobustKernel};
91
92mod debug;
93mod jacobians;
94mod joint_intrinsics;
95mod lm;
96mod matrix_free;
97mod normal_equations;
98mod optimize;
99mod problem;
100mod sqrt_qr;
101
102use debug::*;
103pub(crate) use jacobians::*;
104use lm::*;
105use matrix_free::*;
106use normal_equations::*;
107pub use sqrt_qr::*;
108
109#[cfg(test)]
110mod schur_block_debug_tests;
111
112#[cfg(test)]
113mod generalized_rig_factor_tests;
114
115/// Convert optional normalized matcher confidences into relative BA
116/// information weights without changing the visual factor group's mean scale.
117///
118/// Learned match probabilities are not calibrated inverse variances. Feeding
119/// them directly into tight VI-BA would weaken the entire visual block against
120/// the physically whitened IMU block. Explicit scores are therefore divided
121/// by their own finite mean; observations without a score stay at `1`.
122/// Returns `None` when no valid confidence signal is present.
123pub(crate) fn relative_observation_confidence_weights(
124    confidences: impl IntoIterator<Item = Option<f32>>,
125) -> Option<Vec<f64>> {
126    let confidences = confidences
127        .into_iter()
128        .map(|confidence| {
129            confidence.filter(|value| value.is_finite() && (0.0..=1.0).contains(value))
130        })
131        .collect::<Vec<_>>();
132    let explicit = confidences.iter().flatten().copied().collect::<Vec<_>>();
133    if explicit.is_empty() {
134        return None;
135    }
136    let mean = explicit.iter().map(|value| *value as f64).sum::<f64>() / explicit.len() as f64;
137    if !mean.is_finite() || mean <= 0.0 {
138        return None;
139    }
140    Some(
141        confidences
142            .into_iter()
143            .map(|confidence| confidence.map_or(1.0, |value| value as f64 / mean))
144            .collect(),
145    )
146}
147
148/// FEJ-style dense Gaussian prior over one or more navigation states.
149///
150/// Each keyframe contributes `[pose(6), velocity(3), bias(6)]` in that order.
151/// `information`, `gradient`, and `constant_cost` describe the quadratic at
152/// `reference`: `c + 2 g^T dx + dx^T H dx`. Pose deltas use the same right
153/// perturbation as BA, `T = T_ref Exp(dx)`. Keeping the reference fixed avoids
154/// silently changing the linearisation point as a fixed-lag window slides.
155#[derive(Debug, Clone, PartialEq)]
156pub struct NavigationStatePrior {
157    pub keyframe_ids: Vec<u64>,
158    pub reference_poses: BTreeMap<u64, Pose>,
159    pub reference_velocities: BTreeMap<u64, Vector3<f64>>,
160    pub reference_biases: BTreeMap<u64, Vector6<f64>>,
161    pub information: DMatrix<f64>,
162    pub gradient: DVector<f64>,
163    pub constant_cost: f64,
164}
165
166impl NavigationStatePrior {
167    pub fn is_well_formed(&self) -> bool {
168        let dim = self.keyframe_ids.len() * 15;
169        self.information.nrows() == dim
170            && self.information.ncols() == dim
171            && self.gradient.len() == dim
172            && self.constant_cost.is_finite()
173            && self.information.iter().all(|value| value.is_finite())
174            && self.gradient.iter().all(|value| value.is_finite())
175            && self.keyframe_ids.iter().all(|id| {
176                self.reference_poses.contains_key(id)
177                    && self.reference_velocities.contains_key(id)
178                    && self.reference_biases.contains_key(id)
179            })
180    }
181}
182
183#[derive(Debug, Clone, PartialEq)]
184pub(crate) struct NavigationLinearization {
185    pub pose_ids: Vec<u64>,
186    pub velocity_ids: Vec<u64>,
187    pub bias_ids: Vec<u64>,
188    pub information: DMatrix<f64>,
189    pub gradient: DVector<f64>,
190}
191
192/// One 2D image-point measurement linking a keyframe to a landmark.
193#[derive(Debug, Clone, PartialEq)]
194pub struct BaObservation {
195    pub keyframe_id: u64,
196    pub landmark_id: u64,
197    /// Pixel coordinates `(u, v)` in the keyframe's image.
198    pub xy: Point2<f64>,
199}
200
201/// One rectified-stereo measurement linking a keyframe to a landmark. The
202/// keyframe's pose is the LEFT camera's `T_world_to_camera`. The right camera
203/// is assumed rectified: shared intrinsics, optical axes parallel, and image
204/// rows aligned, so the right pixel only needs its horizontal coordinate
205/// (`v_r = v_l`). The shared baseline lives on [`BundleAdjustment`].
206///
207/// Compared with two independent [`BaObservation`]s for the left and right
208/// pixel, a single [`BaStereoObservation`] (i) avoids carrying a separate
209/// right-camera pose (it is implicitly the left's translated by `bツキxフA) and
210/// (ii) couples the two residuals through the same landmark variable, which
211/// is the standard rectified-stereo BA formulation.
212#[derive(Debug, Clone, PartialEq)]
213pub struct BaStereoObservation {
214    pub keyframe_id: u64,
215    pub landmark_id: u64,
216    /// Left-image pixel coordinates `(u_l, v_l)`.
217    pub xy: Point2<f64>,
218    /// Right-image horizontal pixel coordinate `u_r`. The vertical coordinate
219    /// `v_r` is taken to equal `xy.y` (rectified-stereo assumption).
220    pub u_right: f64,
221}
222
223/// One calibrated, non-rectified stereo observation. The keyframe pose is the
224/// left camera's `T_left<-world`; `left_to_right` is the fixed rig transform
225/// `T_right<-left`. Unlike [`BaStereoObservation`], both right-image
226/// coordinates and the right camera intrinsics are retained, so rigs with a
227/// rotational cam0/cam1 extrinsic (including EuRoC) contribute their true
228/// four-dimensional reprojection residual.
229#[derive(Debug, Clone, PartialEq)]
230pub struct BaGeneralStereoObservation {
231    pub keyframe_id: u64,
232    pub landmark_id: u64,
233    pub xy_left: Point2<f64>,
234    pub xy_right: Point2<f64>,
235    pub right_camera: Camera,
236    pub left_to_right: SE3,
237}
238
239/// One observation from an arbitrary sensor rigidly attached to a shared rig
240/// frame. `poses[keyframe_id]` stores `T_rig<-world`; the fixed extrinsic is
241/// `T_sensor<-rig`. This is the non-central counterpart of
242/// [`BaObservation`] and allows every sensor pixel to constrain one body pose
243/// without requiring a same-landmark observation in a designated left camera.
244#[derive(Debug, Clone, PartialEq)]
245pub struct BaRigObservation {
246    pub keyframe_id: u64,
247    pub landmark_id: u64,
248    pub xy: Point2<f64>,
249    pub camera: Camera,
250    pub sensor_from_rig: SE3,
251}
252
253/// Rotation-alignment gravity prior on every non-fixed pose.
254///
255/// Adds a 3-vector residual `r = R_wc ツキ g_world 竏・g_camera_observed` per
256/// pose, where `R_wc` is the pose's world-to-camera rotation and the two
257/// gravity vectors are caller-supplied. The most common use is a level
258/// prior: set both vectors to the same down-direction (e.g.
259/// `(0, 9.81, 0)` for a KITTI-style y-down camera that starts level)
260/// and the optimiser will resist pitch / roll drift that re-projection
261/// residuals cannot disambiguate on coplanar-feature scenes.
262///
263/// This prior constrains ROTATION only. Pure-translation drift (such as
264/// the structural vertical bias on KITTI sequence 08, where the camera
265/// rotation already matches ground truth) is NOT corrected by this
266/// prior 窶・that would require a translation/altitude prior fed from
267/// IMU velocity or GNSS, which lives outside [`BundleAdjustment`] in
268/// its current form.
269#[derive(Debug, Clone, PartialEq)]
270pub struct GravityPrior {
271    /// Gravity direction in world frame. Magnitude defines the
272    /// residual's natural scale; using the physical 9.81 m/sツイ keeps the
273    /// per-pose residual in the same order of magnitude as a pixel
274    /// reprojection residual, so a default Huber `delta 竕・3` does not
275    /// over- or under-weight the prior.
276    pub g_world: Vector3<f64>,
277    /// Gravity direction observed (or assumed) in camera frame for
278    /// every pose. For a level prior this matches the camera-frame
279    /// direction of `g_world` at the anchor pose, e.g. `(0, 9.81, 0)`.
280    pub g_camera_observed: Vector3<f64>,
281    /// Scalar weight applied to the gravity contribution. The cost
282    /// added per pose is `weight ツキ 窶睦窶鳴イ` and the normal-equations
283    /// contribution is `weight ツキ J盞€ J` / `weight ツキ J盞€ r`. A weight of
284    /// `1.0` makes a 9.81 m/sツイ gravity residual count comparably to a
285    /// single 9.81 px reprojection residual; lower this for a softer
286    /// prior, raise it for a stiffer one.
287    pub weight: f64,
288}
289
290/// Per-keyframe observation of the gravity direction in camera
291/// coordinates. Each entry constrains
292/// `R_wc ツキ g_world 竕・g_camera_observed` at the named keyframe; the
293/// residual and Jacobian shape are identical to [`GravityPrior`]'s
294/// global pose-independent variant, except the observation is sourced
295/// per-keyframe rather than shared across all poses.
296///
297/// The intended source of `g_camera_observed` is an accelerometer
298/// sample (or a low-pass-filtered window of samples) at the keyframe
299/// timestamp, rotated into the camera frame via the body竊団amera
300/// extrinsic. Unlike [`PositionPrior`], which can leak ground-truth
301/// poses when fed from GNSS/INS-fused trajectories, a properly-
302/// generated per-keyframe gravity prior is a true online sensor
303/// observation 窶・the same signal a deployed VIO would consume.
304#[derive(Debug, Clone, PartialEq)]
305pub struct PerPoseGravityObservation {
306    /// Keyframe whose pose rotation is being constrained. The pose
307    /// must already be added to [`BundleAdjustment`]. Fixed poses
308    /// still contribute to the cost report but generate no Jacobian
309    /// rows because they have no Hessian slot.
310    pub keyframe_id: u64,
311    /// Observed gravity direction in camera frame at this keyframe.
312    /// Magnitude should match [`PerPoseGravityPrior::g_world`] (e.g.
313    /// `9.81 m/sツイ` for a physical accelerometer-derived observation),
314    /// so the per-pose residual stays in the same order of magnitude
315    /// as a pixel reprojection residual.
316    pub g_camera_observed: Vector3<f64>,
317    /// Per-observation stiffness multiplier applied on top of the
318    /// global [`PerPoseGravityPrior::weight`]. `1.0` is neutral;
319    /// raise to up-weight a high-confidence sample, lower to soften a
320    /// motion-contaminated one. Setting to `0.0` mutes the
321    /// observation entirely (useful for keeping all keyframe slots
322    /// while gating obviously bad samples).
323    pub weight: f64,
324}
325
326impl PerPoseGravityObservation {
327    /// Build an observation with the default neutral per-obs weight
328    /// (`1.0`). Use the public `weight` field directly when emitting
329    /// per-sample stiffness from a sensor model.
330    pub const fn new(keyframe_id: u64, g_camera_observed: Vector3<f64>) -> Self {
331        Self {
332            keyframe_id,
333            g_camera_observed,
334            weight: 1.0,
335        }
336    }
337}
338
339/// Per-keyframe gravity-alignment prior. Each
340/// [`PerPoseGravityObservation`] adds a rotation-domain residual at
341/// its keyframe; the prior as a whole shares a single world-frame
342/// gravity vector and stiffness.
343///
344/// This is the online-friendly companion to [`GravityPrior`] (single
345/// observation shared across all poses) 窶・it accepts per-keyframe
346/// observations rather than baking in a single "level-world" assumption.
347/// Use it when the body's pitch/roll varies meaningfully along the
348/// trajectory (climbing/descending on a slope, banking on a curve,
349/// etc.) so the gravity-in-camera-frame direction is no longer
350/// constant.
351///
352/// Like [`GravityPrior`], the prior constrains ROTATION only. Pure-
353/// translation drift (such as the structural vertical bias on KITTI
354/// sequence 08, where the camera rotation already matches ground
355/// truth) is NOT corrected by this prior.
356#[derive(Debug, Clone, PartialEq)]
357pub struct PerPoseGravityPrior {
358    /// Per-keyframe observations. May contain at most one entry per
359    /// `keyframe_id`; duplicates are accepted but each contributes
360    /// independently (the optimiser does not deduplicate).
361    pub observations: Vec<PerPoseGravityObservation>,
362    /// Gravity direction in world frame, shared across all
363    /// observations. Magnitude defines the residual's natural scale.
364    pub g_world: Vector3<f64>,
365    /// Global scalar weight applied to every observation's
366    /// contribution, multiplied with each observation's
367    /// [`PerPoseGravityObservation::weight`]. `weight = 1.0` plus
368    /// per-obs `1.0` makes a 9.81 m/sツイ gravity residual count
369    /// comparably to a single 9.81 px reprojection residual; lower
370    /// the global scale for a softer prior, raise for a stiffer one.
371    /// The per-observation field stays neutral unless the upstream
372    /// sensor model emits inverse-variance weights.
373    pub weight: f64,
374}
375
376impl PerPoseGravityPrior {
377    pub const fn new(g_world: Vector3<f64>, weight: f64) -> Self {
378        Self {
379            observations: Vec::new(),
380            g_world,
381            weight,
382        }
383    }
384
385    pub fn push(&mut self, observation: PerPoseGravityObservation) {
386        self.observations.push(observation);
387    }
388}
389
390/// One absolute position measurement for a single keyframe. The
391/// expected world-frame camera centre is compared against the BA's
392/// current estimate of `竏坦盞€ ツキ t`. Designed for translation-domain
393/// priors fed from GNSS, an external altimeter, or 窶・in evaluation
394/// scenarios 窶・ground-truth poses; the prior constrains TRANSLATION
395/// only, complementing [`GravityPrior`] which constrains ROTATION
396/// only.
397///
398/// `axis_weights` enables per-axis stiffness: a per-pose altitude
399/// constraint sets `axis_weights = (0, w, 0)` so only the vertical
400/// component is anchored (the most common shape for fixing seq08-style
401/// vertical drift without claiming horizontal GNSS accuracy).
402#[derive(Debug, Clone, PartialEq)]
403pub struct PositionPriorObservation {
404    /// Keyframe whose world camera centre is being constrained. The
405    /// pose must already be added to [`BundleAdjustment`]. Fixed poses
406    /// still contribute to the cost (for diagnostics) but generate no
407    /// Jacobian rows because they have no Hessian slot.
408    pub keyframe_id: u64,
409    /// Expected world-frame camera centre. For a level KITTI-style
410    /// y-down camera this is the same coordinate frame as
411    /// `pose.camera_center_world()`.
412    pub camera_center_world: Point3<f64>,
413    /// Per-axis weights in the cost `ホ」 w盞「 ツキ (C盞「 竏・target盞「)ツイ` and the
414    /// normal-equations contribution. A zero entry removes that axis
415    /// from the prior entirely; mixed positive entries pin a subset of
416    /// axes with different stiffnesses (`(0, w, 0)` for altitude-only).
417    pub axis_weights: Vector3<f64>,
418}
419
420/// A relative-pose constraint between two BA keyframes, e.g. an IMU
421/// pre-integration delta, a wheel-odometry tick, or an external
422/// pose-graph edge being lifted into BA.
423///
424/// At convergence the measurement equals the BA-implied relative pose
425/// `T_j ツキ T_i竅ア` (`world_to_camera_j` of the "to" keyframe composed with
426/// the inverse of the "from" keyframe). The residual is the SE(3) log
427/// of the disagreement:
428///
429/// ```text
430/// r = log(measurement竅サツケ ツキ T_j ツキ T_i竅ア)  竏・邃昶・
431/// ```
432///
433/// Jacobians under right-perturbation `T 竊・T ツキ exp(ホエ)`:
434///
435/// - `竏S / 竏ばエ_j =  Ad(T_i)`
436/// - `竏S / 竏ばエ_i = 竏但d(T_i)`
437///
438/// This is the same Jacobian shape used by
439/// `PoseGraph::optimize_se3_iterative`; the factor lifts those edges
440/// into [`BundleAdjustment`] so visual residuals and external-sensor
441/// pose deltas can be jointly optimised in a single LM solve. Full
442/// IMU pre-integration with velocity/bias states is a future
443/// extension; this v1 factor assumes the pre-integrator has already
444/// produced a single `(ホ廃, ホ燃)` pair plus a scalar weight.
445#[derive(Debug, Clone, PartialEq)]
446pub struct PairwisePoseFactor {
447    /// "From" keyframe id (the one Ad(T_from) is computed about).
448    pub keyframe_id_from: u64,
449    /// "To" keyframe id.
450    pub keyframe_id_to: u64,
451    /// Measured relative pose `T_meas` such that, at convergence,
452    /// `T_meas = T_j ツキ T_i竅ア` where `T_i` and `T_j` are the BA poses
453    /// for `keyframe_id_from` and `keyframe_id_to` respectively.
454    pub measurement: Pose,
455    /// Scalar weight (sqrt-information squared). The cost added is
456    /// `weight ツキ 窶睦窶鳴イ` so `weight = 1 / マδイ` for an isotropic
457    /// measurement with standard deviation `マチ (per-axis). Anisotropic
458    /// 6テ・ sqrt-information matrices are deferred to a future
459    /// extension.
460    pub weight: f64,
461}
462
463/// Bias random-walk factor between two keyframes' 6-vector IMU
464/// biases. Adds the residual `r = b_j 竏・b_i` with independent gyro and
465/// accelerometer weights. Use this to keep neighbouring
466/// keyframes' biases close to each other when the IMU factor's data-
467/// driven Jacobian leaves some bias DoFs unobservable in isolation
468/// (e.g., gyro biases on a straight-line trajectory).
469///
470/// Both endpoint biases must be registered via
471/// [`BundleAdjustment::add_bias`] for the factor to contribute. If
472/// either side has a non-fixed bias slot, the factor adds its 6テ・
473/// Jacobian (`J_i = 竏棚`, `J_j = I`) to the normal equations; fully-
474/// fixed endpoints still contribute to the cost report but no
475/// Jacobian rows.
476#[derive(Debug, Clone, PartialEq)]
477pub struct BiasRandomWalkFactor {
478    /// "From" keyframe id (the bias on the `竏棚` side of the Jacobian).
479    pub keyframe_id_from: u64,
480    /// "To" keyframe id (the bias on the `+I` side).
481    pub keyframe_id_to: u64,
482    /// Gyroscope-bias sqrt-information squared. A typical value is
483    /// `1 / (マダbgツイ ツキ ホ杯_ij)` for continuous random-walk density `マダbg`.
484    pub weight_gyro: f64,
485    /// Accelerometer-bias sqrt-information squared. A typical value is
486    /// `1 / (マダbaツイ ツキ ホ杯_ij)` for continuous random-walk density `マダba`.
487    pub weight_accel: f64,
488}
489
490/// A bundle of per-keyframe absolute position constraints.
491#[derive(Debug, Clone, PartialEq)]
492pub struct PositionPrior {
493    pub observations: Vec<PositionPriorObservation>,
494    /// When true, the camera-centre residual uses the full Jacobian
495    /// `[-I | [C_w]_x]`, so pose rotation updates can also move the
496    /// constrained centre. When false, the residual uses `[-I | 0]`
497    /// and acts as a translation-only centre prior. Keep this true for
498    /// the historical BA semantics; turn it off for sensor height/grade
499    /// priors that should not pull rotation away from visual evidence.
500    pub couple_rotation: bool,
501}
502
503impl PositionPrior {
504    pub const fn new() -> Self {
505        Self {
506            observations: Vec::new(),
507            couple_rotation: true,
508        }
509    }
510
511    pub const fn with_rotation_coupling(mut self, couple_rotation: bool) -> Self {
512        self.couple_rotation = couple_rotation;
513        self
514    }
515
516    pub fn push(&mut self, observation: PositionPriorObservation) {
517        self.observations.push(observation);
518    }
519}
520
521impl Default for PositionPrior {
522    fn default() -> Self {
523        Self::new()
524    }
525}
526
527/// Bundle-adjustment problem: poses, landmarks, observations, plus a single
528/// shared pinhole camera (multi-camera support is left as a future extension).
529#[derive(Debug, Clone, PartialEq)]
530pub struct BundleAdjustment {
531    pub poses: BTreeMap<u64, Pose>,
532    pub landmarks: BTreeMap<u64, Point3<f64>>,
533    pub observations: Vec<BaObservation>,
534    /// Rectified-stereo observations sharing [`Self::stereo_baseline`]. They
535    /// reference the same `poses` / `landmarks` collections as
536    /// [`Self::observations`], so a single landmark can have both monocular
537    /// and stereo evidence.
538    pub stereo_observations: Vec<BaStereoObservation>,
539    /// Calibrated non-rectified stereo observations. These use [`Self::camera`]
540    /// as the left camera and carry their right camera/extrinsic explicitly.
541    pub general_stereo_observations: Vec<BaGeneralStereoObservation>,
542    /// Arbitrary calibrated rig-sensor observations sharing the frame poses.
543    pub rig_observations: Vec<BaRigObservation>,
544    pub camera: Camera,
545    /// Pose ids whose `Pose` is held constant during optimization.
546    pub fixed_poses: BTreeSet<u64>,
547    /// Pose ids whose rotation is held constant while their translation may
548    /// still be optimized.  The six-dimensional pose slot is retained for
549    /// the Schur system, but the rotation rows/columns are constrained to
550    /// zero by [`Self::optimize`].  An empty set preserves the historical
551    /// pose/structure solve exactly.
552    pub fixed_pose_rotations: BTreeSet<u64>,
553    /// Landmark ids whose `Point3` is held constant during optimization.
554    pub fixed_landmarks: BTreeSet<u64>,
555    /// Rectified-stereo baseline in metric units. The right camera is at
556    /// `+stereo_baseline ツキ xフA of the left in the left-camera frame. Required
557    /// (positive, finite) when [`Self::stereo_observations`] is non-empty;
558    /// ignored otherwise. `None` means "monocular BA".
559    pub stereo_baseline: Option<f64>,
560    /// Optional rotation-alignment gravity prior. When `Some`, every
561    /// non-fixed pose contributes a 3-vector gravity-alignment residual
562    /// (see [`GravityPrior`]). Fixed poses are still included in the
563    /// cost report but do not generate Jacobian rows.
564    pub gravity_prior: Option<GravityPrior>,
565    /// Optional per-keyframe gravity-alignment prior. Like
566    /// [`Self::gravity_prior`] but the `g_camera_observed` varies per
567    /// observation, so the prior accepts e.g. accelerometer-derived
568    /// per-keyframe observations rather than a single shared level-
569    /// world assumption. See [`PerPoseGravityPrior`].
570    pub per_pose_gravity_prior: Option<PerPoseGravityPrior>,
571    /// Optional per-keyframe absolute position prior. Each observation
572    /// adds an axis-weighted residual `(C_w 竏・target)` with Jacobian
573    /// `[竏棚 | [C_w]_テ余` (right perturbation, xi-order `[マ・ マ云`). See
574    /// [`PositionPrior`].
575    pub position_prior: Option<PositionPrior>,
576    /// Pairwise relative-pose factors. Each factor lifts an external
577    /// relative-pose measurement (IMU pre-integration, wheel odometry,
578    /// loop-closure verification, etc.) into the BA solve. See
579    /// [`PairwisePoseFactor`].
580    pub pairwise_pose_factors: Vec<PairwisePoseFactor>,
581    /// Per-keyframe world-frame velocity state. Populated for the
582    /// keyframes that participate in any [`ImuPreintegrationFactor`]; the
583    /// optimiser jointly refines pose + velocity. Keyframes without an
584    /// IMU factor referencing them can leave their velocity slot empty
585    /// (the reprojection / pairwise pose / prior factors don't read it).
586    pub velocities: BTreeMap<u64, Vector3<f64>>,
587    /// Velocity ids held constant during optimisation (mirrors
588    /// [`Self::fixed_poses`] / [`Self::fixed_landmarks`]).
589    pub fixed_velocities: BTreeSet<u64>,
590    /// On-manifold IMU pre-integration factors. Each factor carries a
591    /// gravity-compensated `(ホ燃, ホ牌, ホ廃)` produced by
592    /// [`crate::imu_preintegration::ImuPreintegrator`] and binds two
593    /// keyframes' `(pose, velocity)` states with a 9-vector residual
594    /// `[r_R; r_v; r_p]` (Forster 2017 eq. 45-47). The optimiser
595    /// linearises the rotation residual via the SO(3) right-Jacobian
596    /// inverse.
597    pub imu_factors: Vec<ImuPreintegrationFactor>,
598    /// Rigid transform from the tracked camera/sensor frame into the IMU
599    /// body frame (`T_b<-c`, EuRoC `T_BS`). Visual residuals continue to use
600    /// the stored camera poses; IMU residuals compose this extrinsic to obtain
601    /// body poses. Identity preserves the historical co-located rig behavior.
602    pub imu_body_to_camera: SE3,
603    /// Per-keyframe IMU bias state, packing `(bias_gyro, bias_acc)` as a
604    /// 6-vector. Populated for the keyframes whose
605    /// [`ImuPreintegrationFactor`] should be bias-corrected (the
606    /// integration window from `i` to `j` uses `bias[i]` for its
607    /// first-order correction). Keyframes without an IMU factor
608    /// referencing them, or whose bias has not been registered, fall
609    /// back to using the integrator's linearisation bias (no
610    /// correction).
611    pub biases: BTreeMap<u64, Vector6<f64>>,
612    /// Bias ids held constant during optimisation (mirrors
613    /// [`Self::fixed_poses`] / [`Self::fixed_velocities`]).
614    pub fixed_biases: BTreeSet<u64>,
615    /// Bias random-walk priors between consecutive keyframes. See
616    /// [`BiasRandomWalkFactor`]; the cost contribution is
617    /// `weight ツキ 窶肪_j 竏・b_i窶鳴イ` and the Jacobian places `ツアI` against
618    /// each non-fixed bias slot.
619    pub bias_random_walk_factors: Vec<BiasRandomWalkFactor>,
620    /// Dense fixed-lag prior carried from the preceding VI window.
621    pub navigation_state_prior: Option<NavigationStatePrior>,
622}
623
624/// Configuration for [`BundleAdjustment::optimize`].
625#[derive(Debug, Clone, Copy, PartialEq)]
626pub struct BaConfig {
627    /// Reuse a rolled-back Legacy sparse pose-diagonal linearization. Keeps
628    /// one normal system plus O(P) undamped pose blocks; excludes dense paths.
629    pub reuse_rejected_pose_diagonal: bool,
630    pub max_iterations: usize,
631    pub initial_lambda: Option<f64>,
632    pub lambda_increase_factor: f64,
633    pub lambda_decrease_factor: f64,
634    pub max_lambda: f64,
635    pub min_lambda: f64,
636    pub step_tolerance: f64,
637    pub cost_tolerance: f64,
638    /// Optional relative accepted-cost-decrease stopping threshold.
639    ///
640    /// An accepted iteration converges when
641    /// `(cost_before - cost_after) / max(abs(cost_before), epsilon)` is below
642    /// this value. `None` preserves the historical absolute-cost and step-only
643    /// stopping rules.
644    pub relative_cost_tolerance: Option<f64>,
645    /// Linear-solver backend for the Schur-reduced pose system. The
646    /// landmark elimination is always done analytically via per-landmark
647    /// `3テ・` block inversion (since `H_LL` is block-diagonal).
648    pub linear_solver: LinearSolver,
649    /// Robust IRLS kernel applied per-observation to its squared
650    /// reprojection residual. [`RobustKernel::None`] runs standard
651    /// non-robust BA; `Huber` / `Cauchy` down-weight outliers so a small
652    /// number of bad correspondences cannot pull the solution away from
653    /// the inlier consensus.
654    pub robust_kernel: RobustKernel,
655    /// Also refine the shared pinhole intrinsics `(fx, fy, cx, cy)` **jointly**:
656    /// when set, [`BundleAdjustment::optimize`] carries the 4 intrinsics as extra
657    /// unknowns inside the Schur-complement camera system, co-estimated with the
658    /// poses and (eliminated) landmarks 窶・the COLMAP self-calibration formulation.
659    /// This is the lever for unknown / inaccurate calibration: a wrong fixed focal
660    /// forces a residual onto the poses, and the joint solve lets the camera absorb
661    /// it. (The coupled, landmark-eliminated gradient is what makes this work; an
662    /// alternating refinement against converged structure cannot move a wrong focal,
663    /// because the structure-fixed gradient is ~0.) Only [`CameraModel::Pinhole`]
664    /// and [`CameraModel::OpenCv`] (whose lens terms are held fixed unless
665    /// [`Self::refine_distortion`] is set) are refined; any other model falls
666    /// back to the pose/structure-only solve, which still uses its full lens
667    /// model. **`false` by default** (the public
668    /// [`BundleAdjustment::optimize`] is then bit-identical to before).
669    pub refine_intrinsics: bool,
670    /// Additionally self-calibrate the two radial-distortion coefficients
671    /// `(k1, k2)` jointly with the intrinsics (the camera block grows from 4 to 6).
672    /// Requires `refine_intrinsics`; only applies to a **monocular** pinhole
673    /// reconstruction (rectified stereo is already undistorted). The coefficients
674    /// are appended to `Camera::params` as `[fx, fy, cx, cy, k1, k2]`. **`false`
675    /// by default.**
676    ///
677    /// An [`CameraModel::OpenCv`] camera (`[fx, fy, cx, cy, k1, k2, p1, p2]`) is
678    /// refined in the same layout: its `(k1, k2)` are refined and its tangential
679    /// `(p1, p2)` stay fixed unless [`Self::refine_tangential_distortion`] is set.
680    pub refine_distortion: bool,
681    /// Additionally self-calibrate the tangential coefficients `(p1, p2)` (the
682    /// camera block grows from 6 to 8). Requires `refine_intrinsics` and
683    /// `refine_distortion`, and is ignored without them. A `Pinhole` camera is
684    /// promoted to [`CameraModel::OpenCv`] `[fx, fy, cx, cy, k1, k2, p1, p2]`
685    /// (starting from `p1 = p2 = 0`, which projects exactly like the radial
686    /// pinhole), since that is the layout that carries tangential terms.
687    /// Decentering is weakly observable and trades against the principal point
688    /// on small or forward-moving scenes, so it is opt-in. **`false` by
689    /// default** (the joint solve is then bit-identical to before).
690    pub refine_tangential_distortion: bool,
691    /// Constrain the refined focal length to `fx == fy` (one shared focal, as
692    /// COLMAP's `SIMPLE_*` / `RADIAL` models and every square-pixel sensor do).
693    /// Without it `fx` and `fy` move independently, which lets weakly
694    /// observable motion (e.g. near-pure forward translation) trade a spurious
695    /// aspect ratio against structure. The constraint is applied to the reduced
696    /// camera system (`fx`/`fy` rows and columns summed, the shared update
697    /// written to both), so the Jacobian builder is unchanged. Requires
698    /// `refine_intrinsics`; a camera whose `fx != fy` starts from their mean.
699    /// **`false` by default** (the joint solve is then bit-identical to before).
700    pub shared_focal: bool,
701    /// A Gaussian prior `(f0, sigma)`, in pixels, on `fx` and `fy` while
702    /// `refine_intrinsics` refines them: each adds `((f - f0) / sigma)^2` to
703    /// the cost, where a reprojection residual of one pixel adds 1. For a
704    /// focal length known well enough (a trusted EXIF value or a
705    /// calibration) on captures that observe it weakly, such as a street
706    /// circuited by car or bicycle. **`None` by default** (the joint solve is
707    /// then bit-identical to before).
708    pub focal_prior: Option<(f64, f64)>,
709    /// Run the per-observation assembly, per-landmark Schur reduction, and
710    /// back-substitution loops of [`BundleAdjustment::optimize_weighted`]'s
711    /// Levenberg-Marquardt iteration on the `rayon` pool (see the module's
712    /// "Parallelism" section). The result is bit-identical to the serial
713    /// path at any thread count 窶・this only changes *how* the normal
714    /// equations are computed, never the summation order 窶・so it is safe to
715    /// flip independently of everything else in this config. Small problems
716    /// stay serial even when this is set (see `PARALLEL_MIN_OBSERVATIONS` /
717    /// `PARALLEL_MIN_LANDMARKS`). Only consumed by `optimize_weighted`
718    /// (the plain pose/structure/IMU solve); `optimize_joint_intrinsics`
719    /// ignores it. **`false` by default** (the public
720    /// [`BundleAdjustment::optimize`] is then bit-identical to before).
721    pub parallel: bool,
722    /// Solve the pure-visual bundle adjustment with the matrix-free
723    /// implicit-Schur PCG backend (see [`BundleAdjustment::optimize_matrix_free`])
724    /// instead of the dense/sparse block-Cholesky Schur reduction.
725    ///
726    /// The default reduced pose system fills in when tracks are long, so one LM
727    /// linear solve becomes `O(pose^3)` and a large reconstruction can spend
728    /// hours in `linear_solve`. The matrix-free operator eliminates the
729    /// landmarks implicitly and its cost tracks the observation count.
730    /// Ineligible problems (intrinsics/distortion refinement, non-visual states
731    /// or priors, a fully fixed pose set, or a missing gauge anchor) fall back to
732    /// the ordinary solver, which keeps `true` safe as a general default-off
733    /// opt-in. **`false` by default** (the ordinary solve is then unchanged).
734    pub matrix_free_ba: bool,
735}
736
737impl Default for BaConfig {
738    fn default() -> Self {
739        Self {
740            reuse_rejected_pose_diagonal: false,
741            max_iterations: 20,
742            initial_lambda: Some(1e-4),
743            lambda_increase_factor: 10.0,
744            lambda_decrease_factor: 0.1,
745            max_lambda: 1e12,
746            min_lambda: 1e-9,
747            step_tolerance: 1e-7,
748            cost_tolerance: 1e-9,
749            relative_cost_tolerance: None,
750            linear_solver: LinearSolver::Dense,
751            robust_kernel: RobustKernel::None,
752            refine_intrinsics: false,
753            refine_distortion: false,
754            refine_tangential_distortion: false,
755            shared_focal: false,
756            focal_prior: None,
757            parallel: false,
758            matrix_free_ba: false,
759        }
760    }
761}
762
763#[derive(Debug, Clone, PartialEq)]
764pub struct BaIterationStats {
765    pub iteration: usize,
766    pub cost_before: f64,
767    pub cost_after: f64,
768    pub max_pose_step: f64,
769    pub max_landmark_step: f64,
770    pub lambda: f64,
771    pub step_accepted: bool,
772}
773
774#[derive(Debug, Clone, PartialEq)]
775pub struct BaResult {
776    pub initial_cost: f64,
777    pub final_cost: f64,
778    pub iterations: Vec<BaIterationStats>,
779    pub converged: bool,
780}
781
782/// Options for the opt-in matrix-free pure-visual BA entry point.
783///
784/// This is deliberately separate from [`BaConfig`]: adding a solver variant
785/// there would change the default path and would make existing callers
786/// accidentally opt into a new numerical backend.  The matrix-free entry
787/// point requires a finite, positive LM start value and uses PCG for each
788/// reduced pose solve.
789#[derive(Debug, Clone, Copy, PartialEq)]
790pub struct MatrixFreeBaOptions {
791    /// Maximum PCG iterations for one LM linear solve.
792    pub max_pcg_iterations: usize,
793    /// Relative PCG residual tolerance.
794    pub pcg_relative_tolerance: f64,
795    /// Absolute PCG residual tolerance.
796    pub pcg_absolute_tolerance: f64,
797}
798
799impl Default for MatrixFreeBaOptions {
800    fn default() -> Self {
801        Self {
802            max_pcg_iterations: 128,
803            pcg_relative_tolerance: 1.0e-12,
804            pcg_absolute_tolerance: 1.0e-12,
805        }
806    }
807}
808
809/// Options for the opt-in column-equilibrated matrix-free entry point.
810///
811/// The diagonal bounds are deliberately private fixed policy constants.  The
812/// nested PCG options reuse the existing matrix-free option shape without
813/// changing its defaults or adding a scaling switch to the legacy API.
814#[derive(Debug, Clone, Copy, Default, PartialEq)]
815pub struct MatrixFreeBaColumnScalingOptions {
816    pub pcg: MatrixFreeBaOptions,
817}
818
819/// Per-LM-iteration diagnostics returned by [`BundleAdjustment::optimize_matrix_free`].
820#[derive(Debug, Clone, PartialEq)]
821pub struct MatrixFreeBaIterationStats {
822    pub iteration: usize,
823    pub pcg_iterations: Option<usize>,
824    pub pcg_residual_norm: Option<f64>,
825    pub pcg_target: Option<f64>,
826    pub pcg_failure: Option<String>,
827}
828
829/// Result of the opt-in matrix-free BA run.
830#[derive(Debug, Clone, PartialEq)]
831pub struct MatrixFreeBaResult {
832    pub initial_cost: f64,
833    pub final_cost: f64,
834    pub iterations: Vec<BaIterationStats>,
835    pub matrix_free_iterations: Vec<MatrixFreeBaIterationStats>,
836    pub converged: bool,
837}
838
839/// Scalar accounting for one normal-system equilibration.  PCG residuals in
840/// the nested [`MatrixFreeBaResult`] are in scaled coordinates; physical pose
841/// and landmark step norms remain in its ordinary LM iteration statistics.
842#[derive(Debug, Clone, Copy, PartialEq)]
843pub struct MatrixFreeBaColumnScalingIterationStats {
844    pub iteration: usize,
845    /// Minimum of the clamped normal-equation diagonal values `d_j`, not of
846    /// the transforms `1/sqrt(d_j)`.
847    pub minimum_diagonal: f64,
848    /// Maximum of the clamped normal-equation diagonal values `d_j`, not of
849    /// the transforms `1/sqrt(d_j)`.
850    pub maximum_diagonal: f64,
851    pub clamped_to_minimum: usize,
852    pub clamped_to_maximum: usize,
853}
854
855/// Result of the opt-in column-equilibrated matrix-free BA run.
856#[derive(Debug, Clone, PartialEq)]
857pub struct MatrixFreeBaColumnScalingResult {
858    pub ba: MatrixFreeBaResult,
859    pub scaling_iterations: Vec<MatrixFreeBaColumnScalingIterationStats>,
860}
861
862/// Scalar per-LM-iteration accounting for adaptive column-scaled damping.
863/// Prediction is evaluated in the current scaled coordinates; it is not a
864/// full backward-error diagnostic and does not retain normal-equation state.
865#[derive(Debug, Clone, PartialEq)]
866pub struct MatrixFreeBaAdaptiveDampingIterationStats {
867    pub iteration: usize,
868    pub solve_lambda: f64,
869    pub next_lambda: f64,
870    pub predicted_undamped_squared_decrease: Option<f64>,
871    pub actual_cost_decrease: Option<f64>,
872    pub rho: Option<f64>,
873    pub cost_gate: Option<bool>,
874    pub feasibility_gate: Option<bool>,
875    pub nonprojectable_before: usize,
876    pub nonprojectable_after: Option<usize>,
877    pub accepted: bool,
878    pub reason: String,
879}
880
881/// Result of the opt-in adaptive column-scaled matrix-free BA run.
882#[derive(Debug, Clone, PartialEq)]
883pub struct MatrixFreeBaAdaptiveDampingResult {
884    pub ba: MatrixFreeBaResult,
885    pub scaling_iterations: Vec<MatrixFreeBaColumnScalingIterationStats>,
886    pub adaptive_iterations: Vec<MatrixFreeBaAdaptiveDampingIterationStats>,
887}
888
889/// Additive options for the bounded true-residual restart diagnostic.
890///
891/// `max_restarts_per_solve` is intentionally limited to zero or one.  The
892/// PCG iteration budget in [`MatrixFreeBaOptions`] is global to each reduced
893/// solve and is never reset by a restart.
894#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
895pub struct MatrixFreeBaRestartOptions {
896    pub max_restarts_per_solve: usize,
897}
898
899/// Per-LM-iteration diagnostics for the bounded restart entry point.
900#[derive(Debug, Clone, PartialEq)]
901pub struct MatrixFreeBaRestartIterationStats {
902    pub iteration: usize,
903    /// Total alpha iterations used by this PCG solve.  This value is never
904    /// reset when a residual restart occurs.
905    pub pcg_iterations: Option<usize>,
906    /// Number of explicit true-residual checks performed.
907    pub true_residual_rechecks: usize,
908    /// Number of those checks whose norm exceeded the configured target.  This
909    /// includes checks at the iteration cap; it is not a count of
910    /// restart-eligible checks.
911    pub failed_true_residual_rechecks: usize,
912    pub restarts: usize,
913    pub terminal_failure: Option<String>,
914}
915
916/// Result of [`BundleAdjustment::optimize_matrix_free_with_restart`].
917#[derive(Debug, Clone, PartialEq)]
918pub struct MatrixFreeBaRestartResult {
919    pub ba: MatrixFreeBaResult,
920    pub restart_iterations: Vec<MatrixFreeBaRestartIterationStats>,
921}
922
923/// Failure from the opt-in matrix-free pure-visual BA entry point.
924#[derive(Debug, Clone, PartialEq, Eq)]
925pub enum MatrixFreeBaError {
926    /// The problem contains a factor/state that the pure-visual operator does
927    /// not assemble (for example IMU, navigation, or a non-visual prior).
928    Ineligible(&'static str),
929    /// The matrix-free LM/PCG options are not finite or cannot make progress.
930    InvalidConfiguration(&'static str),
931    /// The existing BA input validation rejected the problem.
932    Ba(BaError),
933    /// The reduced operator or PCG solve failed.  The textual payload is a
934    /// deterministic diagnostic representation of the private numerical error.
935    LinearSolve {
936        iteration: usize,
937        diagnostic: String,
938    },
939}
940
941impl std::fmt::Display for MatrixFreeBaError {
942    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
943        match self {
944            Self::Ineligible(reason) => write!(f, "matrix-free BA is ineligible: {reason}"),
945            Self::InvalidConfiguration(reason) => {
946                write!(f, "invalid matrix-free BA configuration: {reason}")
947            }
948            Self::Ba(error) => write!(f, "matrix-free BA input error: {error}"),
949            Self::LinearSolve {
950                iteration,
951                diagnostic,
952            } => write!(
953                f,
954                "matrix-free reduced solve failed at iteration {iteration}: {diagnostic}"
955            ),
956        }
957    }
958}
959
960impl std::error::Error for MatrixFreeBaError {}
961
962#[cfg(test)]
963mod column_scaling_tests;
964
965#[cfg(test)]
966mod lm_step_quality_tests;
967
968#[derive(Debug, Clone, Copy, PartialEq)]
969pub struct BaCostBreakdown {
970    pub total: f64,
971    pub visual: f64,
972    pub imu: f64,
973    pub bias_random_walk: f64,
974    pub navigation_prior: f64,
975    pub other_structural: f64,
976    pub imu_normalized_squared_residual_per_dof: Option<f64>,
977    pub imu_rotation_residual_rms_rad: Option<f64>,
978    pub imu_velocity_residual_rms_mps: Option<f64>,
979    pub imu_position_residual_rms_meters: Option<f64>,
980}
981
982/// Result of [`BundleAdjustment::optimize_gnc`].
983#[derive(Debug, Clone, PartialEq)]
984pub struct BaGncResult {
985    /// Non-robust reprojection cost at the input estimate.
986    pub initial_cost: f64,
987    /// GNC-weighted reprojection cost at the recovered estimate (every
988    /// observation scaled by its final `w`).
989    pub final_cost: f64,
990    /// Reprojection cost over the classified inliers only (outliers
991    /// contribute nothing), using the `0.5` weight threshold.
992    pub inlier_cost: f64,
993    /// The inlier scale `c` (pixels) the solve actually used: the configured
994    /// [`GncConfig::c`] verbatim, or — under [`GncConfig::auto_scale`] — the
995    /// MAD estimate (floored at the configured `c`).
996    pub inlier_scale: f64,
997    /// Number of reprojection observations (monocular + stereo) the weight
998    /// vector covers.
999    pub observation_count: usize,
1000    /// GNC outer (μ) levels actually executed.
1001    pub outer_iterations: usize,
1002    /// Whether the μ schedule reached its terminal level.
1003    pub converged: bool,
1004    /// Final per-observation Black-Rangarajan weight `w ∈ [0,1]`, indexed
1005    /// monocular, rectified stereo, then general stereo. `NaN` marks an observation that could
1006    /// not be evaluated at the recovered estimate. Near-zero finite entries
1007    /// are the rejected outliers.
1008    pub observation_weights: Vec<f64>,
1009}
1010
1011impl BaGncResult {
1012    /// Count of observations classified as inliers (`w ≥ threshold`).
1013    /// `NaN` (un-evaluable) observations are excluded from both counts.
1014    pub fn inlier_count(&self, threshold: f64) -> usize {
1015        self.observation_weights
1016            .iter()
1017            .filter(|w| w.is_finite() && **w >= threshold)
1018            .count()
1019    }
1020
1021    /// Count of observations classified as outliers (`w < threshold`).
1022    pub fn outlier_count(&self, threshold: f64) -> usize {
1023        self.observation_weights
1024            .iter()
1025            .filter(|w| w.is_finite() && **w < threshold)
1026            .count()
1027    }
1028}
1029
1030#[derive(Debug, Clone, PartialEq, Eq)]
1031pub enum BaError {
1032    NoPoses,
1033    NoLandmarks,
1034    NoObservations,
1035    /// Every pose AND every landmark is fixed, so there is nothing to
1036    /// optimize. (Pose-only or landmark-only BA is allowed.)
1037    AllPosesFixed,
1038    MissingPose(u64),
1039    MissingLandmark(u64),
1040    /// Camera model is not pinhole (multi-model BA is a future extension).
1041    UnsupportedCameraModel,
1042    /// One or more [`BaStereoObservation`]s were added but
1043    /// [`BundleAdjustment::stereo_baseline`] is missing or non-positive.
1044    MissingStereoBaseline,
1045    /// The external visual-weight vector does not match the flattened visual
1046    /// observation count (mono, rectified stereo, general stereo).
1047    ObservationWeightCount {
1048        expected: usize,
1049        actual: usize,
1050    },
1051    /// An external visual weight is negative, NaN, or infinite.
1052    InvalidObservationWeight(usize),
1053    /// A fixed-rotation diagnostic supplied a vector that is not aligned with
1054    /// the pose vector being optimized.
1055    InvalidFixedRotationCount {
1056        expected: usize,
1057        actual: usize,
1058    },
1059    /// Confidence-weighted joint intrinsics refinement is not implemented.
1060    ObservationWeightsWithIntrinsicsRefinement,
1061    /// Reduced camera system was singular even after λ damping. Usually
1062    /// means the gauge is under-fixed (e.g., monocular without enough
1063    /// fixed poses or landmarks to remove scale).
1064    SingularSystem,
1065}
1066
1067impl std::fmt::Display for BaError {
1068    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1069        match self {
1070            BaError::NoPoses => write!(f, "bundle adjustment has no poses"),
1071            BaError::NoLandmarks => write!(f, "bundle adjustment has no landmarks"),
1072            BaError::NoObservations => write!(f, "bundle adjustment has no observations"),
1073            BaError::AllPosesFixed => write!(f, "every pose is fixed; nothing to optimize"),
1074            BaError::MissingPose(id) => write!(f, "observation references unknown pose {id}"),
1075            BaError::MissingLandmark(id) => {
1076                write!(f, "observation references unknown landmark {id}")
1077            }
1078            BaError::UnsupportedCameraModel => {
1079                write!(f, "only pinhole camera models are supported")
1080            }
1081            BaError::MissingStereoBaseline => {
1082                write!(f, "stereo observations require a positive stereo_baseline")
1083            }
1084            BaError::ObservationWeightCount { expected, actual } => write!(
1085                f,
1086                "observation weight count mismatch: expected {expected}, got {actual}"
1087            ),
1088            BaError::InvalidObservationWeight(index) => write!(
1089                f,
1090                "observation weight at index {index} must be finite and non-negative"
1091            ),
1092            BaError::InvalidFixedRotationCount { expected, actual } => write!(
1093                f,
1094                "fixed-rotation pose count mismatch: expected {expected}, got {actual}"
1095            ),
1096            BaError::ObservationWeightsWithIntrinsicsRefinement => write!(
1097                f,
1098                "observation weights are not supported with joint intrinsics refinement"
1099            ),
1100            BaError::SingularSystem => write!(f, "reduced camera system is singular"),
1101        }
1102    }
1103}
1104
1105impl std::error::Error for BaError {}
1106
1107#[cfg(test)]
1108mod mono_projection_tests;
1109
1110#[test]
1111fn qr_shadow_caps_reject_oversized_diagnostics() {
1112    assert!(qr_shadow_dimensions_allowed(60, 64, 1024, 20000));
1113    for dimensions in [
1114        (61, 64, 1024, 20000),
1115        (60, 65, 1024, 20000),
1116        (60, 64, 1025, 20000),
1117        (60, 64, 1024, 20001),
1118        (60, 64, 1024, 0),
1119        (usize::MAX, usize::MAX, usize::MAX, usize::MAX),
1120    ] {
1121        assert!(!qr_shadow_dimensions_allowed(
1122            dimensions.0,
1123            dimensions.1,
1124            dimensions.2,
1125            dimensions.3
1126        ));
1127    }
1128}
1129
1130/// `LocalRefiner` implementation that runs windowed bundle adjustment on
1131/// a staged map update. Existing keyframes and landmarks in the window
1132/// (already in `VisualMap`) are added as fixed gauge; the newly-staged
1133/// keyframe poses and landmark positions are the BA variables. Observations
1134/// from both the existing window and the staged update feed the residual.
1135///
1136/// Refined poses / landmarks are written back into the staged update so
1137/// subsequent `apply_to(&mut map)` lands the BA-corrected values. The
1138/// existing map is never mutated by this refiner.
1139#[derive(Debug, Clone, PartialEq)]
1140pub struct BundleAdjustmentRefiner {
1141    pub config: BaConfig,
1142}
1143
1144impl BundleAdjustmentRefiner {
1145    pub const fn new(config: BaConfig) -> Self {
1146        Self { config }
1147    }
1148}
1149
1150impl Default for BundleAdjustmentRefiner {
1151    fn default() -> Self {
1152        Self::new(BaConfig::default())
1153    }
1154}
1155
1156impl LocalRefiner for BundleAdjustmentRefiner {
1157    fn refine(
1158        &self,
1159        map: &VisualMap,
1160        local_window: &LocalMapWindow,
1161        staged_update: &mut StagedMapUpdate,
1162    ) -> LocalRefinementResult {
1163        // Pick a camera. Prefer the camera attached to the first staged
1164        // keyframe; fall back to any camera in the existing window.
1165        let camera = staged_update
1166            .keyframes
1167            .iter()
1168            .find_map(|kf| map.cameras.get(&kf.frame.camera_id).cloned())
1169            .or_else(|| {
1170                local_window
1171                    .keyframe_ids
1172                    .iter()
1173                    .find_map(|id| map.keyframes.get(id))
1174                    .and_then(|kf| map.cameras.get(&kf.frame.camera_id).cloned())
1175            });
1176        let Some(camera) = camera else {
1177            return LocalRefinementResult::skipped(LocalRefinementReason::Noop);
1178        };
1179
1180        let mut ba = BundleAdjustment::new(camera);
1181
1182        // Treat staged keyframes / landmarks as variable. Everything else
1183        // in the window is already in `map` and serves as a fixed gauge.
1184        // The local window typically already includes the newly-staged
1185        // keyframe (the local-mapping pipeline inserts it into a working
1186        // map before computing the window), so we must skip those when
1187        // adding fixed poses — otherwise the BA variable would become a
1188        // fixed gauge and never move.
1189        let staged_kf_ids: std::collections::BTreeSet<u64> = staged_update
1190            .keyframes
1191            .iter()
1192            .map(|kf| kf.frame.id)
1193            .collect();
1194        let staged_lm_ids: std::collections::BTreeSet<u64> =
1195            staged_update.landmarks.iter().map(|lm| lm.id).collect();
1196
1197        // Fixed gauge: window keyframes that are NOT in the staged update.
1198        for &kf_id in &local_window.keyframe_ids {
1199            if staged_kf_ids.contains(&kf_id) {
1200                continue;
1201            }
1202            let Some(kf) = map.keyframes.get(&kf_id) else {
1203                continue;
1204            };
1205            let Some(pose) = kf.frame.pose.clone() else {
1206                continue;
1207            };
1208            ba.add_pose(kf_id, pose);
1209            ba.fix_pose(kf_id);
1210        }
1211        // Variable: newly-staged keyframe poses.
1212        for kf in &staged_update.keyframes {
1213            let id = kf.frame.id;
1214            let Some(pose) = kf.frame.pose.clone() else {
1215                continue;
1216            };
1217            ba.add_pose(id, pose);
1218        }
1219
1220        // Fixed gauge: window landmarks that are NOT in the staged update.
1221        for &lm_id in &local_window.landmark_ids {
1222            if staged_lm_ids.contains(&lm_id) {
1223                continue;
1224            }
1225            let Some(lm) = map.landmarks.get(&lm_id) else {
1226                continue;
1227            };
1228            ba.add_landmark(lm_id, lm.position);
1229            ba.fix_landmark(lm_id);
1230        }
1231        // Variable: newly-staged landmarks.
1232        for lm in &staged_update.landmarks {
1233            ba.add_landmark(lm.id, lm.position);
1234        }
1235
1236        // Observations: existing keyframes' observations of fixed landmarks
1237        // (anchor the gauge), plus new staged observations.
1238        for &kf_id in &local_window.keyframe_ids {
1239            let Some(kf) = map.keyframes.get(&kf_id) else {
1240                continue;
1241            };
1242            for obs in &kf.observations {
1243                if ba.poses.contains_key(&obs.frame_id)
1244                    && ba.landmarks.contains_key(&obs.landmark_id)
1245                {
1246                    ba.add_observation(BaObservation {
1247                        keyframe_id: obs.frame_id,
1248                        landmark_id: obs.landmark_id,
1249                        xy: obs.xy,
1250                    });
1251                }
1252            }
1253        }
1254        for obs in &staged_update.observations {
1255            if ba.poses.contains_key(&obs.frame_id) && ba.landmarks.contains_key(&obs.landmark_id) {
1256                ba.add_observation(BaObservation {
1257                    keyframe_id: obs.frame_id,
1258                    landmark_id: obs.landmark_id,
1259                    xy: obs.xy,
1260                });
1261            }
1262        }
1263
1264        // No observations to optimize against → nothing to refine.
1265        if ba.observations.is_empty() {
1266            return LocalRefinementResult::skipped(LocalRefinementReason::Noop);
1267        }
1268        // Every variable pose is fixed (or no variable poses exist) AND
1269        // every variable landmark is fixed → nothing to optimize. The BA
1270        // would still report `AllPosesFixed`; just skip cleanly.
1271        let has_variable_pose = ba.poses.keys().any(|id| !ba.fixed_poses.contains(id));
1272        let has_variable_landmark = ba
1273            .landmarks
1274            .keys()
1275            .any(|id| !ba.fixed_landmarks.contains(id));
1276        if !has_variable_pose && !has_variable_landmark {
1277            return LocalRefinementResult::skipped(LocalRefinementReason::Noop);
1278        }
1279
1280        if ba.optimize(&self.config).is_err() {
1281            return LocalRefinementResult::skipped(LocalRefinementReason::Noop);
1282        }
1283
1284        // Write back refined values into staged_update. Fixed entries are
1285        // never modified.
1286        let mut keyframe_count = 0usize;
1287        for kf in staged_update.keyframes.iter_mut() {
1288            let id = kf.frame.id;
1289            if ba.fixed_poses.contains(&id) {
1290                continue;
1291            }
1292            if let Some(refined) = ba.poses.get(&id).cloned() {
1293                kf.frame.pose = Some(refined);
1294                keyframe_count += 1;
1295            }
1296        }
1297        let mut landmark_count = 0usize;
1298        for lm in staged_update.landmarks.iter_mut() {
1299            if ba.fixed_landmarks.contains(&lm.id) {
1300                continue;
1301            }
1302            if let Some(refined) = ba.landmarks.get(&lm.id).copied() {
1303                lm.position = refined;
1304                landmark_count += 1;
1305            }
1306        }
1307
1308        LocalRefinementResult {
1309            refined: keyframe_count > 0 || landmark_count > 0,
1310            reason: LocalRefinementReason::Refined,
1311            keyframe_count,
1312            landmark_count,
1313        }
1314    }
1315}
1316
1317/// Private matrix-free Schur backend.
1318///
1319/// The backend consumes an assembled pure-visual `PoseDiagonal` system and
1320/// never constructs pose-pair blocks, triplets, or a Cholesky factor.  Its
1321/// public entry point remains on [`BundleAdjustment`]; keeping the numerical
1322/// implementation here avoids a second operator implementation in tests.
1323mod implicit_schur;
1324
1325#[cfg(test)]
1326mod matrix_free_ba_api_tests;
1327
1328#[cfg(test)]
1329mod matrix_free_real_oracle_tests;
1330
1331#[cfg(test)]
1332mod visual_jacobian_audit_tests;
1333
1334#[cfg(test)]
1335mod imu_gradient_tests;
1336
1337/// Tests for [`BaConfig::parallel`] (see the module's "Parallelism"
1338/// section): the serial and parallel assembly / Schur-reduction /
1339/// back-substitution paths must agree, and the parallel path must be
1340/// deterministic. The synthetic problem is sized past
1341/// `PARALLEL_MIN_OBSERVATIONS` / `PARALLEL_MIN_LANDMARKS` so these tests
1342/// actually exercise the parallel dispatch rather than falling through the
1343/// work gate to the serial loops.
1344#[cfg(test)]
1345mod parallel_ba_tests;