visloc-vision 0.5.0

Feature, matching, PnP, RANSAC, and pose-refinement building blocks for visloc-rs.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
use rand::rngs::SmallRng;
use rand::seq::SliceRandom;
use rand::SeedableRng;
use visloc_core::geometry::{reproject, Pose};
use visloc_core::types::{
    Camera, PoseEstimationFailureDiagnostics, PoseEstimationFailureReason, PoseEstimatorDiagnostics,
};

use crate::pnp::{Correspondence2D3D, DltPnP, GaussNewtonPoseRefiner, PoseEstimator, PoseRefiner};

#[derive(Debug, Clone, PartialEq)]
pub struct RansacReport {
    pub pose: Pose,
    pub inliers: Vec<usize>,
    pub inlier_reprojection_errors: Vec<f64>,
    pub mean_reprojection_error: f64,
    pub median_reprojection_error: f64,
    pub max_reprojection_error: f64,
    pub diagnostics: PoseEstimatorDiagnostics,
}

#[derive(Debug, Clone, PartialEq)]
struct ReprojectionScore {
    inliers: Vec<usize>,
    inlier_errors: Vec<f64>,
    mean_error: f64,
    median_error: f64,
    max_error: f64,
}

pub trait RobustPoseEstimator {
    fn estimate(
        &self,
        correspondences: &[Correspondence2D3D],
        camera: &Camera,
    ) -> Option<RansacReport>;

    /// Confidence-aware variant: when `weights[i]` is high, correspondence
    /// `i` is preferred during RANSAC sampling (PROSAC-style). Default
    /// implementation falls back to the unweighted `estimate` so existing
    /// implementors don't need to change.
    fn estimate_with_weights(
        &self,
        correspondences: &[Correspondence2D3D],
        camera: &Camera,
        weights: &[f32],
    ) -> Option<RansacReport> {
        let _ = weights;
        self.estimate(correspondences, camera)
    }

    /// Prior-aware variant: when `pose_prior` is `Some`, the estimator
    /// MAY seed its search with the prior pose as an initial hypothesis
    /// (so a successful prior short-circuits RANSAC and a failed prior
    /// is still beaten by the standard random search). Default
    /// implementation ignores the prior and delegates to the weighted /
    /// unweighted path so existing implementors don't need to change.
    fn estimate_with_pose_prior_and_weights(
        &self,
        correspondences: &[Correspondence2D3D],
        camera: &Camera,
        pose_prior: Option<&Pose>,
        weights: Option<&[f32]>,
    ) -> Option<RansacReport> {
        let _ = pose_prior;
        match weights {
            Some(w) => self.estimate_with_weights(correspondences, camera, w),
            None => self.estimate(correspondences, camera),
        }
    }

