Skip to main content

visloc_vision/pnp/
generalized.rs

1//! Non-central absolute pose for calibrated multi-camera rigs.
2//!
3//! A generalized camera observation is a ray with a known origin in the rig
4//! frame.  Given world point `X`, rig pose `(R, t)`, ray direction `f`, and ray
5//! origin `c`, the absolute-pose constraint is
6//!
7//! ```text
8//! f × (R X + t - c) = 0.
9//! ```
10//!
11//! Unlike selecting the best central-camera PnP, every hypothesis below pools
12//! observations from distinct sensor origins and estimates one `world -> rig`
13//! pose.  The linear initializer is the generalized-camera analogue of DLT;
14//! RANSAC scores the true per-sensor pixel residual and the final
15//! Gauss-Newton pass refines the shared rig pose.  The formulation follows the
16//! non-central absolute-pose model used by OpenGV's GP3P/GPnP implementations.
17
18use nalgebra::{DMatrix, DVector, Matrix3, Point2, Point3, UnitQuaternion, Vector3};
19use rand::rngs::SmallRng;
20use rand::seq::SliceRandom;
21use rand::SeedableRng;
22use visloc_core::geometry::{Pose, SE3};
23use visloc_core::types::Camera;
24
25use crate::pnp::gp3p::gp3p_solve;
26use crate::pnp::{Correspondence2D3D, GaussNewtonPoseRefiner, P3PGrunert};
27use crate::ransac::{PnPRansac, RobustPoseEstimator};
28
29/// One calibrated sensor rigidly attached to a generalized camera rig.
30#[derive(Debug, Clone, PartialEq)]
31pub struct RigSensor {
32    pub camera: Camera,
33    /// Fixed transform `T_sensor<-rig`.
34    pub sensor_from_rig: SE3,
35}
36
37/// Validated sensor geometry used by generalized absolute pose.
38#[derive(Debug, Clone, PartialEq)]
39pub struct GeneralizedCameraRig {
40    sensors: Vec<RigSensor>,
41    origins_rig: Vec<Point3<f64>>,
42}
43
44impl GeneralizedCameraRig {
45    /// Construct a rig. Returns `None` for an empty rig, invalid intrinsics, or
46    /// non-finite extrinsics.
47    pub fn new(sensors: Vec<RigSensor>) -> Option<Self> {
48        if sensors.is_empty() {
49            return None;
50        }
51        let mut origins_rig = Vec::with_capacity(sensors.len());
52        for sensor in &sensors {
53            let intrinsics = sensor.camera.intrinsics()?;
54            if ![intrinsics.0, intrinsics.1, intrinsics.2, intrinsics.3]
55                .iter()
56                .all(|value| value.is_finite())
57                || intrinsics.0 <= 0.0
58                || intrinsics.1 <= 0.0
59                || !sensor
60                    .sensor_from_rig
61                    .translation
62                    .iter()
63                    .all(|value| value.is_finite())
64            {
65                return None;
66            }
67            let rig_from_sensor = sensor.sensor_from_rig.inverse();
68            let origin = Point3::from(rig_from_sensor.translation);
69            if !origin.coords.iter().all(|value| value.is_finite()) {
70                return None;
71            }
72            origins_rig.push(origin);
73        }
74        Some(Self {
75            sensors,
76            origins_rig,
77        })
78    }
79
80    pub fn sensors(&self) -> &[RigSensor] {
81        &self.sensors
82    }
83
84    pub fn sensor(&self, index: usize) -> Option<&RigSensor> {
85        self.sensors.get(index)
86    }
87
88    pub fn sensor_origin_rig(&self, index: usize) -> Option<&Point3<f64>> {
89        self.origins_rig.get(index)
90    }
91
92    fn ray_rig(
93        &self,
94        correspondence: &GeneralizedCorrespondence2D3D,
95    ) -> Option<(Point3<f64>, Vector3<f64>)> {
96        let sensor = self.sensor(correspondence.sensor_index)?;
97        // A camera that sees behind itself (a fisheye past 180°) has rays
98        // the normalized plane cannot hold.
99        let bearing_sensor = if sensor.camera.sees_behind() {
100            sensor.camera.unit_ray_from_pixel(&correspondence.point2d)?
101        } else {
102            let normalized = sensor.camera.normalize_pixel(&correspondence.point2d)?;
103            Vector3::new(normalized.x, normalized.y, 1.0).try_normalize(1e-15)?
104        };
105        let bearing_rig = sensor
106            .sensor_from_rig
107            .rotation
108            .inverse_transform_vector(&bearing_sensor)
109            .try_normalize(1e-15)?;
110        Some((
111            *self.sensor_origin_rig(correspondence.sensor_index)?,
112            bearing_rig,
113        ))
114    }
115
116    fn project(
117        &self,
118        pose: &Pose,
119        correspondence: &GeneralizedCorrespondence2D3D,
120    ) -> Option<Point2<f64>> {
121        let sensor = self.sensor(correspondence.sensor_index)?;
122        let point_rig = pose.transform_world_point(&correspondence.point3d);
123        let point_sensor = sensor.sensor_from_rig.transform_point(&point_rig);
124        sensor.camera.project(&point_sensor)
125    }
126}
127
128/// One world-point to rig-sensor pixel correspondence.
129#[derive(Debug, Clone, PartialEq)]
130pub struct GeneralizedCorrespondence2D3D {
131    pub sensor_index: usize,
132    pub point2d: Point2<f64>,
133    pub point3d: Point3<f64>,
134    pub confidence: Option<f32>,
135}
136
137/// Linear non-central absolute-pose initializer.
138#[derive(Debug, Clone, Copy, PartialEq)]
139pub struct GeneralizedDltPoseEstimator {
140    /// Minimum ray-origin span required by a solve sample. A zero-origin
141    /// central-camera sample is deliberately rejected instead of silently
142    /// degenerating to ordinary PnP.
143    pub minimum_origin_span: f64,
144    /// Maximum singular-value anisotropy of the recovered scaled rotation.
145    pub maximum_rotation_anisotropy: f64,
146}
147
148impl Default for GeneralizedDltPoseEstimator {
149    fn default() -> Self {
150        Self {
151            minimum_origin_span: 1.0e-9,
152            maximum_rotation_anisotropy: 0.35,
153        }
154    }
155}
156
157impl GeneralizedDltPoseEstimator {
158    pub const MINIMUM_CORRESPONDENCES: usize = 6;
159
160    /// Estimate one shared `world -> rig` pose. Every accepted solve contains
161    /// at least two distinct ray origins.
162    pub fn estimate_pose(
163        &self,
164        rig: &GeneralizedCameraRig,
165        correspondences: &[GeneralizedCorrespondence2D3D],
166    ) -> Option<Pose> {
167        if correspondences.len() < Self::MINIMUM_CORRESPONDENCES
168            || !self.minimum_origin_span.is_finite()
169            || self.minimum_origin_span < 0.0
170            || !self.maximum_rotation_anisotropy.is_finite()
171            || self.maximum_rotation_anisotropy < 0.0
172        {
173            return None;
174        }
175
176        let rays = correspondences
177            .iter()
178            .map(|correspondence| rig.ray_rig(correspondence))
179            .collect::<Option<Vec<_>>>()?;
180        let origin_span = rays
181            .iter()
182            .enumerate()
183            .flat_map(|(left, (origin_left, _))| {
184                rays[(left + 1)..]
185                    .iter()
186                    .map(move |(origin_right, _)| (origin_left - origin_right).norm())
187            })
188            .fold(0.0_f64, f64::max);
189        if origin_span <= self.minimum_origin_span {
190            return None;
191        }
192
193        let count = correspondences.len() as f64;
194        let centroid = correspondences
195            .iter()
196            .fold(Vector3::zeros(), |sum, correspondence| {
197                sum + correspondence.point3d.coords
198            })
199            / count;
200        let mean_distance = correspondences
201            .iter()
202            .map(|correspondence| (correspondence.point3d.coords - centroid).norm())
203            .sum::<f64>()
204            / count;
205        if !mean_distance.is_finite() || mean_distance <= 1.0e-12 {
206            return None;
207        }
208        let world_scale = 3.0_f64.sqrt() / mean_distance;
209
210        // Three cross-product rows are retained per ray. Each 3-row block has
211        // rank two, while SVD least squares handles that intentional
212        // redundancy without choosing a numerically fragile row pair.
213        let mut design = DMatrix::<f64>::zeros(correspondences.len() * 3, 12);
214        let mut rhs = DVector::<f64>::zeros(correspondences.len() * 3);
215        for (index, (correspondence, (origin, bearing))) in
216            correspondences.iter().zip(&rays).enumerate()
217        {
218            let point = world_scale * (correspondence.point3d.coords - centroid);
219            let cross = skew(bearing);
220            let cross_origin = cross * origin.coords;
221            for equation in 0..3 {
222                let row = index * 3 + equation;
223                for output_axis in 0..3 {
224                    for world_axis in 0..3 {
225                        design[(row, output_axis * 3 + world_axis)] =
226                            cross[(equation, output_axis)] * point[world_axis];
227                    }
228                    design[(row, 9 + output_axis)] = cross[(equation, output_axis)];
229                }
230                rhs[row] = cross_origin[equation];
231            }
232        }
233
234        let svd = design.try_svd(true, true, f64::EPSILON * 5.0, 10_000)?;
235        let solution = svd.solve(&rhs, 1.0e-12).ok()?;
236        if solution.len() != 12 || !solution.iter().all(|value| value.is_finite()) {
237            return None;
238        }
239        let scaled_rotation = Matrix3::new(
240            solution[0],
241            solution[1],
242            solution[2],
243            solution[3],
244            solution[4],
245            solution[5],
246            solution[6],
247            solution[7],
248            solution[8],
249        );
250        let rotation_svd = scaled_rotation.try_svd(true, true, f64::EPSILON * 5.0, 10_000)?;
251        let singular = rotation_svd.singular_values;
252        let rotation_scale = singular.iter().sum::<f64>() / 3.0;
253        if !rotation_scale.is_finite() || rotation_scale <= 1.0e-12 {
254            return None;
255        }
256        let anisotropy = (singular.max() - singular.min()) / rotation_scale;
257        if anisotropy > self.maximum_rotation_anisotropy {
258            return None;
259        }
260        let u = rotation_svd.u?;
261        let v_t = rotation_svd.v_t?;
262        let mut sign = Matrix3::identity();
263        sign[(2, 2)] = (u * v_t).determinant().signum();
264        if sign[(2, 2)] == 0.0 {
265            return None;
266        }
267        let rotation_matrix = u * sign * v_t;
268        let translation_normalized = Vector3::new(solution[9], solution[10], solution[11]);
269        let translation = translation_normalized - rotation_matrix * centroid;
270        let pose = Pose::from_world_to_camera(
271            visloc_core::geometry::rotation_from_matrix(&rotation_matrix),
272            translation,
273        );
274
275        // Reject the reflected/behind-camera branch and gross linear failures.
276        let positive = correspondences
277            .iter()
278            .filter(|correspondence| rig.project(&pose, correspondence).is_some())
279            .count();
280        (positive * 2 >= correspondences.len()).then_some(pose)
281    }
282}
283
284/// Shared-rig nonlinear pose refiner.
285///
286/// Port of COLMAP's post-RANSAC generalized-pose refinement,
287/// `RefineGeneralizedAbsolutePose` (`estimators/generalized_pose.cc:280-431`),
288/// as called from `RegisterNextGeneralFrame`
289/// (`sfm/incremental_mapper.cc:601-641`) — the routine this crate's
290/// `GeneralizedPnPRansac` uses this refiner for. That routine hardcodes a
291/// Cauchy loss unconditionally (`generalized_pose.cc:298-299`:
292/// `std::make_unique<ceres::CauchyLoss>(options.loss_function_scale)` — there
293/// is no `Trivial`/`SoftL1` option at this call site to mirror, unlike
294/// `colmap_incremental::bundle_adjustment::LossFunction`'s BA path), so
295/// `loss_scale` here is *always* applied as a Cauchy loss, not a switchable
296/// enum. `AbsolutePoseRefinementOptions::loss_function_scale`'s default is
297/// `1.0` (`estimators/pose.h:73`), reproduced by
298/// [`GeneralizedGaussNewtonPoseRefiner::default`].
299///
300/// This refiner computes its Jacobian by finite differences on the *raw*
301/// (loss-free) stacked residual vector (unchanged from before this port), so
302/// the robust-loss correction is applied as a distinct step afterward,
303/// per-observation (one `[x,y]` sub-block per correspondence, matching
304/// Ceres' per-residual-block granularity exactly): see
305/// [`apply_robust_loss`], a block-local port of `ceres::internal::Corrector`
306/// (`internal/ceres/corrector.cc`) — the same algorithm as
307/// `colmap_incremental::rig_ba_solver::Corrector` (that module's doc has the
308/// full citation), reimplemented here directly on `DVector`/`DMatrix`
309/// row-slices rather than shared across crates, since this refiner's problem
310/// (stacked finite-difference Jacobian, not a per-observation analytic
311/// Jacobian folded into a Schur-complement system) has a different enough
312/// shape that sharing the fixed-size `SMatrix`-based type from
313/// `rig_ba_solver.rs` would need its own adapter either way.
314#[derive(Debug, Clone, Copy, PartialEq)]
315pub struct GeneralizedGaussNewtonPoseRefiner {
316    pub iterations: usize,
317    pub damping: f64,
318    pub finite_difference_epsilon: f64,
319    pub minimum_error_reduction: f64,
320    /// Cauchy loss scale `a` (`AbsolutePoseRefinementOptions::loss_function_scale`,
321    /// `estimators/pose.h:73`, default `1.0`).
322    pub loss_scale: f64,
323}
324
325impl Default for GeneralizedGaussNewtonPoseRefiner {
326    fn default() -> Self {
327        Self {
328            iterations: 10,
329            damping: 1.0e-6,
330            finite_difference_epsilon: 1.0e-6,
331            minimum_error_reduction: 1.0e-10,
332            loss_scale: 1.0,
333        }
334    }
335}
336
337impl GeneralizedGaussNewtonPoseRefiner {
338    pub fn refine_pose(
339        &self,
340        rig: &GeneralizedCameraRig,
341        initial_pose: &Pose,
342        correspondences: &[GeneralizedCorrespondence2D3D],
343    ) -> Option<Pose> {
344        if correspondences.is_empty()
345            || self.iterations == 0
346            || !self.damping.is_finite()
347            || self.damping < 0.0
348            || !self.finite_difference_epsilon.is_finite()
349            || self.finite_difference_epsilon <= 0.0
350            || !self.loss_scale.is_finite()
351            || self.loss_scale <= 0.0
352        {
353            return None;
354        }
355        let mut pose = initial_pose.clone();
356        let mut best_cost = robust_cost(rig, &pose, correspondences, self.loss_scale)?;
357        for _ in 0..self.iterations {
358            let raw_residual = residuals(rig, &pose, correspondences)?;
359            let mut jacobian = DMatrix::<f64>::zeros(raw_residual.len(), 6);
360            for parameter in 0..6 {
361                let mut delta = DVector::<f64>::zeros(6);
362                delta[parameter] = self.finite_difference_epsilon;
363                let perturbed_pose = perturb_pose(&pose, &delta);
364                let perturbed = residuals(rig, &perturbed_pose, correspondences)?;
365                jacobian.set_column(
366                    parameter,
367                    &((perturbed - &raw_residual) / self.finite_difference_epsilon),
368                );
369            }
370            // Robust-loss correction, per observation block — mutates both
371            // in place (Jacobian first, from the still-raw residual, then
372            // the residual itself; see `apply_robust_loss`'s doc).
373            let mut residual = raw_residual;
374            apply_robust_loss(self.loss_scale, &mut residual, &mut jacobian);
375            let transpose = jacobian.transpose();
376            let mut hessian = &transpose * &jacobian;
377            for diagonal in 0..6 {
378                hessian[(diagonal, diagonal)] += self.damping;
379            }
380            let gradient = transpose * residual;
381            let step = hessian.lu().solve(&(-gradient))?;
382            if !step.iter().all(|value| value.is_finite()) {
383                break;
384            }
385            let candidate = perturb_pose(&pose, &step);
386            let Some(candidate_cost) =
387                robust_cost(rig, &candidate, correspondences, self.loss_scale)
388            else {
389                break;
390            };
391            if candidate_cost + self.minimum_error_reduction >= best_cost {
392                break;
393            }
394            pose = candidate;
395            best_cost = candidate_cost;
396        }
397        Some(pose)
398    }
399}
400
401/// `rho(s), rho'(s), rho''(s)` for `ceres::CauchyLoss` — port of
402/// `CauchyLoss::Evaluate` (`internal/ceres/loss_function.cc:77-84`),
403/// `b=a²,c=1/b` from `include/ceres/loss_function.h:207-217`. Identical
404/// formula to `colmap_incremental::rig_ba_solver::evaluate_loss`'s
405/// `LossFunction::Cauchy` arm; duplicated here (rather than shared) since
406/// this crate (`visloc-vision`) does not depend on `visloc-slam`.
407#[inline]
408fn cauchy_loss(scale: f64, s: f64) -> [f64; 3] {
409    let b = scale * scale;
410    let c = 1.0 / b;
411    let sum = 1.0 + s * c;
412    let inv = 1.0 / sum;
413    let rho0 = b * sum.ln();
414    let rho1 = inv.max(f64::MIN_POSITIVE);
415    let rho2 = -c * (inv * inv);
416    [rho0, rho1, rho2]
417}
418
419/// `Σ rho(s_i)` over every observation's own squared residual norm
420/// `s_i = r_i.x² + r_i.y²` — the robustified analog of `mean_squared_error`,
421/// matching Ceres' `cost = Σ 0.5·rho(s_i)` convention up to the constant
422/// `0.5`/`N` factors (irrelevant here: only used to compare a candidate
423/// step's cost against the current best, `residual_block.cc:161-168`).
424fn robust_cost(
425    rig: &GeneralizedCameraRig,
426    pose: &Pose,
427    correspondences: &[GeneralizedCorrespondence2D3D],
428    loss_scale: f64,
429) -> Option<f64> {
430    let r = residuals(rig, pose, correspondences)?;
431    let num_obs = r.len() / 2;
432    let mut cost = 0.0;
433    for i in 0..num_obs {
434        let s = r[2 * i] * r[2 * i] + r[2 * i + 1] * r[2 * i + 1];
435        cost += cauchy_loss(loss_scale, s)[0];
436    }
437    Some(cost)
438}
439
440/// Block-local port of `ceres::internal::Corrector`
441/// (`internal/ceres/corrector.cc:41-155`; see
442/// `colmap_incremental::rig_ba_solver::Corrector`'s doc for the full
443/// algorithm citation and the exact call-order/cost-convention rationale
444/// this mirrors, `residual_block.cc:161-197`) applied independently to each
445/// `[x,y]` observation sub-block of `residual`/`jacobian` (rows `2i,2i+1`) —
446/// i.e. at the same per-residual-block granularity Ceres itself uses,
447/// despite `jacobian` being one finite-difference-assembled `2N×6` matrix
448/// here rather than N separate analytic `2×6` blocks. Mutates both in place;
449/// `jacobian`'s correction uses the *pre-correction* residual values (must
450/// run first, matching Ceres), so `residual` is corrected last.
451fn apply_robust_loss(loss_scale: f64, residual: &mut DVector<f64>, jacobian: &mut DMatrix<f64>) {
452    let num_obs = residual.len() / 2;
453    let ncols = jacobian.ncols();
454    for i in 0..num_obs {
455        let r0 = residual[2 * i];
456        let r1 = residual[2 * i + 1];
457        let s = r0 * r0 + r1 * r1;
458        let rho = cauchy_loss(loss_scale, s);
459        let sqrt_rho1 = rho[1].max(0.0).sqrt();
460        let (residual_scaling, alpha_sq_norm) = if s == 0.0 || rho[2] <= 0.0 {
461            (sqrt_rho1, 0.0)
462        } else {
463            let d = 1.0 + 2.0 * s * rho[2] / rho[1];
464            let alpha = 1.0 - d.sqrt();
465            (sqrt_rho1 / (1.0 - alpha), alpha / s)
466        };
467        if alpha_sq_norm == 0.0 {
468            for c in 0..ncols {
469                jacobian[(2 * i, c)] *= sqrt_rho1;
470                jacobian[(2 * i + 1, c)] *= sqrt_rho1;
471            }
472        } else {
473            for c in 0..ncols {
474                let j0 = jacobian[(2 * i, c)];
475                let j1 = jacobian[(2 * i + 1, c)];
476                let r_transpose_j = r0 * j0 + r1 * j1;
477                jacobian[(2 * i, c)] = sqrt_rho1 * (j0 - alpha_sq_norm * r0 * r_transpose_j);
478                jacobian[(2 * i + 1, c)] = sqrt_rho1 * (j1 - alpha_sq_norm * r1 * r_transpose_j);
479            }
480        }
481        residual[2 * i] *= residual_scaling;
482        residual[2 * i + 1] *= residual_scaling;
483    }
484}
485
486/// Generalized-camera RANSAC result.
487#[derive(Debug, Clone, PartialEq)]
488pub struct GeneralizedRansacReport {
489    pub pose: Pose,
490    pub inliers: Vec<usize>,
491    pub inlier_reprojection_errors: Vec<f64>,
492    pub mean_reprojection_error: f64,
493    pub median_reprojection_error: f64,
494    pub max_reprojection_error: f64,
495    pub refinement_applied: bool,
496}
497
498/// Which minimal solver [`GeneralizedPnPRansac`] uses to generate pose
499/// hypotheses from a minimal sample. Port of the C3 task's "keep the
500/// existing 6-point DLT path selectable (option) for A/B" instruction:
501/// [`MinimalSolver::Gp3p`] (the default, matching COLMAP's
502/// `EstimateGeneralizedAbsolutePose` -> `GP3PEstimator`,
503/// `estimators/generalized_pose.cc:131-190`, `RANSAC<GP3PEstimator,...>`
504/// sampling exactly 3 correspondences per trial) is the faithful C3 port;
505/// [`MinimalSolver::Dlt6pt`] keeps this port's pre-C3 6-point linear DLT
506/// path (see `generalized.rs`'s module doc and
507/// [`GeneralizedDltPoseEstimator`]) available for A/B parity checks.
508#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
509pub enum MinimalSolver {
510    #[default]
511    Gp3p,
512    Dlt6pt,
513}
514
515/// Deterministic pixel-space RANSAC for one generalized rig frame.
516#[derive(Debug, Clone, Copy, PartialEq)]
517pub struct GeneralizedPnPRansac {
518    pub minimal_solver: MinimalSolver,
519    pub pose_estimator: GeneralizedDltPoseEstimator,
520    pub pose_refiner: Option<GeneralizedGaussNewtonPoseRefiner>,
521    pub iterations: usize,
522    pub reprojection_threshold: f64,
523    pub confidence: Option<f64>,
524    pub seed: u64,
525}
526
527impl Default for GeneralizedPnPRansac {
528    fn default() -> Self {
529        Self {
530            minimal_solver: MinimalSolver::default(),
531            pose_estimator: GeneralizedDltPoseEstimator::default(),
532            pose_refiner: Some(GeneralizedGaussNewtonPoseRefiner::default()),
533            iterations: 256,
534            reprojection_threshold: 4.0,
535            confidence: Some(0.999),
536            seed: 7,
537        }
538    }
539}
540
541/// Generates GP3P's up-to-8 candidate `world -> rig` poses from a minimal
542/// 3-correspondence sample, drawn from possibly different sensors of the
543/// rig (`rig.ray_rig` handles the per-sensor bearing/origin transform into
544/// the shared rig frame, same helper [`GeneralizedDltPoseEstimator`] uses).
545fn gp3p_hypotheses(
546    rig: &GeneralizedCameraRig,
547    correspondences: &[GeneralizedCorrespondence2D3D],
548    sample_idx: [usize; 3],
549    seed: u64,
550) -> Vec<Pose> {
551    let mut origins = [Point3::origin(); 3];
552    let mut bearings = [Vector3::zeros(); 3];
553    let mut points = [Point3::origin(); 3];
554    for (k, &idx) in sample_idx.iter().enumerate() {
555        let correspondence = &correspondences[idx];
556        let Some((origin, bearing)) = rig.ray_rig(correspondence) else {
557            return Vec::new();
558        };
559        origins[k] = origin;
560        bearings[k] = bearing;
561        points[k] = correspondence.point3d;
562    }
563    gp3p_solve(&origins, &bearings, &points, seed)
564}
565
566impl GeneralizedPnPRansac {
567    pub fn estimate(
568        &self,
569        rig: &GeneralizedCameraRig,
570        correspondences: &[GeneralizedCorrespondence2D3D],
571    ) -> Option<GeneralizedRansacReport> {
572        self.estimate_with_pose_prior(rig, correspondences, None)
573    }
574
575    pub fn estimate_with_pose_prior(
576        &self,
577        rig: &GeneralizedCameraRig,
578        correspondences: &[GeneralizedCorrespondence2D3D],
579        pose_prior: Option<&Pose>,
580    ) -> Option<GeneralizedRansacReport> {
581        let sample_size = match self.minimal_solver {
582            MinimalSolver::Gp3p => 3,
583            MinimalSolver::Dlt6pt => GeneralizedDltPoseEstimator::MINIMUM_CORRESPONDENCES,
584        };
585        if correspondences.len() < sample_size
586            || self.iterations == 0
587            || !self.reprojection_threshold.is_finite()
588            || self.reprojection_threshold <= 0.0
589        {
590            return None;
591        }
592
593        let mut best_pose = pose_prior.cloned();
594        let mut best_score = pose_prior.map_or_else(GeneralizedScore::empty, |pose| {
595            score_pose(rig, pose, correspondences, self.reprojection_threshold)
596        });
597        let rig_timing_debug = std::env::var_os("VISLOC_RIG_SFM_TIMING").is_some();
598        let rig_timing_estimate_started = if rig_timing_debug {
599            Some(std::time::Instant::now())
600        } else {
601            None
602        };
603        let mut rng = SmallRng::seed_from_u64(self.seed);
604        let mut indices = (0..correspondences.len()).collect::<Vec<_>>();
605        let mut required_iterations = self.iterations;
606        let mut dlt_hypotheses = 0usize;
607        let mut central_hypotheses = 0usize;
608        for iteration in 0..self.iterations {
609            if let Some(started) = rig_timing_estimate_started {
610                if iteration % 10 == 0 {
611                    eprintln!(
612                        "rig-timing: ransac-iter iteration={iteration}/{} elapsed={:.3}s \
613                         correspondences={}",
614                        self.iterations,
615                        started.elapsed().as_secs_f64(),
616                        correspondences.len(),
617                    );
618                }
619            }
620            indices.shuffle(&mut rng);
621            let hypotheses: Vec<Pose> = match self.minimal_solver {
622                MinimalSolver::Dlt6pt => {
623                    let sample = indices
624                        .iter()
625                        .take(sample_size)
626                        .map(|index| correspondences[*index].clone())
627                        .collect::<Vec<_>>();
628                    self.pose_estimator
629                        .estimate_pose(rig, &sample)
630                        .into_iter()
631                        .collect()
632                }
633                MinimalSolver::Gp3p => {
634                    // A per-trial seed derived from the RANSAC seed and
635                    // trial index — deterministic for a fixed `self.seed`
636                    // (task requirement), distinct per trial so different
637                    // trials don't repeat GP3P's own internal auxiliary
638                    // randomness (see `gp3p.rs`'s module doc).
639                    let trial_seed = self
640                        .seed
641                        .wrapping_mul(0x9E37_79B9_7F4A_7C15)
642                        .wrapping_add(iteration as u64);
643                    gp3p_hypotheses(
644                        rig,
645                        correspondences,
646                        [indices[0], indices[1], indices[2]],
647                        trial_seed,
648                    )
649                }
650            };
651            if !hypotheses.is_empty() {
652                dlt_hypotheses += 1;
653            }
654            for pose in &hypotheses {
655                let score = score_pose(rig, pose, correspondences, self.reprojection_threshold);
656                if score.is_better_than(&best_score) {
657                    best_pose = Some(pose.clone());
658                    best_score = score;
659                    if let Some(confidence) = self.confidence {
660                        let inlier_ratio =
661                            best_score.inliers.len() as f64 / correspondences.len() as f64;
662                        if inlier_ratio >= 1.0 {
663                            required_iterations = iteration + 1;
664                        } else if inlier_ratio > 0.0 && confidence > 0.0 && confidence < 1.0 {
665                            let denominator = (1.0 - inlier_ratio.powi(sample_size as i32)).ln();
666                            if denominator < -1.0e-12 {
667                                required_iterations = required_iterations
668                                    .min(((1.0 - confidence).ln() / denominator).ceil().max(1.0)
669                                        as usize);
670                            }
671                        }
672                    }
673                }
674            }
675            if iteration + 1 >= required_iterations {
676                break;
677            }
678        }
679
680        // A small physical rig baseline makes the inhomogeneous generalized
681        // DLT poorly conditioned under pixel noise. Generate additional
682        // minimal P3P hypotheses independently inside each central sensor,
683        // transform them to the rig frame, then score them against *all*
684        // sensors. Sensor choice affects hypothesis generation only; the
685        // accepted body pose and nonlinear refinement remain fully pooled.
686        // Only applies to the [`MinimalSolver::Dlt6pt`] A/B path — GP3P is
687        // already an exact minimal solver and COLMAP's own
688        // `EstimateGeneralizedAbsolutePose` has no analogous per-sensor
689        // bootstrap step.
690        for sensor_index in 0..(if self.minimal_solver == MinimalSolver::Dlt6pt {
691            rig.sensors().len()
692        } else {
693            0
694        }) {
695            let sensor_correspondences = correspondences
696                .iter()
697                .filter(|correspondence| correspondence.sensor_index == sensor_index)
698                .map(|correspondence| Correspondence2D3D {
699                    point2d: correspondence.point2d,
700                    point3d: correspondence.point3d,
701                    confidence: correspondence.confidence,
702                })
703                .collect::<Vec<_>>();
704            if sensor_correspondences.len() < 4 {
705                continue;
706            }
707            let central = PnPRansac {
708                pose_estimator: P3PGrunert,
709                pose_refiner: Some(GaussNewtonPoseRefiner::default()),
710                iterations: self.iterations.max(32),
711                reprojection_threshold: self.reprojection_threshold,
712                seed: self.seed.wrapping_add(sensor_index as u64),
713                early_stop_min_iterations: 16,
714                early_stop_inlier_ratio: Some(0.9),
715                confidence: self.confidence,
716                inlier_refits: 0,
717            };
718            let Some(report) =
719                central.estimate(&sensor_correspondences, &rig.sensors()[sensor_index].camera)
720            else {
721                continue;
722            };
723            central_hypotheses += 1;
724            let world_to_rig = rig.sensors()[sensor_index]
725                .sensor_from_rig
726                .inverse()
727                .compose(&report.pose.world_to_camera);
728            let pose = Pose {
729                world_to_camera: world_to_rig,
730            };
731            let score = score_pose(rig, &pose, correspondences, self.reprojection_threshold);
732            if std::env::var_os("VISLOC_SFM_DEBUG_PNP_HYPOTHESES").is_some() {
733                let own_sensor_inliers = score
734                    .inliers
735                    .iter()
736                    .filter(|&&i| correspondences[i].sensor_index == sensor_index)
737                    .count();
738                eprintln!(
739                    "generalized-pnp-central: sensor={sensor_index} correspondences={} central_inliers={} pooled_inliers={} own_sensor_inliers={own_sensor_inliers}",
740                    sensor_correspondences.len(), report.inliers.len(), score.inliers.len(),
741                );
742            }
743            if score.is_better_than(&best_score) {
744                best_pose = Some(pose);
745                best_score = score;
746            }
747        }
748
749        if std::env::var_os("VISLOC_SFM_DEBUG_PNP_HYPOTHESES").is_some() {
750            eprintln!(
751                "generalized-pnp-hypotheses: correspondences={} dlt_hypotheses={dlt_hypotheses} central_reports={central_hypotheses} pooled_inliers={} required={sample_size} prior={}",
752                correspondences.len(), best_score.inliers.len(), pose_prior.is_some(),
753            );
754        }
755        if best_score.inliers.len() < sample_size {
756            return None;
757        }
758        let inliers = best_score
759            .inliers
760            .iter()
761            .map(|index| correspondences[*index].clone())
762            .collect::<Vec<_>>();
763        // COLMAP's `EstimateGeneralizedAbsolutePose` (plain `RANSAC`, no
764        // local-optimization refit step) returns the best minimal-sample
765        // model directly into `RefineGeneralizedAbsolutePose` — so the
766        // intermediate linear-DLT refit below is specific to this port's
767        // A/B [`MinimalSolver::Dlt6pt`] path, where it compensates for the
768        // 6-point DLT's higher noise sensitivity; it is skipped for
769        // [`MinimalSolver::Gp3p`] to match COLMAP's flow exactly (the
770        // Gauss-Newton `pose_refiner` step below still runs either way,
771        // matching `RefineGeneralizedAbsolutePose`).
772        let refit_pose = if self.minimal_solver == MinimalSolver::Dlt6pt {
773            self.pose_estimator
774                .estimate_pose(rig, &inliers)
775                .filter(|pose| {
776                    let score = score_pose(rig, pose, correspondences, self.reprojection_threshold);
777                    !best_score.is_better_than(&score)
778                })
779        } else {
780            None
781        };
782        let mut pose = refit_pose.or(best_pose)?;
783        let refit_score = score_pose(rig, &pose, correspondences, self.reprojection_threshold);
784        let mut refinement_applied = false;
785        if let Some(refiner) = self.pose_refiner {
786            if let Some(candidate) = refiner.refine_pose(rig, &pose, &inliers) {
787                let candidate_score = score_pose(
788                    rig,
789                    &candidate,
790                    correspondences,
791                    self.reprojection_threshold,
792                );
793                if candidate_score.is_better_than(&refit_score)
794                    || (candidate_score.inliers.len() == refit_score.inliers.len()
795                        && candidate_score.mean_error <= refit_score.mean_error + 1.0e-12)
796                {
797                    pose = candidate;
798                    refinement_applied = true;
799                }
800            }
801        }
802        let score = score_pose(rig, &pose, correspondences, self.reprojection_threshold);
803        Some(GeneralizedRansacReport {
804            pose,
805            inliers: score.inliers,
806            inlier_reprojection_errors: score.errors,
807            mean_reprojection_error: score.mean_error,
808            median_reprojection_error: score.median_error,
809            max_reprojection_error: score.max_error,
810            refinement_applied,
811        })
812    }
813}
814
815#[derive(Debug, Clone)]
816struct GeneralizedScore {
817    inliers: Vec<usize>,
818    errors: Vec<f64>,
819    mean_error: f64,
820    median_error: f64,
821    max_error: f64,
822}
823
824impl GeneralizedScore {
825    const fn empty() -> Self {
826        Self {
827            inliers: Vec::new(),
828            errors: Vec::new(),
829            mean_error: f64::INFINITY,
830            median_error: f64::INFINITY,
831            max_error: f64::INFINITY,
832        }
833    }
834
835    fn is_better_than(&self, other: &Self) -> bool {
836        self.inliers.len() > other.inliers.len()
837            || (self.inliers.len() == other.inliers.len() && self.mean_error < other.mean_error)
838    }
839}
840
841fn score_pose(
842    rig: &GeneralizedCameraRig,
843    pose: &Pose,
844    correspondences: &[GeneralizedCorrespondence2D3D],
845    threshold: f64,
846) -> GeneralizedScore {
847    let mut indexed_errors = correspondences
848        .iter()
849        .enumerate()
850        .filter_map(|(index, correspondence)| {
851            let projected = rig.project(pose, correspondence)?;
852            let error = (projected - correspondence.point2d).norm();
853            (error.is_finite() && error <= threshold).then_some((index, error))
854        })
855        .collect::<Vec<_>>();
856    if indexed_errors.is_empty() {
857        return GeneralizedScore::empty();
858    }
859    let inliers = indexed_errors.iter().map(|(index, _)| *index).collect();
860    let errors = indexed_errors
861        .iter()
862        .map(|(_, error)| *error)
863        .collect::<Vec<_>>();
864    let mean_error = errors.iter().sum::<f64>() / errors.len() as f64;
865    indexed_errors.sort_by(|left, right| left.1.total_cmp(&right.1));
866    let median_error = indexed_errors[indexed_errors.len() / 2].1;
867    let max_error = indexed_errors.last().map_or(0.0, |entry| entry.1);
868    GeneralizedScore {
869        inliers,
870        errors,
871        mean_error,
872        median_error,
873        max_error,
874    }
875}
876
877/// Trivial-loss mean squared reprojection error — only used by
878/// `tests::nonlinear_refinement_reduces_joint_sensor_error` to report a
879/// loss-independent before/after error metric; [`GeneralizedGaussNewtonPoseRefiner::refine_pose`]
880/// itself now uses [`robust_cost`] (Cauchy-weighted) since it always applies
881/// a robust loss, see that struct's doc.
882#[cfg(test)]
883fn mean_squared_error(
884    rig: &GeneralizedCameraRig,
885    pose: &Pose,
886    correspondences: &[GeneralizedCorrespondence2D3D],
887) -> Option<f64> {
888    let residual = residuals(rig, pose, correspondences)?;
889    Some(residual.norm_squared() / correspondences.len() as f64)
890}
891
892fn residuals(
893    rig: &GeneralizedCameraRig,
894    pose: &Pose,
895    correspondences: &[GeneralizedCorrespondence2D3D],
896) -> Option<DVector<f64>> {
897    let mut residual = DVector::zeros(correspondences.len() * 2);
898    for (index, correspondence) in correspondences.iter().enumerate() {
899        let projected = rig.project(pose, correspondence)?;
900        residual[index * 2] = projected.x - correspondence.point2d.x;
901        residual[index * 2 + 1] = projected.y - correspondence.point2d.y;
902    }
903    Some(residual)
904}
905
906fn perturb_pose(pose: &Pose, delta: &DVector<f64>) -> Pose {
907    let rotation_delta =
908        UnitQuaternion::from_scaled_axis(Vector3::new(delta[0], delta[1], delta[2]));
909    let translation_delta = Vector3::new(delta[3], delta[4], delta[5]);
910    Pose::from_world_to_camera(
911        rotation_delta * pose.world_to_camera.rotation,
912        pose.world_to_camera.translation + translation_delta,
913    )
914}
915
916fn skew(vector: &Vector3<f64>) -> Matrix3<f64> {
917    Matrix3::new(
918        0.0, -vector.z, vector.y, vector.z, 0.0, -vector.x, -vector.y, vector.x, 0.0,
919    )
920}
921
922#[cfg(test)]
923mod tests {
924    use super::*;
925
926    fn test_rig() -> GeneralizedCameraRig {
927        let camera_left = Camera::pinhole(1, 848, 800, 285.0, 286.0, 425.5, 398.5);
928        let camera_right = Camera::pinhole(2, 848, 800, 284.8, 286.1, 428.0, 397.5);
929        GeneralizedCameraRig::new(vec![
930            RigSensor {
931                camera: camera_left,
932                sensor_from_rig: SE3::identity(),
933            },
934            RigSensor {
935                camera: camera_right,
936                // Right optical centre is +0.20 m on the rig x axis.
937                sensor_from_rig: SE3::new(
938                    UnitQuaternion::from_euler_angles(0.002, -0.004, 0.003),
939                    Vector3::new(-0.20, 0.001, -0.002),
940                ),
941            },
942        ])
943        .unwrap()
944    }
945
946    fn truth_pose() -> Pose {
947        Pose::from_world_to_camera(
948            UnitQuaternion::from_euler_angles(0.06, -0.12, 0.04),
949            Vector3::new(0.35, -0.18, 0.42),
950        )
951    }
952
953    fn synthetic_correspondences(
954        rig: &GeneralizedCameraRig,
955        pose: &Pose,
956    ) -> Vec<GeneralizedCorrespondence2D3D> {
957        let mut correspondences = Vec::new();
958        for index in 0..24 {
959            let point = Point3::new(
960                -1.6 + 0.31 * (index % 7) as f64,
961                -0.9 + 0.28 * (index % 5) as f64,
962                4.0 + 0.22 * index as f64 + 0.13 * (index % 3) as f64,
963            );
964            let sensor_index = index % 2;
965            let sensor = rig.sensor(sensor_index).unwrap();
966            let point_rig = pose.transform_world_point(&point);
967            let point_sensor = sensor.sensor_from_rig.transform_point(&point_rig);
968            let point2d = sensor.camera.project(&point_sensor).unwrap();
969            correspondences.push(GeneralizedCorrespondence2D3D {
970                sensor_index,
971                point2d,
972                point3d: point,
973                confidence: None,
974            });
975        }
976        correspondences
977    }
978
979    fn pose_errors(estimate: &Pose, truth: &Pose) -> (f64, f64) {
980        let rotation =
981            (estimate.world_to_camera.rotation * truth.world_to_camera.rotation.inverse()).angle();
982        let translation =
983            (estimate.world_to_camera.translation - truth.world_to_camera.translation).norm();
984        (rotation, translation)
985    }
986
987    #[test]
988    fn generalized_dlt_recovers_shared_rig_pose() {
989        let rig = test_rig();
990        let truth = truth_pose();
991        let correspondences = synthetic_correspondences(&rig, &truth);
992        let estimate = GeneralizedDltPoseEstimator::default()
993            .estimate_pose(&rig, &correspondences)
994            .unwrap();
995        let (rotation_error, translation_error) = pose_errors(&estimate, &truth);
996        assert!(rotation_error < 1.0e-8, "rotation error {rotation_error}");
997        assert!(
998            translation_error < 1.0e-8,
999            "translation error {translation_error}"
1000        );
1001    }
1002
1003    #[test]
1004    fn rejects_single_origin_instead_of_falling_back_to_central_pnp() {
1005        let rig = test_rig();
1006        let truth = truth_pose();
1007        let mut correspondences = synthetic_correspondences(&rig, &truth);
1008        correspondences.retain(|correspondence| correspondence.sensor_index == 0);
1009        assert!(GeneralizedDltPoseEstimator::default()
1010            .estimate_pose(&rig, &correspondences)
1011            .is_none());
1012    }
1013
1014    #[test]
1015    fn generalized_ransac_rejects_pixel_outliers_and_refines_one_pose() {
1016        let rig = test_rig();
1017        let truth = truth_pose();
1018        let mut correspondences = synthetic_correspondences(&rig, &truth);
1019        for index in [1usize, 6, 11, 16, 21] {
1020            correspondences[index].point2d.x += 90.0 + index as f64;
1021            correspondences[index].point2d.y -= 55.0;
1022        }
1023        let report = GeneralizedPnPRansac {
1024            iterations: 512,
1025            reprojection_threshold: 1.0,
1026            ..GeneralizedPnPRansac::default()
1027        }
1028        .estimate(&rig, &correspondences)
1029        .unwrap();
1030        let (rotation_error, translation_error) = pose_errors(&report.pose, &truth);
1031        assert_eq!(report.inliers.len(), 19);
1032        assert!(rotation_error < 1.0e-7, "rotation error {rotation_error}");
1033        assert!(
1034            translation_error < 1.0e-7,
1035            "translation error {translation_error}"
1036        );
1037        assert!(report.mean_reprojection_error < 1.0e-5);
1038    }
1039
1040    /// C3 task item: "RANSAC recovers it with 30% outliers" for the GP3P
1041    /// minimal solver path specifically (not relying on
1042    /// [`GeneralizedPnPRansac::default`] happening to already be
1043    /// [`MinimalSolver::Gp3p`], in case that default ever changes).
1044    #[test]
1045    fn gp3p_ransac_recovers_pose_with_thirty_percent_outliers() {
1046        let rig = test_rig();
1047        let truth = truth_pose();
1048        let mut correspondences = synthetic_correspondences(&rig, &truth);
1049        // 24 correspondences total (see `synthetic_correspondences`); flip
1050        // 7 (~29%) into gross pixel outliers.
1051        for index in [0usize, 3, 7, 10, 14, 18, 22] {
1052            correspondences[index].point2d.x += 120.0 + index as f64;
1053            correspondences[index].point2d.y -= 75.0;
1054        }
1055        let report = GeneralizedPnPRansac {
1056            minimal_solver: MinimalSolver::Gp3p,
1057            iterations: 1024,
1058            reprojection_threshold: 1.0,
1059            ..GeneralizedPnPRansac::default()
1060        }
1061        .estimate(&rig, &correspondences)
1062        .unwrap();
1063        let (rotation_error, translation_error) = pose_errors(&report.pose, &truth);
1064        assert_eq!(report.inliers.len(), correspondences.len() - 7);
1065        assert!(rotation_error < 1.0e-6, "rotation error {rotation_error}");
1066        assert!(
1067            translation_error < 1.0e-6,
1068            "translation error {translation_error}"
1069        );
1070    }
1071
1072    /// C3 task item: determinism with a fixed seed, at the RANSAC level
1073    /// (covers both GP3P's own internal auxiliary-randomness seeding, per
1074    /// `gp3p.rs`'s module doc, and the RANSAC sample-shuffling `SmallRng`).
1075    #[test]
1076    fn gp3p_ransac_is_deterministic_for_a_fixed_seed() {
1077        let rig = test_rig();
1078        let truth = truth_pose();
1079        let mut correspondences = synthetic_correspondences(&rig, &truth);
1080        for index in [1usize, 6, 11, 16, 21] {
1081            correspondences[index].point2d.x += 90.0 + index as f64;
1082            correspondences[index].point2d.y -= 55.0;
1083        }
1084        let config = GeneralizedPnPRansac {
1085            minimal_solver: MinimalSolver::Gp3p,
1086            iterations: 512,
1087            reprojection_threshold: 1.0,
1088            seed: 4242,
1089            ..GeneralizedPnPRansac::default()
1090        };
1091        let a = config.estimate(&rig, &correspondences).unwrap();
1092        let b = config.estimate(&rig, &correspondences).unwrap();
1093        assert_eq!(a.inliers, b.inliers);
1094        assert_eq!(
1095            a.pose.world_to_camera.rotation,
1096            b.pose.world_to_camera.rotation
1097        );
1098        assert_eq!(
1099            a.pose.world_to_camera.translation,
1100            b.pose.world_to_camera.translation
1101        );
1102    }
1103
1104    /// A/B: the pre-C3 6-point DLT path stays selectable and functional.
1105    #[test]
1106    fn dlt6pt_minimal_solver_still_selectable_and_recovers_pose() {
1107        let rig = test_rig();
1108        let truth = truth_pose();
1109        let mut correspondences = synthetic_correspondences(&rig, &truth);
1110        for index in [1usize, 6, 11, 16, 21] {
1111            correspondences[index].point2d.x += 90.0 + index as f64;
1112            correspondences[index].point2d.y -= 55.0;
1113        }
1114        let report = GeneralizedPnPRansac {
1115            minimal_solver: MinimalSolver::Dlt6pt,
1116            iterations: 512,
1117            reprojection_threshold: 1.0,
1118            ..GeneralizedPnPRansac::default()
1119        }
1120        .estimate(&rig, &correspondences)
1121        .unwrap();
1122        let (rotation_error, translation_error) = pose_errors(&report.pose, &truth);
1123        assert_eq!(report.inliers.len(), 19);
1124        assert!(rotation_error < 1.0e-6, "rotation error {rotation_error}");
1125        assert!(
1126            translation_error < 1.0e-6,
1127            "translation error {translation_error}"
1128        );
1129    }
1130
1131    #[test]
1132    fn nonlinear_refinement_reduces_joint_sensor_error() {
1133        let rig = test_rig();
1134        let truth = truth_pose();
1135        let correspondences = synthetic_correspondences(&rig, &truth);
1136        let initial = Pose::from_world_to_camera(
1137            UnitQuaternion::from_scaled_axis(Vector3::new(0.01, -0.008, 0.006))
1138                * truth.world_to_camera.rotation,
1139            truth.world_to_camera.translation + Vector3::new(0.04, -0.03, 0.02),
1140        );
1141        let before = mean_squared_error(&rig, &initial, &correspondences).unwrap();
1142        let refined = GeneralizedGaussNewtonPoseRefiner::default()
1143            .refine_pose(&rig, &initial, &correspondences)
1144            .unwrap();
1145        let after = mean_squared_error(&rig, &refined, &correspondences).unwrap();
1146        assert!(after < before * 1.0e-6, "before={before} after={after}");
1147        let (rotation_error, translation_error) = pose_errors(&refined, &truth);
1148        assert!(rotation_error < 1.0e-6);
1149        assert!(translation_error < 1.0e-6);
1150    }
1151}