    fn failure_diagnostics(
        &self,
        _correspondences: &[Correspondence2D3D],
        _camera: &Camera,
    ) -> Option<PoseEstimationFailureDiagnostics> {
        None
    }
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub struct PnPRansac<P = DltPnP, R = GaussNewtonPoseRefiner> {
    pub pose_estimator: P,
    pub pose_refiner: Option<R>,
    pub iterations: usize,
    pub reprojection_threshold: f64,
    pub seed: u64,
    /// Stop the RANSAC search after this many trials when
    /// `early_stop_inlier_ratio` is also satisfied. Set the ratio to `None`
    /// to force the full iteration budget.
    pub early_stop_min_iterations: usize,
    /// Optional consensus-ratio threshold for early termination. This keeps
    /// high-consensus PnP pairs from spending the full budget scoring
    /// near-identical hypotheses.
    pub early_stop_inlier_ratio: Option<f64>,
    /// COLMAP-style dynamic iteration budget: when set, `iterations` becomes
    /// a *maximum* cap and the search stops as soon as the best model's
    /// inlier ratio implies, with this confidence, that enough samples have
    /// been drawn (`needed = log(1-conf)/log(1-w^s)`, standard RANSAC
    /// termination). `None` keeps the fixed budget.
    pub confidence: Option<f64>,
    /// After the final refinement, re-collect the inliers of the refined
    /// pose and refine again on them, up to this many times (until the set
    /// stops changing or a round does not improve the score). The RANSAC
    /// winner comes from a three-point sample, so its inliers can include
    /// outliers that happen to sit within the threshold of that noisy pose,
    /// and the least-squares refinement fits them too. 0 (the default) keeps
    /// the single refinement on the winner's inliers.
    pub inlier_refits: usize,
}

impl Default for PnPRansac {
    fn default() -> Self {
        Self {
            pose_estimator: DltPnP::default(),
            pose_refiner: Some(GaussNewtonPoseRefiner::default()),
            confidence: None,
            iterations: 128,
            reprojection_threshold: 4.0,
            seed: 7,
            early_stop_min_iterations: 0,
            early_stop_inlier_ratio: None,
            inlier_refits: 0,
        }
    }
}

impl<P, R> RobustPoseEstimator for PnPRansac<P, R>
where
    P: PoseEstimator,
    R: PoseRefiner,
{
    fn failure_diagnostics(
        &self,
        correspondences: &[Correspondence2D3D],
        camera: &Camera,
    ) -> Option<PoseEstimationFailureDiagnostics> {
        let sample_size = self.pose_estimator.minimum_correspondences();
        if correspondences.len() < sample_size {
            return Some(PoseEstimationFailureDiagnostics {
                reason: PoseEstimationFailureReason::InsufficientCorrespondences,
                correspondence_count: correspondences.len(),
                minimum_correspondence_count: Some(sample_size),
                ransac_iterations: Some(self.iterations),
                ransac_reprojection_threshold: Some(self.reprojection_threshold),
                best_inlier_count: None,
            });
        }

        let search = self.search_best_pose(correspondences, camera, sample_size, None, None);
        Some(PoseEstimationFailureDiagnostics {
            reason: if search.best_pose.is_some() {
                PoseEstimationFailureReason::EstimatorRejected
            } else {
                PoseEstimationFailureReason::NoValidPose
            },
            correspondence_count: correspondences.len(),
            minimum_correspondence_count: Some(sample_size),
            ransac_iterations: Some(self.iterations),
            ransac_reprojection_threshold: Some(self.reprojection_threshold),
            best_inlier_count: Some(search.best_inliers.len()),
        })
    }

    fn estimate(
        &self,
        correspondences: &[Correspondence2D3D],
        camera: &Camera,
    ) -> Option<RansacReport> {
        self.estimate_with_optional_inputs(correspondences, camera, None, None)
    }

    /// PROSAC-style PnP RANSAC: sort correspondences by descending weight
    /// (e.g. matcher confidence) and expand the sampling subset linearly
    /// from `sample_size` to `n` over the iteration budget. High-confidence
    /// correspondences anchor early iterations. Falls back to the uniform
    /// shuffle when `weights` is the wrong length, all-zero, or
    /// non-finite.
    fn estimate_with_weights(
        &self,
        correspondences: &[Correspondence2D3D],
        camera: &Camera,
        weights: &[f32],
    ) -> Option<RansacReport> {
        if weights.len() != correspondences.len() {
            return self.estimate(correspondences, camera);
        }
        self.estimate_with_optional_inputs(correspondences, camera, Some(weights), None)
    }

    fn estimate_with_pose_prior_and_weights(
        &self,
        correspondences: &[Correspondence2D3D],
        camera: &Camera,
        pose_prior: Option<&Pose>,
        weights: Option<&[f32]>,
    ) -> Option<RansacReport> {
        let valid_weights = weights.and_then(|w| (w.len() == correspondences.len()).then_some(w));
        self.estimate_with_optional_inputs(correspondences, camera, valid_weights, pose_prior)
    }
}

impl<P, R> PnPRansac<P, R>
where
    P: PoseEstimator,
    R: PoseRefiner,
{
    fn estimate_with_optional_inputs(
        &self,
        correspondences: &[Correspondence2D3D],
        camera: &Camera,
        weights: Option<&[f32]>,
        pose_prior: Option<&Pose>,
    ) -> Option<RansacReport> {
        let sample_size = self.pose_estimator.minimum_correspondences();
        if correspondences.len() < sample_size {
            return None;
        }

        let search =
            self.search_best_pose(correspondences, camera, sample_size, weights, pose_prior);

        if search.best_inliers.len() >= sample_size {
            let refined = search
                .best_inliers
                .iter()
                .map(|index| correspondences[*index].clone())
                .collect::<Vec<_>>();
            // Start from the better of the search's winner and a refit of
            // the pose estimator on all its inliers. The refit alone is not
            // enough: a minimal solver re-run on the inliers solves from three
            // of them and can land far from the winner (on Courthouse it
            // turned 700 correspondences with hundreds of inliers into 3-6),
            // which then failed registration.
            let mut start: Option<(Pose, ReprojectionScore)> =
                search.best_pose.as_ref().map(|pose| {
                    let score =
                        score_pose(camera, pose, correspondences, self.reprojection_threshold);
                    (pose.clone(), score)
                });
            if let Some(refit) = self.pose_estimator.estimate_pose(&refined, camera) {
                let score =
                    score_pose(camera, &refit, correspondences, self.reprojection_threshold);
                if start
                    .as_ref()
                    .is_none_or(|(_, best)| is_refinement_better(&score, best))
                {
                    start = Some((refit, score));
                }
            }
            if let Some((mut refined_pose, pre_refinement_score)) = start {
                let mut refinement_applied = false;
                if let Some(pose_refiner) = &self.pose_refiner {
                    if let Some(nonlinear_pose) =
                        pose_refiner.refine_pose(&refined_pose, &refined, camera)
                    {
                        let nonlinear_score = score_pose(
                            camera,
                            &nonlinear_pose,
                            correspondences,
                            self.reprojection_threshold,
                        );
                        if is_refinement_better(&nonlinear_score, &pre_refinement_score) {
                            refined_pose = nonlinear_pose;
                            refinement_applied = true;
                        }
                    }
                }
                let mut score = score_pose(
                    camera,
                    &refined_pose,
                    correspondences,
                    self.reprojection_threshold,
                );
                if let Some(pose_refiner) = &self.pose_refiner {
                    let mut fitted = search.best_inliers.clone();
                    for _ in 0..self.inlier_refits {
                        if score.inliers == fitted {
                            break;
                        }
                        let set = score
                            .inliers
                            .iter()
                            .map(|index| correspondences[*index].clone())
                            .collect::<Vec<_>>();
                        let Some(pose) = pose_refiner.refine_pose(&refined_pose, &set, camera)
                        else {
                            break;
                        };
                        let refit_score =
                            score_pose(camera, &pose, correspondences, self.reprojection_threshold);
                        if !is_refinement_better(&refit_score, &score) {
                            break;
                        }
                        fitted = score.inliers;
                        refined_pose = pose;
                        refinement_applied = true;
                        score = refit_score;
                    }
                }
                return Some(RansacReport {
                    pose: refined_pose,
                    inliers: score.inliers,
                    inlier_reprojection_errors: score.inlier_errors,
                    mean_reprojection_error: score.mean_error,
                    median_reprojection_error: score.median_error,
                    max_reprojection_error: score.max_error,
                    diagnostics: PoseEstimatorDiagnostics {
                        refinement_applied,
                        pre_refinement_mean_reprojection_error: Some(
                            pre_refinement_score.mean_error,
                        ),
                        post_refinement_mean_reprojection_error: Some(score.mean_error),
                        refinement_error_delta: Some(
                            pre_refinement_score.mean_error - score.mean_error,
                        ),
                    },
                });
            }
        }

        search.best_pose.map(|pose| {
            let score = score_pose(camera, &pose, correspondences, self.reprojection_threshold);
            RansacReport {
                pose,
                inliers: score.inliers,
                inlier_reprojection_errors: score.inlier_errors,
                mean_reprojection_error: score.mean_error,
                median_reprojection_error: score.median_error,
                max_reprojection_error: score.max_error,
                diagnostics: PoseEstimatorDiagnostics {
                    refinement_applied: false,
                    pre_refinement_mean_reprojection_error: None,
                    post_refinement_mean_reprojection_error: Some(score.mean_error),
                    refinement_error_delta: None,
                },
            }
        })
    }
}

impl<P, R> PnPRansac<P, R>
where
    P: PoseEstimator,
{
    fn search_best_pose(
        &self,
        correspondences: &[Correspondence2D3D],
        camera: &Camera,
        sample_size: usize,
        weights: Option<&[f32]>,
        pose_prior: Option<&Pose>,
    ) -> RansacSearchResult {
        let mut rng = SmallRng::seed_from_u64(self.seed);
        let n = correspondences.len();
        // PROSAC ordering: sort indices by descending weight when weights
        // are usable; otherwise fall back to natural order + uniform
        // shuffle (the original behaviour).
        let weighted =
            weights.filter(|w| w.len() == n && w.iter().any(|&v| v.is_finite() && v > 0.0));
        let mut sorted_indices: Vec<usize> = (0..n).collect();
        if let Some(w) = weighted {
            sorted_indices
                .sort_by(|&a, &b| w[b].partial_cmp(&w[a]).unwrap_or(std::cmp::Ordering::Equal));
        }

        let mut best_pose = None;
        let mut best_inliers = Vec::new();
        let mut best_error = f64::INFINITY;

        // Warm-start with the pose prior, if supplied. Random samples
        // must beat its inlier count to win, so a well-aligned prior
        // short-circuits RANSAC on hard scenes while a misaligned prior
        // gracefully degrades to the standard random search.
        if let Some(prior) = pose_prior {
            let score =
                score_hypothesis(camera, prior, correspondences, self.reprojection_threshold);
            if !score.inliers.is_empty() {
                best_pose = Some(prior.clone());
                best_inliers = score.inliers;
                best_error = score.mean_error;
            }
        }
        let total_iters = self.iterations.max(1);
        let expansion_iters = if weighted.is_some() && self.early_stop_inlier_ratio.is_some() {
            self.early_stop_min_iterations.max(1).min(total_iters)
        } else {
            total_iters
        };
        let expansion_denom = expansion_iters.saturating_sub(1).max(1);

        // Dynamic RANSAC termination (COLMAP `UpdateNumIterations`): with a
        // confidence target, the required sample count shrinks as the best
        // model's inlier ratio grows.
        // A fixed budget (no early stop, no dynamic termination, uniform
        // sampling) can draw every sample up front, in the same order from
        // the same RNG, and score the hypotheses in parallel: picking the
        // best in iteration order afterwards is the serial loop exactly.
        #[cfg(feature = "parallel")]
        if weighted.is_none()
            && self.early_stop_inlier_ratio.is_none()
            && self.confidence.is_none()
            && self.iterations > 1
        {
            use rayon::prelude::*;
            let samples: Vec<Vec<Correspondence2D3D>> = (0..self.iterations)
                .map(|_| {
                    let mut subset: Vec<usize> = sorted_indices[..n].to_vec();
                    subset.shuffle(&mut rng);
                    subset
                        .iter()
                        .take(sample_size)
                        .map(|index| correspondences[*index].clone())
                        .collect()
                })
                .collect();
            let (estimator, threshold) = (&self.pose_estimator, self.reprojection_threshold);
            let hypotheses: Vec<Option<(Pose, HypothesisScore)>> = samples
                .par_iter()
                .map(|sample| {
                    let pose = estimator.estimate_pose(sample, camera)?;
                    let score = score_hypothesis(camera, &pose, correspondences, threshold);
                    Some((pose, score))
                })
                .collect();
            for (pose, score) in hypotheses.into_iter().flatten() {
                if score.inliers.len() > best_inliers.len()
                    || (score.inliers.len() == best_inliers.len() && score.mean_error < best_error)
                {
                    best_pose = Some(pose);
                    best_inliers = score.inliers;
                    best_error = score.mean_error;
                }
            }
            return RansacSearchResult {
                best_pose,
                best_inliers,
            };
        }

        let mut required_iterations = self.iterations.max(1);
        for iteration in 0..self.iterations {
            // PROSAC shrinking sample-set: m_k expands linearly from
            // `sample_size` to `n`. When an early-stop guard is active,
            // expand over that guard window instead of the whole budget so
            // a larger fail-safe iteration count does not delay good samples.
            // When weights are absent this collapses to `m_k = n` and the
            // shuffle samples uniformly across all correspondences.
            let m_k = if weighted.is_some() {
                let progress = (iteration.min(expansion_denom)) as f64 / expansion_denom as f64;
                let m = sample_size as f64 + (n - sample_size) as f64 * progress;
                (m.ceil() as usize).clamp(sample_size, n)
            } else {
                n
            };
            let mut subset: Vec<usize> = sorted_indices[..m_k].to_vec();
            subset.shuffle(&mut rng);
            let sample: Vec<Correspondence2D3D> = subset
                .iter()
                .take(sample_size)
                .map(|index| correspondences[*index].clone())
                .collect();

            let Some(pose) = self.pose_estimator.estimate_pose(&sample, camera) else {
                continue;
            };

            let score =
                score_hypothesis(camera, &pose, correspondences, self.reprojection_threshold);
            if score.inliers.len() > best_inliers.len()
                || (score.inliers.len() == best_inliers.len() && score.mean_error < best_error)
            {
                best_pose = Some(pose);
                best_inliers = score.inliers;
                best_error = score.mean_error;
            }

            if should_stop_pnp_search_early(
                iteration + 1,
                best_pose.is_some(),
                best_inliers.len(),
                n,
                self.early_stop_min_iterations,
                self.early_stop_inlier_ratio,
            ) {
                break;
            }

            if let Some(confidence) = self.confidence {
                let w = if n > 0 {
                    best_inliers.len() as f64 / n as f64
                } else {
                    0.0
                };
                if w > 0.0 && w < 1.0 {
                    // needed = log(1-confidence) / log(1 - w^s)
                    let denom = (1.0 - w.powi(sample_size as i32)).ln();
                    if denom < -1e-12 {
                        let needed = ((1.0 - confidence).ln() / denom).ceil().max(1.0) as usize;
                        required_iterations = required_iterations.min(needed);
                    }
                } else if w >= 1.0 {
                    required_iterations = iteration + 1; // perfect consensus
                }
                if iteration + 1 >= required_iterations {
                    break;
                }
            }
        }

        RansacSearchResult {
            best_pose,
            best_inliers,
        }
    }
}

fn should_stop_pnp_search_early(
    completed_iterations: usize,
    has_pose: bool,
    best_inliers: usize,
    total_correspondences: usize,
    min_iterations: usize,
    inlier_ratio: Option<f64>,
) -> bool {
    let Some(inlier_ratio) = inlier_ratio else {
        return false;
    };
    if !has_pose
        || completed_iterations < min_iterations.max(1)
        || total_correspondences == 0
        || !inlier_ratio.is_finite()
        || inlier_ratio <= 0.0
    {
        return false;
    }
    (best_inliers as f64) >= inlier_ratio.min(1.0) * total_correspondences as f64
}

fn is_refinement_better(candidate: &ReprojectionScore, baseline: &ReprojectionScore) -> bool {
    let candidate_inliers = candidate.inliers.len();
    let baseline_inliers = baseline.inliers.len();
    candidate_inliers > baseline_inliers
        || (candidate_inliers == baseline_inliers
            && candidate.mean_error <= baseline.mean_error + 1.0e-9)
}

#[derive(Debug, Clone, PartialEq)]
struct RansacSearchResult {
    best_pose: Option<Pose>,
    best_inliers: Vec<usize>,
}

/// What the hypothesis search compares: the inliers and their mean error
/// ([`score_pose`] without the median and maximum, whose sort of every
/// inlier error per hypothesis was a large part of a registration).
struct HypothesisScore {
    inliers: Vec<usize>,
    mean_error: f64,
}

fn score_hypothesis(
    camera: &Camera,
    pose: &Pose,
    correspondences: &[Correspondence2D3D],
    threshold: f64,
) -> HypothesisScore {
    let mut inliers = Vec::new();
    let mut error_sum = 0.0;
    for (index, correspondence) in correspondences.iter().enumerate() {
        let Some(projected) = reproject(camera, pose, &correspondence.point3d) else {
            continue;
        };
        let error = camera
            .pixel_residual(&projected, &correspondence.point2d)
            .norm();
        if error <= threshold {
            inliers.push(index);
            error_sum += error;
        }
    }
    // The same sum, in the same order, as `reprojection_stats`' mean.
    let mean_error = if inliers.is_empty() {
        f64::INFINITY
    } else {
        error_sum / inliers.len() as f64
    };
    HypothesisScore {
        inliers,
        mean_error,
    }
}

fn score_pose(
    camera: &Camera,
    pose: &Pose,
    correspondences: &[Correspondence2D3D],
    threshold: f64,
) -> ReprojectionScore {
    let mut inliers = Vec::new();
    let mut inlier_errors = Vec::new();

    for (index, correspondence) in correspondences.iter().enumerate() {
        let Some(projected) = reproject(camera, pose, &correspondence.point3d) else {
            continue;
        };
        let error = camera
            .pixel_residual(&projected, &correspondence.point2d)
            .norm();
        if error <= threshold {
            inliers.push(index);
            inlier_errors.push(error);
        }
    }

    let (mean_error, median_error, max_error) = reprojection_stats(&inlier_errors);
    ReprojectionScore {
        inliers,
        inlier_errors,
        mean_error,
        median_error,
        max_error,
    }
}

fn reprojection_stats(errors: &[f64]) -> (f64, f64, f64) {
    if errors.is_empty() {
        return (f64::INFINITY, f64::INFINITY, f64::INFINITY);
    }

    let mean = errors.iter().sum::<f64>() / errors.len() as f64;
    let mut sorted = errors.to_vec();
    sorted.sort_by(f64::total_cmp);
    let median = if sorted.len().is_multiple_of(2) {
        let upper = sorted.len() / 2;
        (sorted[upper - 1] + sorted[upper]) * 0.5
    } else {
        sorted[sorted.len() / 2]
    };
    let max = *sorted.last().expect("errors is non-empty");
    (mean, median, max)
}

#[cfg(test)]
mod tests {
    use super::{
        is_refinement_better, should_stop_pnp_search_early, PnPRansac, ReprojectionScore,
        RobustPoseEstimator,
    };
    use crate::pnp::{Correspondence2D3D, PoseEstimator};
    use nalgebra::{Point3, UnitQuaternion, Vector3};
    use visloc_core::geometry::Pose;
    use visloc_core::types::Camera;

    #[derive(Debug, Clone, Copy)]
    struct IdentityPnP {
        min_correspondences: usize,
    }

    impl PoseEstimator for IdentityPnP {
        fn estimate_pose(
            &self,
            _correspondences: &[Correspondence2D3D],
            _camera: &Camera,
        ) -> Option<Pose> {
            Some(Pose::identity())
        }

        fn minimum_correspondences(&self) -> usize {
            self.min_correspondences
        }
    }

    fn reprojection_score(inlier_count: usize, mean_error: f64) -> ReprojectionScore {
        ReprojectionScore {
            inliers: (0..inlier_count).collect(),
            inlier_errors: vec![mean_error; inlier_count],
            mean_error,
            median_error: mean_error,
            max_error: mean_error,
        }
    }

    #[test]
    fn refinement_guard_rejects_worse_reprojection_consensus() {
        let baseline = reprojection_score(12, 0.8);
        let worse_error = reprojection_score(12, 0.9);
        let fewer_inliers = reprojection_score(11, 0.1);
        let more_inliers = reprojection_score(13, 1.2);
        let same_or_better = reprojection_score(12, 0.8);

        assert!(!is_refinement_better(&worse_error, &baseline));
        assert!(!is_refinement_better(&fewer_inliers, &baseline));
        assert!(is_refinement_better(&more_inliers, &baseline));
        assert!(is_refinement_better(&same_or_better, &baseline));
    }

    /// A pose estimator that solves its minimal samples exactly but returns
    /// a far-off pose when refit on more points, like a minimal solver run
    /// on three of many noisy inliers.
    #[derive(Debug, Clone)]
    struct BadRefitPnP {
        truth: Pose,
    }

    impl PoseEstimator for BadRefitPnP {
        fn estimate_pose(
            &self,
            correspondences: &[Correspondence2D3D],
            _camera: &Camera,
        ) -> Option<Pose> {
            if correspondences.len() == self.minimum_correspondences() {
                Some(self.truth.clone())
            } else {
                Some(Pose::from_world_to_camera(
                    UnitQuaternion::from_euler_angles(0.0, 0.3, 0.0),
                    Vector3::new(2.0, 0.0, 0.0),
                ))
            }
        }

        fn minimum_correspondences(&self) -> usize {
            4
        }
    }

    #[test]
    fn a_bad_refit_does_not_replace_the_search_winner() {
        let camera = Camera::pinhole(1, 640, 480, 500.0, 500.0, 320.0, 240.0);
        let truth = Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::zeros());
        let correspondences = (0..40)
            .map(|i| {
                let point3d = Point3::new(
                    (i % 8) as f64 * 0.3 - 1.0,
                    (i / 8) as f64 * 0.3 - 0.6,
                    4.0 + (i % 5) as f64,
                );
                Correspondence2D3D {
                    point2d: camera
                        .project(&truth.transform_world_point(&point3d))
                        .unwrap(),
                    point3d,
                    confidence: None,
                }
            })
            .collect::<Vec<_>>();

        let report = PnPRansac {
            pose_estimator: BadRefitPnP {
                truth: truth.clone(),
            },
            pose_refiner: None::<crate::pnp::GaussNewtonPoseRefiner>,
            iterations: 8,
            confidence: None,
            reprojection_threshold: 2.0,
            seed: 3,
            early_stop_min_iterations: 0,
            early_stop_inlier_ratio: None,
            inlier_refits: 0,
        }
        .estimate(&correspondences, &camera)
        .unwrap();

        assert_eq!(report.inliers.len(), correspondences.len());
        assert_eq!(report.pose, truth);
    }

    #[test]
    fn ransac_accepts_custom_minimal_pose_estimator() {
        let camera = Camera::pinhole(1, 640, 480, 500.0, 500.0, 320.0, 240.0);
        let pose = Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::zeros());
        let points = vec![
            Point3::new(-1.0, -1.0, 4.0),
            Point3::new(1.0, -1.0, 4.5),
            Point3::new(-1.0, 1.0, 5.0),
        ];
        let correspondences = points
            .into_iter()
            .map(|point3d| Correspondence2D3D {
                point2d: camera
                    .project(&pose.transform_world_point(&point3d))
                    .unwrap(),
                point3d,
                confidence: None,
            })
            .collect::<Vec<_>>();

        let report = PnPRansac {
            pose_estimator: IdentityPnP {
                min_correspondences: 3,
            },
            pose_refiner: None::<crate::pnp::GaussNewtonPoseRefiner>,
            iterations: 8,
            confidence: None,
            reprojection_threshold: 1.0e-6,
            seed: 3,
            early_stop_min_iterations: 0,
            early_stop_inlier_ratio: None,
            inlier_refits: 0,
        }
        .estimate(&correspondences, &camera)
        .unwrap();

        assert_eq!(report.inliers.len(), 3);
        assert_eq!(report.inlier_reprojection_errors.len(), 3);
        assert!(report.max_reprojection_error < 1.0e-9);
        assert!(!report.diagnostics.refinement_applied);
        assert_eq!(report.pose, Pose::identity());
    }

    #[test]
    fn weighted_pnp_ransac_recovers_pose_with_outlier_heavy_input() {
        use crate::pnp::DltPnP;
        let camera = Camera::pinhole(1, 640, 480, 500.0, 500.0, 320.0, 240.0);
        let pose =
            Pose::from_world_to_camera(UnitQuaternion::identity(), Vector3::new(0.0, 0.0, 0.0));
        // 12 inliers from a real geometry + 24 random outliers with
        // mismatched 2D pixels. Inliers carry confidence 0.9, outliers 0.05.
        let inlier_points = [
            Point3::new(-1.0, -1.0, 4.0),
            Point3::new(1.0, -1.0, 4.5),
            Point3::new(-1.0, 1.0, 5.0),
            Point3::new(1.0, 1.0, 4.7),
            Point3::new(0.0, 0.0, 5.2),
            Point3::new(0.5, -0.25, 6.0),
            Point3::new(-0.5, 0.25, 5.5),
            Point3::new(-0.7, 0.4, 4.5),
            Point3::new(0.6, 0.8, 5.5),
            Point3::new(-0.3, -0.6, 4.8),
            Point3::new(0.2, 0.2, 6.5),
            Point3::new(-0.2, 0.7, 5.7),
        ];
        let mut correspondences: Vec<Correspondence2D3D> = inlier_points
            .iter()
            .map(|p| Correspondence2D3D {
                point2d: camera.project(&pose.transform_world_point(p)).unwrap(),
                point3d: *p,
                confidence: None,
            })
            .collect();
        let n_inliers = correspondences.len();
        let mut weights: Vec<f32> = vec![0.9; n_inliers];

        // Outlier rays: random 3D points with off-image 2D coords.
        let outlier_seeds = [
            (0.4_f64, 0.3, 7.0, 100.0_f64, 50.0_f64),
            (-0.6, 0.5, 8.0, 580.0, 60.0),
            (0.1, -0.8, 5.0, 50.0, 420.0),
            (0.7, -0.3, 6.0, 600.0, 410.0),
            (-0.4, -0.4, 9.0, 320.0, 60.0),
            (0.5, 0.5, 5.5, 40.0, 240.0),
            (-0.7, 0.0, 7.5, 600.0, 240.0),
            (0.0, -0.6, 4.5, 320.0, 420.0),
            (0.2, 0.7, 6.5, 540.0, 100.0),
            (-0.5, -0.6, 5.0, 80.0, 160.0),
            (0.3, 0.4, 5.8, 340.0, 320.0),
            (-0.2, 0.6, 6.2, 200.0, 80.0),
            (0.6, -0.5, 4.5, 460.0, 360.0),
            (0.4, 0.2, 5.0, 260.0, 200.0),
            (-0.8, 0.3, 7.0, 540.0, 220.0),
            (0.1, 0.5, 5.5, 60.0, 300.0),
            (0.5, 0.6, 6.0, 480.0, 100.0),
            (-0.3, -0.7, 4.8, 380.0, 380.0),
            (0.7, 0.1, 5.3, 60.0, 80.0),
            (-0.6, -0.4, 6.5, 580.0, 280.0),
            (0.0, 0.4, 5.6, 200.0, 240.0),
            (-0.4, 0.0, 5.2, 420.0, 280.0),
            (0.2, -0.5, 5.0, 120.0, 360.0),
            (0.1, 0.3, 6.0, 540.0, 60.0),
        ];
        for (px, py, pz, cx, cy) in outlier_seeds {
            correspondences.push(Correspondence2D3D {
                point2d: nalgebra::Point2::new(cx, cy),
                point3d: Point3::new(px, py, pz),
                confidence: None,
            });
            weights.push(0.05);
        }
        assert_eq!(weights.len(), correspondences.len());

        let ransac = PnPRansac {
            pose_estimator: DltPnP::default(),
            pose_refiner: None::<crate::pnp::GaussNewtonPoseRefiner>,
            iterations: 64,
            reprojection_threshold: 2.0,
            seed: 11,
            early_stop_min_iterations: 0,
            confidence: None,
            early_stop_inlier_ratio: None,
            inlier_refits: 0,
        };

        let weighted = ransac
            .estimate_with_weights(&correspondences, &camera, &weights)
            .expect("weighted PnP RANSAC must recover the pose");

        let recovered_inliers: usize = weighted.inliers.iter().filter(|&&i| i < n_inliers).count();
        assert!(
            recovered_inliers >= n_inliers - 1,
            "weighted PnP RANSAC should recover the geometric inliers, got {}/{}",
            recovered_inliers,
            n_inliers
        );
    }

    #[test]
    fn weighted_pnp_ransac_falls_back_to_uniform_when_weight_length_mismatches() {
        use crate::pnp::DltPnP;
        let camera = Camera::pinhole(1, 640, 480, 500.0, 500.0, 320.0, 240.0);
        let pose = Pose::identity();
        let points = [
            Point3::new(-1.0, -1.0, 4.0),
            Point3::new(1.0, -1.0, 4.5),
            Point3::new(-1.0, 1.0, 5.0),
            Point3::new(1.0, 1.0, 4.7),
            Point3::new(0.0, 0.0, 5.2),
            Point3::new(0.5, -0.25, 6.0),
        ];
        let correspondences: Vec<Correspondence2D3D> = points
            .iter()
            .map(|p| Correspondence2D3D {
                point2d: camera.project(&pose.transform_world_point(p)).unwrap(),
                point3d: *p,
                confidence: None,
            })
            .collect();
        let bad_weights = vec![1.0_f32; correspondences.len() + 3]; // wrong length
        let ransac = PnPRansac {
            pose_estimator: DltPnP::default(),
            pose_refiner: None::<crate::pnp::GaussNewtonPoseRefiner>,
            iterations: 16,
            reprojection_threshold: 1.0e-3,
            seed: 7,
            early_stop_min_iterations: 0,
            confidence: None,
            early_stop_inlier_ratio: None,
            inlier_refits: 0,
        };
        let unweighted = ransac.estimate(&correspondences, &camera).unwrap();
        let fallback = ransac
            .estimate_with_weights(&correspondences, &camera, &bad_weights)
            .unwrap();
        assert_eq!(unweighted.inliers, fallback.inliers);
    }

    #[test]
    fn pnp_early_stop_requires_pose_min_iterations_and_ratio() {
        assert!(!should_stop_pnp_search_early(100, true, 90, 100, 100, None));
        assert!(!should_stop_pnp_search_early(
            99,
            true,
            90,
            100,
            100,
            Some(0.85)
        ));
        assert!(!should_stop_pnp_search_early(
            100,
            false,
            90,
            100,
            100,
            Some(0.85)
        ));
        assert!(!should_stop_pnp_search_early(
            100,
            true,
            84,
            100,
            100,
            Some(0.85)
        ));
        assert!(should_stop_pnp_search_early(
            100,
            true,
            85,
            100,
            100,
            Some(0.85)
        ));
    }

    #[test]
    fn pnp_ransac_pose_prior_warm_start_recovers_when_random_search_fails() {
        use crate::pnp::DltPnP;
        // Scene: 7 correspondences perfectly consistent with the
        // identity pose, plus 5 outliers (3D points whose pixels are
        // scrambled). With iterations=1, the unweighted random search
        // has a ~0.76 % chance of stumbling on a 6-of-7 inlier sample
        // and at seed=1234 it does not — so the no-prior estimate
        // returns `None`. The warm-start path, in contrast, scores the
        // identity prior against the correspondences before the loop,
        // seeds `best_inliers` with the 7 geometric inliers, and
        // refines via DLT on those inliers, returning a valid report.
        let camera = Camera::pinhole(1, 640, 480, 500.0, 500.0, 320.0, 240.0);
        let pose = Pose::identity();
        let inlier_points = [
            Point3::new(-1.0, -1.0, 4.0),
            Point3::new(1.0, -1.0, 4.5),
            Point3::new(-1.0, 1.0, 5.0),
            Point3::new(1.0, 1.0, 4.7),
            Point3::new(0.0, 0.0, 5.2),
            Point3::new(0.5, -0.25, 6.0),
            Point3::new(-0.5, 0.25, 5.5),
        ];
        let mut correspondences: Vec<Correspondence2D3D> = inlier_points
            .iter()
            .map(|p| Correspondence2D3D {
                point2d: camera.project(&pose.transform_world_point(p)).unwrap(),
                point3d: *p,
                confidence: None,
            })
            .collect();
        let n_inliers = correspondences.len();
        let outlier_seeds = [
            (0.4_f64, 0.3, 7.0, 50.0_f64, 50.0_f64),
            (-0.6, 0.5, 8.0, 590.0, 50.0),
            (0.1, -0.8, 5.0, 50.0, 430.0),
            (0.7, -0.3, 6.0, 600.0, 410.0),
            (-0.4, -0.4, 9.0, 320.0, 50.0),
        ];
        for (px, py, pz, cx, cy) in outlier_seeds {
            correspondences.push(Correspondence2D3D {
                point2d: nalgebra::Point2::new(cx, cy),
                point3d: Point3::new(px, py, pz),
                confidence: None,
            });
        }

        let ransac = PnPRansac {
            pose_estimator: DltPnP::default(),
            pose_refiner: None::<crate::pnp::GaussNewtonPoseRefiner>,
            iterations: 1,
            reprojection_threshold: 2.0,
            seed: 1234,
            early_stop_min_iterations: 0,
            confidence: None,
            early_stop_inlier_ratio: None,
            inlier_refits: 0,
        };

        // No prior: 1 random iteration is overwhelmingly likely to
        // sample an outlier, and at this fixed seed it does.
        assert!(
            ransac.estimate(&correspondences, &camera).is_none(),
            "control: without a prior, 1-iteration RANSAC should fail at this seed"
        );

        // Identity prior: pre-iteration scoring nails the 7 inliers
        // immediately, the iteration can't beat that, and DLT-on-inliers
        // recovers the identity pose.
        let prior = Pose::identity();
        let warm = ransac
            .estimate_with_pose_prior_and_weights(&correspondences, &camera, Some(&prior), None)
            .expect("warm-started PnP must recover a pose");
        let warm_inliers: usize = warm.inliers.iter().filter(|&&i| i < n_inliers).count();
        assert_eq!(
            warm_inliers, n_inliers,
            "warm-start PnP RANSAC should converge to all 7 geometric inliers"
        );
    }

    #[test]
    fn pnp_ransac_pose_prior_with_zero_inliers_falls_back_to_random_search() {
        use crate::pnp::DltPnP;
        // Same scene, but the prior is grossly wrong (1000 m off): all
        // pixels reproject far outside the threshold, so the prior
        // contributes zero inliers and the RANSAC iteration budget
        // takes over. The result should match the no-prior estimate.
        let camera = Camera::pinhole(1, 640, 480, 500.0, 500.0, 320.0, 240.0);
        let pose = Pose::identity();
        let points = [
            Point3::new(-1.0, -1.0, 4.0),
            Point3::new(1.0, -1.0, 4.5),
            Point3::new(-1.0, 1.0, 5.0),
            Point3::new(1.0, 1.0, 4.7),
            Point3::new(0.0, 0.0, 5.2),
            Point3::new(0.5, -0.25, 6.0),
        ];
        let correspondences: Vec<Correspondence2D3D> = points
            .iter()
            .map(|p| Correspondence2D3D {
                point2d: camera.project(&pose.transform_world_point(p)).unwrap(),
                point3d: *p,
                confidence: None,
            })
            .collect();

        let ransac = PnPRansac {
            pose_estimator: DltPnP::default(),
            pose_refiner: None::<crate::pnp::GaussNewtonPoseRefiner>,
            iterations: 32,
            reprojection_threshold: 1.0e-3,
            seed: 99,
            early_stop_min_iterations: 0,
            confidence: None,
            early_stop_inlier_ratio: None,
            inlier_refits: 0,
        };

        let bad_prior = Pose::from_world_to_camera(
            UnitQuaternion::identity(),
            Vector3::new(1000.0, 1000.0, 1000.0),
        );
        let no_prior = ransac.estimate(&correspondences, &camera).unwrap();
        let with_bad_prior = ransac
            .estimate_with_pose_prior_and_weights(&correspondences, &camera, Some(&bad_prior), None)
            .unwrap();
        assert_eq!(no_prior.inliers, with_bad_prior.inliers);
    }

    /// The fixed-budget search (scored in parallel under the `parallel`
    /// feature) returns exactly what the serial loop does; `confidence =
    /// Some(1.0)` forces the serial loop without ever stopping it early.
    #[test]
    fn fixed_budget_search_matches_serial_loop() {
        let camera = Camera::pinhole(1, 640, 480, 500.0, 500.0, 320.0, 240.0);
        let truth = Pose {
            world_to_camera: visloc_core::geometry::SE3::new(
                UnitQuaternion::from_euler_angles(0.05, -0.1, 0.02),
                Vector3::new(0.2, -0.1, 0.3),
            ),
        };
        let mut state = 99u64;
        let mut next = move || {
            state = state
                .wrapping_mul(6364136223846793005)
                .wrapping_add(1442695040888963407);
            (state >> 11) as f64 / (1u64 << 53) as f64
        };
        let correspondences: Vec<Correspondence2D3D> = (0..300)
            .filter_map(|i| {
                let point = Point3::new(next() * 4.0 - 2.0, next() * 3.0 - 1.5, 4.0 + next() * 6.0);
                let mut xy = visloc_core::geometry::reproject(&camera, &truth, &point)?;
                if i % 4 == 0 {
                    xy.x += 40.0 * (next() - 0.5);
                    xy.y += 40.0 * (next() - 0.5);
                }
                Some(Correspondence2D3D {
                    point2d: xy,
                    point3d: point,
                    confidence: None,
                })
            })
            .collect();
        let fixed = PnPRansac {
            pose_estimator: crate::pnp::P3PGrunert,
            pose_refiner: Some(crate::pnp::GaussNewtonPoseRefiner::default()),
            iterations: 64,
            reprojection_threshold: 2.0,
            seed: 3,
            early_stop_min_iterations: 0,
            early_stop_inlier_ratio: None,
            confidence: None,
            inlier_refits: 0,
        };
        let serial = PnPRansac {
            confidence: Some(1.0),
            ..fixed
        };
        let sample_size = fixed.pose_estimator.minimum_correspondences();
        let search_a = fixed.search_best_pose(&correspondences, &camera, sample_size, None, None);
        let search_b = serial.search_best_pose(&correspondences, &camera, sample_size, None, None);
        assert!(
            search_a.best_inliers.len() > 150,
            "most points are inliers: {} of {}",
            search_a.best_inliers.len(),
            correspondences.len()
        );
        assert_eq!(search_a.best_inliers, search_b.best_inliers);
        let (pa, pb) = (search_a.best_pose.unwrap(), search_b.best_pose.unwrap());
        assert_eq!(
            pa.world_to_camera.translation,
            pb.world_to_camera.translation
        );
        assert_eq!(pa.world_to_camera.rotation, pb.world_to_camera.rotation);
        let a = fixed.estimate(&correspondences, &camera).expect("pose");
        let b = serial.estimate(&correspondences, &camera).expect("pose");
        assert_eq!(a.inliers, b.inliers);
        assert_eq!(
            a.pose.world_to_camera.translation,
            b.pose.world_to_camera.translation
        );
        assert_eq!(
            a.pose.world_to_camera.rotation,
            b.pose.world_to_camera.rotation
        );
    }

    /// Camera-centre errors (over the scene distance) of P3P-RANSAC with
    /// `inlier_refits` rounds, on 1 px noise and 30% outliers: a wall
    /// (`depth_spread` 0) or points spread behind it.
    fn refit_errors(inlier_refits: usize, depth_spread: f64, scenes: usize) -> Vec<f64> {
        use crate::pnp::{P3PSolver, P3P};
        use nalgebra::{Point2, UnitQuaternion};
        let camera = Camera::pinhole(1, 640, 480, 500.0, 500.0, 320.0, 240.0);
        let mut state = 7_u64;
        let mut next = move || {
            state ^= state << 13;
            state ^= state >> 7;
            state ^= state << 17;
            (state >> 11) as f64 / (1u64 << 53) as f64
        };
        let mut errors = Vec::new();
        for _ in 0..scenes {
            let tilt = 1.3 * next();
            let azimuth = std::f64::consts::TAU * next();
            let normal = Vector3::new(
                tilt.sin() * azimuth.cos(),
                tilt.sin() * azimuth.sin(),
                tilt.cos(),
            );
            let distance = 2.0 + 6.0 * next();
            let true_pose = Pose::from_world_to_camera(
                UnitQuaternion::from_scaled_axis(Vector3::new(
                    next() - 0.5,
                    next() - 0.5,
                    next() - 0.5,
                )),
                Vector3::new(next(), next(), next()),
            );
            let world_from_camera = true_pose.world_to_camera.inverse();
            let mut correspondences = Vec::new();
            for i in 0..150 {
                let pixel = Point2::new(640.0 * next(), 480.0 * next());
                let ray = Vector3::new((pixel.x - 320.0) / 500.0, (pixel.y - 240.0) / 500.0, 1.0);
                let depth = normal.z * distance / normal.dot(&ray);
                if !(0.3..40.0).contains(&depth) {
                    continue;
                }
                let depth = depth + depth_spread * next();
                // Box-Muller, 1 px.
                let (u, v) = (next().max(1.0e-300), next());
                let radius = (-2.0 * u.ln()).sqrt();
                let angle = std::f64::consts::TAU * v;
                let observed = if i % 10 < 3 {
                    Point2::new(640.0 * next(), 480.0 * next())
                } else {
                    Point2::new(
                        pixel.x + radius * angle.cos(),
                        pixel.y + radius * angle.sin(),
                    )
                };
                correspondences.push(Correspondence2D3D {
                    point2d: observed,
                    point3d: world_from_camera.transform_point(&Point3::from(ray * depth)),
                    confidence: None,
                });
            }
            let ransac = PnPRansac {
                pose_estimator: P3P::new(P3PSolver::LambdaTwist),
                pose_refiner: Some(crate::pnp::GaussNewtonPoseRefiner::default()),
                iterations: 1000,
                reprojection_threshold: 3.0,
                seed: 7,
                early_stop_min_iterations: 0,
                early_stop_inlier_ratio: None,
                confidence: Some(0.999),
                inlier_refits,
            };
            let report = ransac.estimate(&correspondences, &camera).expect("a pose");
            let centre = report.pose.world_to_camera.inverse().translation;
            errors.push((centre - world_from_camera.translation).norm() / distance);
        }
        errors.sort_by(f64::total_cmp);
        errors
    }

    #[test]
    fn inlier_refits_tighten_the_pose_on_a_wall() {
        let (before, after) = (refit_errors(0, 0.0, 100), refit_errors(3, 0.0, 100));
        let mean = |e: &[f64]| e.iter().sum::<f64>() / e.len() as f64;
        assert!(
            mean(&after) < 0.9 * mean(&before),
            "mean centre error {} with refits vs {} without",
            mean(&after),
            mean(&before)
        );
    }

    /// `cargo test --release -p visloc-vision --lib inlier_refit_scan -- --ignored --nocapture`
    #[test]
    #[ignore = "measurement"]
    fn inlier_refit_scan() {
        for (scene, spread) in [("wall", 0.0), ("3d", 3.0)] {
            for refits in [0, 1, 3] {
                let e = refit_errors(refits, spread, 400);
                eprintln!(
                    "{scene} inlier_refits {refits}: centre error / distance median {:.2e} p90 {:.2e} max {:.2e}",
                    e[e.len() / 2],
                    e[e.len() * 9 / 10],
                    e[e.len() - 1]
                );
            }
        }
    }
}