ringgrid 0.5.6

Pure-Rust detector for coded ring calibration targets
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
use crate::board_layout::BoardLayout;
use crate::homography::RansacHomographyConfig;
use crate::marker::{DecodeConfig, MarkerSpec};
use crate::pixelmap::SelfUndistortConfig;
use crate::ring::{EdgeSampleConfig, OuterEstimationConfig};

use crate::proposal::ProposalConfig;

fn proposal_spacing_ratio_for_board(board: &BoardLayout) -> f32 {
    let outer_diameter_mm = 2.0 * board.marker_outer_radius_mm();
    if !(outer_diameter_mm.is_finite() && outer_diameter_mm > 0.0) {
        return 1.0;
    }

    let spacing_mm = board.min_center_spacing_mm();
    if !(spacing_mm.is_finite() && spacing_mm > 0.0) {
        return 1.0;
    }

    spacing_mm / outer_diameter_mm
}

pub(crate) fn derive_proposal_config(
    board: &BoardLayout,
    marker_scale: MarkerScalePrior,
    base: &ProposalConfig,
) -> ProposalConfig {
    let [d_min, d_max] = marker_scale.diameter_range_px();
    let outer_radius_max_px = d_max * 0.5;
    let spacing_ratio = proposal_spacing_ratio_for_board(board);
    let spacing_min_px = spacing_ratio * d_min;
    let spacing_max_px = spacing_ratio * d_max;

    let nms_radius = (0.16 * d_min).max(4.0);

    let mut proposal = base.clone();
    proposal.r_min = (0.15 * spacing_min_px).max(2.0);
    proposal.r_max = (0.45 * spacing_max_px).min(1.35 * outer_radius_max_px);
    proposal.min_distance = nms_radius.max(0.85 * spacing_min_px);

    proposal
}

/// Seed-injection controls for proposal generation.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(default)]
pub struct SeedProposalParams {
    /// Radius (pixels) used to merge seed centers with detector proposals.
    pub merge_radius_px: f32,
    /// Score assigned to injected seed proposals.
    pub seed_score: f32,
    /// Maximum number of seeds consumed in one run.
    pub max_seeds: Option<usize>,
}

impl Default for SeedProposalParams {
    fn default() -> Self {
        Self {
            merge_radius_px: 3.0,
            seed_score: 1.0e12,
            max_seeds: Some(512),
        }
    }
}

/// Configuration for homography-guided completion: attempt local fits for
/// missing IDs at H-projected board locations.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(default)]
pub struct CompletionParams {
    /// Enable completion (runs only when a valid homography is available).
    pub enable: bool,
    /// Radial sampling extent (pixels) used for edge sampling around the prior center.
    pub roi_radius_px: f32,
    /// Maximum allowed reprojection error (pixels) between the fitted center and
    /// the H-projected board center.
    pub reproj_gate_px: f32,
    /// Minimum fit confidence in [0, 1].
    pub min_fit_confidence: f32,
    /// Minimum arc coverage (fraction of rays with both edges found).
    pub min_arc_coverage: f32,
    /// Optional cap on how many completion fits to attempt (in ID order).
    pub max_attempts: Option<usize>,
    /// Skip attempts whose projected center is too close to the image boundary.
    pub image_margin_px: f32,
    /// Require a perfect decode (dist=0 and margin ≥ the active profile's
    /// minimum cyclic Hamming distance) for a completion marker to be accepted.
    ///
    /// When homography prediction accuracy is low (e.g. significant lens distortion
    /// without a calibrated mapper), the H-projected seed can be several pixels off.
    /// Under those conditions, the geometry gates alone are insufficient; requiring a
    /// perfect decode provides an independent quality signal that does not depend on H.
    ///
    /// Default: `false` (backward-compatible). Set to `true` for Scheimpflug / high-
    /// distortion setups where no calibrated camera model is available.
    #[serde(default = "CompletionParams::default_require_perfect_decode")]
    pub require_perfect_decode: bool,
    /// Maximum allowed coefficient of variation (std_dev / mean) of per-ray outer
    /// radii. High scatter indicates inner/outer edge contamination — rays landing on
    /// the inner ring inflate the apparent outer radius for some angles. Values above
    /// this threshold cause the completion candidate to be rejected.
    ///
    /// The gate is skipped when fewer than 2 rays have valid outer radii or when the
    /// mean outer radius is below 1 px (degenerate fit).
    ///
    /// Default: `0.35` (35% coefficient of variation).
    #[serde(default = "CompletionParams::default_max_radii_std_ratio")]
    pub max_radii_std_ratio: f32,
}

impl CompletionParams {
    fn default_require_perfect_decode() -> bool {
        false
    }

    fn default_max_radii_std_ratio() -> f32 {
        0.35
    }
}

impl Default for CompletionParams {
    fn default() -> Self {
        Self {
            enable: true,
            roi_radius_px: 24.0,
            reproj_gate_px: 3.0,
            min_fit_confidence: 0.45,
            min_arc_coverage: 0.35,
            max_attempts: None,
            image_margin_px: 10.0,
            require_perfect_decode: false,
            max_radii_std_ratio: 0.35,
        }
    }
}

/// Projective-only unbiased center recovery from inner/outer conics.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(default)]
pub struct ProjectiveCenterParams {
    /// Use `marker_spec.r_inner_expected` as an optional eigenvalue prior.
    pub use_expected_ratio: bool,
    /// Weight of the eigenvalue-vs-ratio penalty term.
    pub ratio_penalty_weight: f64,
    /// Optional maximum allowed shift (pixels) from the pre-correction center.
    ///
    /// When set, large jumps are rejected and the original center is kept.
    pub max_center_shift_px: Option<f64>,
    /// Optional maximum accepted projective-selection residual.
    ///
    /// Higher values are less strict; `None` disables this gate.
    pub max_selected_residual: Option<f64>,
    /// Optional minimum accepted eigenvalue separation used by the selector.
    ///
    /// Low separation indicates unstable conic-pencil eigenpairs.
    pub min_eig_separation: Option<f64>,
}

impl Default for ProjectiveCenterParams {
    fn default() -> Self {
        Self {
            use_expected_ratio: true,
            ratio_penalty_weight: 1.0,
            max_center_shift_px: None,
            max_selected_residual: Some(0.25),
            min_eig_separation: Some(1e-6),
        }
    }
}

/// Configuration for robust inner ellipse fitting from outer-fit hints.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(default)]
pub struct InnerFitConfig {
    /// Minimum number of sampled points required to attempt a fit.
    pub min_points: usize,
    /// Minimum accepted inlier ratio when RANSAC is used.
    pub min_inlier_ratio: f32,
    /// Maximum accepted RMS Sampson residual (px) of the fitted inner ellipse.
    pub max_rms_residual: f64,
    /// Maximum allowed center shift from outer to inner fit center (px).
    pub max_center_shift_px: f64,
    /// Maximum allowed absolute error in recovered scale ratio vs radial hint.
    pub max_ratio_abs_error: f64,
    /// Local half-width (in radius-sample indices) around the radial hint.
    pub local_peak_halfwidth_idx: usize,
    /// RANSAC configuration for robust inner ellipse fitting.
    pub ransac: crate::conic::RansacConfig,
    /// Confidence multiplier applied when inner ellipse fit fails or is absent.
    ///
    /// Inner fit failure is a reliable signal of poor image quality (heavy blur,
    /// distortion, or edge contamination). Setting this below 1.0 discounts the
    /// decode confidence when the inner ring cannot be fitted, making true markers
    /// in clear regions easier to separate from false detections.
    ///
    /// Default: 0.7 (30 % confidence reduction on inner-fit miss).
    #[serde(default = "InnerFitConfig::default_miss_confidence_factor")]
    pub miss_confidence_factor: f32,
    /// Maximum allowed angular gap (radians) between consecutive inner edge
    /// points. Fits where the largest gap exceeds this are rejected.
    ///
    /// Default: π/2 (90 degrees).
    #[serde(default = "InnerFitConfig::default_max_angular_gap_rad")]
    pub max_angular_gap_rad: f64,
    /// When true, markers are hard-rejected (not just penalized) if the inner
    /// ellipse cannot be fitted. Requires two good ellipses per marker.
    ///
    /// Default: false (backward-compatible).
    #[serde(default = "InnerFitConfig::default_require_inner_fit")]
    pub require_inner_fit: bool,
}

impl InnerFitConfig {
    fn default_miss_confidence_factor() -> f32 {
        0.7
    }
    fn default_max_angular_gap_rad() -> f64 {
        std::f64::consts::FRAC_PI_2
    }
    fn default_require_inner_fit() -> bool {
        false
    }
}

impl Default for InnerFitConfig {
    fn default() -> Self {
        Self {
            min_points: 20,
            min_inlier_ratio: 0.5,
            max_rms_residual: 1.0,
            max_center_shift_px: 12.0,
            max_ratio_abs_error: 0.15,
            local_peak_halfwidth_idx: 3,
            ransac: crate::conic::RansacConfig {
                max_iters: 200,
                inlier_threshold: 1.5,
                min_inliers: 8,
                seed: 43,
            },
            miss_confidence_factor: 0.7,
            max_angular_gap_rad: Self::default_max_angular_gap_rad(),
            require_inner_fit: false,
        }
    }
}

/// Configuration for robust outer ellipse fitting from sampled edge points.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(default)]
pub struct OuterFitConfig {
    /// Minimum number of sampled points required to attempt direct LS fit.
    pub min_direct_fit_points: usize,
    /// Minimum sampled points required before attempting RANSAC.
    pub min_ransac_points: usize,
    /// RANSAC configuration for robust outer ellipse fitting.
    pub ransac: crate::conic::RansacConfig,
    /// Relative weight of size agreement in outer-hypothesis scoring.
    ///
    /// The score combines decode quality, fit support, size agreement, and
    /// residual quality. This weight controls the size-agreement term and is
    /// normalized with the other terms at runtime.
    ///
    /// Default: `0.15` (preserves legacy behavior).
    #[serde(default = "OuterFitConfig::default_size_score_weight")]
    pub size_score_weight: f32,
    /// Maximum allowed angular gap (radians) between consecutive outer edge
    /// points. Fits where the largest gap exceeds this are rejected.
    ///
    /// Default: π/2 (90 degrees).
    #[serde(default = "OuterFitConfig::default_max_angular_gap_rad")]
    pub max_angular_gap_rad: f64,
}

impl OuterFitConfig {
    fn default_size_score_weight() -> f32 {
        0.15
    }

    fn default_max_angular_gap_rad() -> f64 {
        std::f64::consts::FRAC_PI_2
    }
}

impl Default for OuterFitConfig {
    fn default() -> Self {
        Self {
            min_direct_fit_points: 6,
            min_ransac_points: 8,
            ransac: crate::conic::RansacConfig {
                max_iters: 200,
                inlier_threshold: 1.5,
                min_inliers: 6,
                seed: 42,
            },
            size_score_weight: Self::default_size_score_weight(),
            max_angular_gap_rad: Self::default_max_angular_gap_rad(),
        }
    }
}

/// Center-correction strategy used after local fits are accepted.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
pub enum CircleRefinementMethod {
    /// Disable center correction.
    None,
    /// Run projective-center recovery from inner/outer conics.
    #[default]
    ProjectiveCenter,
}

impl CircleRefinementMethod {
    /// Returns `true` when this method includes projective-center recovery.
    pub fn uses_projective_center(self) -> bool {
        matches!(self, Self::ProjectiveCenter)
    }
}

/// Scale prior for marker diameter in detector working pixels.
///
/// The detector uses this range to derive proposal radii, outer-edge search
/// windows, ellipse validation bounds, and completion ROI. When the marker
/// scale prior is set via [`DetectConfig::set_marker_scale_prior`] or a
/// constructor, all scale-dependent parameters are auto-derived.
///
/// A single known size can be expressed with
/// [`MarkerScalePrior::from_nominal_diameter_px`]. For scenes where markers
/// vary in apparent size, use [`MarkerScalePrior::new`] with a range.
#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
#[serde(default)]
pub struct MarkerScalePrior {
    /// Minimum expected marker outer diameter in pixels.
    pub diameter_min_px: f32,
    /// Maximum expected marker outer diameter in pixels.
    pub diameter_max_px: f32,
}

impl MarkerScalePrior {
    const MIN_DIAMETER_FLOOR_PX: f32 = 4.0;

    /// Construct a scale prior from a diameter range in pixels.
    pub fn new(diameter_min_px: f32, diameter_max_px: f32) -> Self {
        let mut out = Self {
            diameter_min_px,
            diameter_max_px,
        };
        out.normalize_in_place();
        out
    }

    /// Construct a fixed-size scale prior from one diameter hint.
    pub fn from_nominal_diameter_px(diameter_px: f32) -> Self {
        Self::new(diameter_px, diameter_px)
    }

    /// Return the normalized diameter range `[min, max]` in pixels.
    pub fn diameter_range_px(self) -> [f32; 2] {
        let n = self.normalized();
        [n.diameter_min_px, n.diameter_max_px]
    }

    /// Return nominal diameter (midpoint of `[min, max]`) in pixels.
    pub fn nominal_diameter_px(self) -> f32 {
        let [d_min, d_max] = self.diameter_range_px();
        0.5 * (d_min + d_max)
    }

    /// Return nominal outer radius in pixels.
    pub fn nominal_outer_radius_px(self) -> f32 {
        self.nominal_diameter_px() * 0.5
    }

    /// Return a normalized copy with finite, ordered, non-degenerate bounds.
    pub fn normalized(self) -> Self {
        let mut out = self;
        out.normalize_in_place();
        out
    }

    fn normalize_in_place(&mut self) {
        let defaults = MarkerScalePrior::default();
        let mut d_min = if self.diameter_min_px.is_finite() {
            self.diameter_min_px
        } else {
            defaults.diameter_min_px
        };
        let mut d_max = if self.diameter_max_px.is_finite() {
            self.diameter_max_px
        } else {
            defaults.diameter_max_px
        };
        if d_min > d_max {
            std::mem::swap(&mut d_min, &mut d_max);
        }
        d_min = d_min.max(Self::MIN_DIAMETER_FLOOR_PX);
        d_max = d_max.max(d_min);
        self.diameter_min_px = d_min;
        self.diameter_max_px = d_max;
    }
}

impl Default for MarkerScalePrior {
    fn default() -> Self {
        Self {
            diameter_min_px: 14.0,
            diameter_max_px: 66.0,
        }
    }
}

/// One scale band for multi-scale adaptive detection.
///
/// Each tier covers a diameter range with a ratio of at most 3:1. Combine
/// multiple tiers with [`ScaleTiers`] to cover scenes where markers span a
/// wide range of apparent sizes.
#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
pub struct ScaleTier {
    /// Marker outer diameter range for this tier (pixels).
    pub prior: MarkerScalePrior,
}

impl ScaleTier {
    /// Create a tier covering `[diameter_min_px, diameter_max_px]`.
    ///
    /// For best results keep the ratio `diameter_max_px / diameter_min_px ≤ 3`.
    pub fn new(diameter_min_px: f32, diameter_max_px: f32) -> Self {
        Self {
            prior: MarkerScalePrior::new(diameter_min_px, diameter_max_px),
        }
    }
}

/// An ordered set of scale tiers for multi-scale adaptive detection.
///
/// Each tier runs one full detection pass (fit + decode + projective centers).
/// Results from all tiers are merged with size-consistency-aware dedup, then
/// global filter, completion, and final H refit run once on the merged pool.
///
/// Use the preset constructors for common scenarios:
///
/// - [`ScaleTiers::four_tier_wide`] — 8–220 px, full range (27:1 ratio)
/// - [`ScaleTiers::two_tier_standard`] — 14–100 px, moderate variation (7:1)
/// - [`ScaleTiers::single`] — single-pass equivalent, no merge overhead
/// - [`ScaleTiers::from_detected_radii`] — built from a scale-probe result
///
/// See [`crate::Detector::detect_adaptive`] and
/// [`crate::Detector::detect_multiscale`].
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ScaleTiers(pub Vec<ScaleTier>);

impl ScaleTiers {
    /// Four overlapping tiers covering 8–220 px (27:1 diameter ratio).
    ///
    /// Tier boundaries: `[8,24]`, `[20,60]`, `[50,130]`, `[110,220]` px.
    /// Each tier has ratio ≤ 3:1. Overlapping boundaries ensure markers in
    /// the 20–24, 50–60, and 110–130 px range are detected by two tiers.
    ///
    /// Use when marker apparent size is unknown or spans a very wide range.
    pub fn four_tier_wide() -> Self {
        Self(vec![
            ScaleTier::new(8.0, 24.0),
            ScaleTier::new(20.0, 60.0),
            ScaleTier::new(50.0, 130.0),
            ScaleTier::new(110.0, 220.0),
        ])
    }

    /// Two overlapping tiers covering 14–100 px (~7:1 diameter ratio).
    ///
    /// Tier boundaries: `[14,42]`, `[36,100]` px. Faster than
    /// [`four_tier_wide`](Self::four_tier_wide) for moderate scale variation.
    pub fn two_tier_standard() -> Self {
        Self(vec![
            ScaleTier::new(14.0, 42.0),
            ScaleTier::new(36.0, 100.0),
        ])
    }

    /// Single tier wrapping the given prior — no multi-scale overhead.
    ///
    /// Equivalent to single-pass detection. Use when marker scale is
    /// approximately known.
    pub fn single(prior: MarkerScalePrior) -> Self {
        Self(vec![ScaleTier { prior }])
    }

    /// Construct tiers from dominant code-band radii estimated by the scale probe.
    ///
    /// Clusters `probe_radii` into groups where `max/min ≤ 3.0`, converts each
    /// cluster to an outer-ring diameter estimate (probe radii land in the code
    /// band at ~0.8× the outer ring radius), and pads each tier by ±30 %.
    ///
    /// Falls back to `single(MarkerScalePrior::default())` when `probe_radii`
    /// is empty or contains no finite positive values.
    pub fn from_detected_radii(probe_radii: &[f32]) -> Self {
        let mut sorted: Vec<f32> = probe_radii
            .iter()
            .copied()
            .filter(|r| r.is_finite() && *r > 0.0)
            .collect();

        if sorted.is_empty() {
            return Self::single(MarkerScalePrior::default());
        }

        sorted.sort_by(|a, b| a.partial_cmp(b).unwrap());

        // Code-band midpoint sits at ~0.8× the outer ring radius for the default
        // inner/outer ratio of 0.6: midpoint = 0.5*(0.6+1.0) = 0.8.
        const PROBE_TO_OUTER: f32 = 1.0 / 0.8; // ≈ 1.25

        let mut tiers = Vec::new();
        let mut cluster_min = sorted[0];
        let mut cluster_max = sorted[0];

        for &r in &sorted[1..] {
            if r / cluster_min <= 3.0 {
                cluster_max = r;
            } else {
                let r_outer_min = cluster_min * PROBE_TO_OUTER;
                let r_outer_max = cluster_max * PROBE_TO_OUTER;
                let d_min = (2.0 * r_outer_min * 0.70).max(4.0);
                let d_max = (2.0 * r_outer_max * 1.35).max(d_min);
                tiers.push(ScaleTier::new(d_min, d_max));
                cluster_min = r;
                cluster_max = r;
            }
        }
        // Final cluster.
        let r_outer_min = cluster_min * PROBE_TO_OUTER;
        let r_outer_max = cluster_max * PROBE_TO_OUTER;
        let d_min = (2.0 * r_outer_min * 0.70).max(4.0);
        let d_max = (2.0 * r_outer_max * 1.35).max(d_min);
        tiers.push(ScaleTier::new(d_min, d_max));

        Self(tiers)
    }

    /// Access the ordered tier list.
    pub fn tiers(&self) -> &[ScaleTier] {
        &self.0
    }
}

/// Structural ID verification and correction using hex neighborhood consensus.
///
/// Runs after fit-decode and deduplication, before the global RANSAC filter.
/// Uses the board's hex lattice geometry to detect wrong IDs (misidentified by
/// the codebook decoder) and recover missing ones. Each marker's correct ID is
/// implied by its decoded neighbors' positions: neighbors vote on the expected
/// board position of the query marker using a local affine transform (or scale
/// estimate when fewer than 3 neighbors are available).
///
/// Markers that cannot be verified or corrected have their IDs cleared
/// (`id = None`) or are removed entirely depending on `remove_unverified`.
/// This guarantees no wrong IDs reach the global filter or completion stages.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(default)]
pub struct IdCorrectionConfig {
    /// Enable structural ID verification and correction.
    pub enable: bool,
    /// Local-scale staged search multipliers (one per recovery pass, sorted ascending).
    ///
    /// The neighbor gate for pair `(i, j)` in each pass is:
    /// `dist_px(i,j) <= mul * 0.5 * (outer_radius_px_i + outer_radius_px_j)`.
    ///
    /// Multiple multipliers produce a staged sweep from tight to loose. A single-element
    /// Vec produces one pass (equivalent to the old `search_radius_outer_mul`).
    pub auto_search_radius_outer_muls: Vec<f64>,
    /// Local-scale neighborhood multiplier for consistency checks.
    pub consistency_outer_mul: f64,
    /// Minimum number of local neighbors required to run consistency checks.
    /// Default: 1 (any single neighbor provides enough evidence).
    pub consistency_min_neighbors: usize,
    /// Minimum number of one-hop board-neighbor support edges required for a
    /// non-soft-locked ID to remain assigned. Default: 1.
    pub consistency_min_support_edges: usize,
    /// Maximum allowed contradiction fraction in local consistency checks.
    pub consistency_max_contradiction_frac: f32,
    /// When enabled, exact decodes (`best_dist=0, margin>=2`) are soft-locked:
    /// they are not overridden during normal recovery and only cleared on
    /// strict structural contradiction.
    pub soft_lock_exact_decode: bool,
    /// Minimum number of independent neighbor votes required to accept a
    /// candidate ID for a marker that already has an id. Default: 2.
    pub min_votes: usize,
    /// Minimum votes to assign an ID to a marker that currently has `id = None`.
    ///
    /// A single high-confidence trusted neighbor is sufficient evidence when
    /// there is no existing wrong ID to protect. Default: 1.
    pub min_votes_recover: usize,
    /// Minimum fraction of total weighted votes the winning candidate must
    /// receive. Default: 0.55 (slight majority).
    pub min_vote_weight_frac: f32,
    /// H-reprojection gate (pixels) used by rough-homography fallback
    /// assignments. Intentionally loose to tolerate significant distortion.
    pub h_reproj_gate_px: f64,
    /// Enable rough-homography fallback for unresolved markers.
    pub homography_fallback_enable: bool,
    /// Minimum trusted markers required before attempting homography fallback.
    pub homography_min_trusted: usize,
    /// Minimum inliers required for fallback homography RANSAC acceptance.
    pub homography_min_inliers: usize,
    /// Maximum number of iterative correction passes. Default: 5.
    pub max_iters: usize,
    /// When `true`, remove markers that cannot be verified or corrected.
    /// When `false` (default), clear their ID (set to `None`) and keep the
    /// detection so its geometry is available for debugging.
    pub remove_unverified: bool,
    /// Minimum decode confidence for bootstrapping trusted seeds when no
    /// homography is available. Default: 0.7.
    pub seed_min_decode_confidence: f32,
}

impl IdCorrectionConfig {
    /// Returns the minimum vote threshold appropriate for a marker at `i`:
    /// `min_votes_recover` if the marker has no current ID, `min_votes` otherwise.
    pub(crate) fn effective_min_votes(&self, has_id: bool) -> usize {
        if has_id {
            self.min_votes
        } else {
            self.min_votes_recover
        }
    }
}

impl Default for IdCorrectionConfig {
    fn default() -> Self {
        Self {
            enable: true,
            auto_search_radius_outer_muls: vec![2.4, 2.9, 3.5, 4.2, 5.0],
            consistency_outer_mul: 3.2,
            consistency_min_neighbors: 1,
            consistency_min_support_edges: 1,
            consistency_max_contradiction_frac: 0.5,
            soft_lock_exact_decode: true,
            min_votes: 2,
            min_votes_recover: 1,
            min_vote_weight_frac: 0.55,
            h_reproj_gate_px: 30.0,
            homography_fallback_enable: true,
            homography_min_trusted: 24,
            homography_min_inliers: 12,
            max_iters: 5,
            remove_unverified: false,
            seed_min_decode_confidence: 0.7,
        }
    }
}

/// Configuration for automatic recovery of markers where the inner edge was
/// incorrectly fitted as the outer ellipse.
///
/// After all markers are finalized, each marker's outer radius is compared to
/// the median outer radius of its k nearest neighbors. A ratio well below 1.0
/// (see `ratio_threshold`) indicates the outer fit locked onto the inner ring
/// edge. When enabled, the detector re-attempts the outer fit for flagged
/// markers using the neighbor median radius as the corrected expected radius.
///
/// The recovery re-fit uses a tight 4 px search window (to exclude the inner
/// ring) combined with relaxed quality gates (`min_theta_consistency`,
/// `min_ring_depth`, `refine_halfwidth_px`) suited to the blurry/soft edges
/// that typically cause inner-as-outer confusion. A post-fit size gate
/// (`size_gate_tolerance`) prevents the relaxed estimator from re-locking onto
/// the inner ring even under the relaxed thresholds.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(default)]
pub struct InnerAsOuterRecoveryConfig {
    /// Enable inner-as-outer recovery (default: `true`).
    pub enable: bool,
    /// Neighbor-radius ratio below which a marker is considered anomalous and
    /// a re-fit is attempted.
    ///
    /// Default: `0.75`. Markers with `own_radius / neighbor_median < 0.75` are
    /// flagged. A value of ~0.64 is expected for an inner-as-outer confusion
    /// (inner radius ≈ 0.49 × outer radius → ratio = 0.49 / 0.77 ≈ 0.64 when
    /// inner accounts for the inner/outer ratio of the ring marker geometry).
    pub ratio_threshold: f32,
    /// Number of nearest neighbors used to compute the median outer radius.
    ///
    /// Default: `6` (matching the hex-lattice neighbor count). Self is always
    /// excluded by passing k+1 to the neighbor function.
    pub k_neighbors: usize,
    /// Minimum fraction of angular samples (rays) whose radial peak must agree
    /// with the selected hypothesis radius during the recovery re-estimation.
    ///
    /// Lower than the production default (0.35) because blurry outer edges
    /// scatter per-θ peaks more widely. Default: `0.18`.
    pub min_theta_consistency: f32,
    /// Minimum fraction of angular rays with valid (in-bounds) samples during
    /// the recovery re-estimation. Default: `0.40`.
    pub min_theta_coverage: f32,
    /// Minimum signed intensity depth at a candidate outer edge point during
    /// recovery edge collection. Lower than production (0.05) to tolerate
    /// blur-smeared intensity gradients. Default: `0.02`.
    pub min_ring_depth: f32,
    /// Per-ray radius refinement half-width (pixels) during recovery. Wider
    /// than production (1.0 px) to catch the flat-topped derivative peaks that
    /// occur under blur. Default: `2.5`.
    pub refine_halfwidth_px: f32,
    /// Maximum allowed fractional deviation of the recovered outer radius from
    /// the neighbor-median corrected radius: `|r_recovered - r_corrected| /
    /// r_corrected ≤ size_gate_tolerance`. Prevents the relaxed estimator from
    /// accepting a re-locked inner-ring fit. Default: `0.25`.
    pub size_gate_tolerance: f32,
}

impl Default for InnerAsOuterRecoveryConfig {
    fn default() -> Self {
        Self {
            enable: true,
            ratio_threshold: 0.75,
            k_neighbors: 6,
            min_theta_consistency: 0.18,
            min_theta_coverage: 0.40,
            min_ring_depth: 0.02,
            refine_halfwidth_px: 2.5,
            size_gate_tolerance: 0.25,
        }
    }
}

/// Controls optional image downscaling before proposal generation.
///
/// When markers are large in the image, the proposal stage can be run on a
/// downscaled copy for significant speedup. All downstream stages (outer fit,
/// decode, inner fit) still operate at full resolution.
///
/// Proposal coordinates are automatically scaled back to original image space.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ProposalDownscale {
    /// Auto-select downscale factor from `marker_scale.diameter_min_px`.
    ///
    /// `factor = clamp(floor(d_min / 14.0), 1, 4)`. Ensures markers remain
    /// at least ~7 px diameter after downscaling, which is sufficient for
    /// RSD center detection.
    Auto,
    /// No downscaling (full resolution proposals).
    #[default]
    Off,
    /// Explicit integer downscale factor (clamped to `[1, 4]`).
    Factor(u32),
}

impl ProposalDownscale {
    /// Resolve the concrete integer factor given the current marker scale prior.
    pub fn resolve(&self, marker_scale: MarkerScalePrior) -> u32 {
        match self {
            Self::Auto => {
                let d_min = marker_scale.diameter_range_px()[0];
                (d_min / 14.0).floor().clamp(1.0, 4.0) as u32
            }
            Self::Off => 1,
            Self::Factor(f) => (*f).clamp(1, 4),
        }
    }
}

/// Top-level detection configuration.
///
/// Contains all parameters that control the detection pipeline. Use one of the
/// recommended constructors rather than constructing directly:
///
/// - [`DetectConfig::from_target`] — default scale prior
/// - [`DetectConfig::from_target_and_scale_prior`] — explicit scale range
/// - [`DetectConfig::from_target_and_marker_diameter`] — fixed diameter hint
///
/// These constructors auto-derive scale-dependent parameters (proposal radii,
/// edge search windows, validation bounds) from the board geometry and marker
/// scale prior. Individual fields can be tuned after construction.
#[derive(Debug, Clone)]
pub struct DetectConfig {
    /// Marker diameter prior (range) in working-frame pixels.
    pub marker_scale: MarkerScalePrior,
    /// Outer edge estimation configuration (anchored on `marker_scale`).
    pub outer_estimation: OuterEstimationConfig,
    /// Proposal generation configuration.
    pub proposal: ProposalConfig,
    /// Seed-injection controls for multi-pass proposal generation.
    pub seed_proposals: SeedProposalParams,
    /// Radial edge sampling configuration.
    pub edge_sample: EdgeSampleConfig,
    /// Marker decode configuration.
    pub decode: DecodeConfig,
    /// Marker geometry specification and estimator controls.
    pub marker_spec: MarkerSpec,
    /// Robust inner ellipse fitting controls shared across pipeline stages.
    pub inner_fit: InnerFitConfig,
    /// Robust outer ellipse fitting controls shared across pipeline stages.
    pub outer_fit: OuterFitConfig,
    /// Post-fit circle refinement method selector.
    pub circle_refinement: CircleRefinementMethod,
    /// Projective-center recovery controls.
    pub projective_center: ProjectiveCenterParams,
    /// Homography-guided completion controls.
    pub completion: CompletionParams,
    /// Minimum semi-axis for a valid outer ellipse.
    /// Derived from `marker_scale` by the config constructors; do not set directly.
    pub(crate) min_semi_axis: f64,
    /// Maximum semi-axis for a valid outer ellipse.
    /// Derived from `marker_scale` by the config constructors; do not set directly.
    pub(crate) max_semi_axis: f64,
    /// Maximum aspect ratio (a/b) for a valid ellipse.
    pub max_aspect_ratio: f64,
    /// NMS dedup radius for final markers (pixels).
    pub dedup_radius: f64,
    /// Enable global homography filtering (requires board spec).
    pub use_global_filter: bool,
    /// Hex-topology consistency filter threshold (pixels).
    ///
    /// After global filter and ID correction, each decoded marker's position is
    /// compared against the midpoint predicted by its hex neighbors. Markers
    /// that deviate by more than this threshold are removed.
    ///
    /// Set to `None` to disable the topology filter. Default: `None`.
    pub topology_filter_threshold_px: Option<f32>,
    /// RANSAC homography configuration.
    pub ransac_homography: RansacHomographyConfig,
    /// Board layout: marker positions and geometry.
    pub board: BoardLayout,
    /// Self-undistort estimation controls.
    pub self_undistort: SelfUndistortConfig,
    /// Structural ID verification and correction using hex neighborhood consensus.
    pub id_correction: IdCorrectionConfig,
    /// Automatic recovery for markers where the inner edge was incorrectly
    /// fitted as the outer ellipse.
    pub inner_as_outer_recovery: InnerAsOuterRecoveryConfig,
    /// Soft confidence penalty alpha for H-reprojection error.
    ///
    /// After the final homography is estimated, each marker's confidence is
    /// multiplied by `1 / (1 + alpha * h_reproj_err_px)`. Markers with small
    /// reprojection errors are unaffected; geometrically inconsistent markers
    /// (e.g. 5 px error) are penalised by roughly `1 / (1 + 0.2 * 5) = 0.5`.
    ///
    /// Set to `0.0` to disable the penalty. Default: `0.2`.
    pub h_reproj_confidence_alpha: f32,
    /// Optional image downscaling before proposal generation.
    ///
    /// When markers are large, running proposals on a smaller image is much
    /// faster while proposal coordinates are approximate anyway (downstream
    /// stages refine at full resolution). Default: `Off`.
    pub proposal_downscale: ProposalDownscale,
}

impl DetectConfig {
    /// Build a configuration with scale-dependent parameters derived from a
    /// marker diameter range and a runtime target layout.
    ///
    /// This is the recommended constructor for library users. After calling it,
    /// individual fields can be overridden as needed.
    pub fn from_target_and_scale_prior(board: BoardLayout, marker_scale: MarkerScalePrior) -> Self {
        let mut cfg = Self {
            marker_scale: marker_scale.normalized(),
            ..Default::default()
        };
        cfg.board = board;
        apply_target_geometry_priors(&mut cfg);
        apply_marker_scale_prior(&mut cfg);
        cfg
    }

    /// Build a configuration from target layout and default marker scale prior.
    pub fn from_target(board: BoardLayout) -> Self {
        Self::from_target_and_scale_prior(board, MarkerScalePrior::default())
    }

    /// Build a configuration from target layout and a fixed marker diameter hint.
    pub fn from_target_and_marker_diameter(board: BoardLayout, diameter_px: f32) -> Self {
        Self::from_target_and_scale_prior(
            board,
            MarkerScalePrior::from_nominal_diameter_px(diameter_px),
        )
    }

    /// Update marker scale prior and re-derive all scale-coupled parameters.
    pub fn set_marker_scale_prior(&mut self, marker_scale: MarkerScalePrior) {
        self.marker_scale = marker_scale.normalized();
        apply_marker_scale_prior(self);
    }

    /// Update marker scale prior from a fixed marker diameter hint.
    pub fn set_marker_diameter_hint_px(&mut self, diameter_px: f32) {
        self.set_marker_scale_prior(MarkerScalePrior::from_nominal_diameter_px(diameter_px));
    }

    #[cfg(test)]
    fn proposal_spacing_ratio(&self) -> f32 {
        proposal_spacing_ratio_for_board(&self.board)
    }

    #[cfg(test)]
    fn proposal_spacing_min_px(&self) -> f32 {
        let [d_min, _] = self.marker_scale.diameter_range_px();
        self.proposal_spacing_ratio() * d_min
    }

    #[cfg(test)]
    fn proposal_spacing_max_px(&self) -> f32 {
        let [_, d_max] = self.marker_scale.diameter_range_px();
        self.proposal_spacing_ratio() * d_max
    }
}

impl Default for DetectConfig {
    fn default() -> Self {
        let mut cfg = Self {
            marker_scale: MarkerScalePrior::default(),
            outer_estimation: OuterEstimationConfig::default(),
            proposal: ProposalConfig::default(),
            seed_proposals: SeedProposalParams::default(),
            edge_sample: EdgeSampleConfig::default(),
            decode: DecodeConfig::default(),
            marker_spec: MarkerSpec::default(),
            inner_fit: InnerFitConfig::default(),
            outer_fit: OuterFitConfig::default(),
            circle_refinement: CircleRefinementMethod::default(),
            projective_center: ProjectiveCenterParams::default(),
            completion: CompletionParams::default(),
            min_semi_axis: 3.0,
            max_semi_axis: 15.0,
            max_aspect_ratio: 3.0,
            dedup_radius: 6.0,
            use_global_filter: true,
            topology_filter_threshold_px: None,
            ransac_homography: RansacHomographyConfig::default(),
            board: BoardLayout::default(),
            self_undistort: SelfUndistortConfig::default(),
            id_correction: IdCorrectionConfig::default(),
            inner_as_outer_recovery: InnerAsOuterRecoveryConfig::default(),
            h_reproj_confidence_alpha: 0.2,
            proposal_downscale: ProposalDownscale::default(),
        };
        apply_target_geometry_priors(&mut cfg);
        apply_marker_scale_prior(&mut cfg);
        cfg
    }
}

fn apply_marker_scale_prior(config: &mut DetectConfig) {
    config.marker_scale = config.marker_scale.normalized();
    let [d_min, d_max] = config.marker_scale.diameter_range_px();
    let d_nom = config.marker_scale.nominal_diameter_px();
    let outer_radius_min_px = d_min * 0.5;
    let outer_radius_max_px = d_max * 0.5;
    let r_nom = d_nom * 0.5;
    config.proposal = derive_proposal_config(&config.board, config.marker_scale, &config.proposal);

    // Edge sampling range
    config.edge_sample.r_max = outer_radius_max_px * 2.0;
    config.edge_sample.r_min = 1.5;
    let desired_halfwidth = ((outer_radius_max_px - outer_radius_min_px) * 0.5).max(2.0);
    let base_halfwidth = OuterEstimationConfig::default().search_halfwidth_px;
    config.outer_estimation.search_halfwidth_px = desired_halfwidth.max(base_halfwidth);

    // Ellipse validation bounds
    config.min_semi_axis = (outer_radius_min_px as f64 * 0.3).max(2.0);
    config.max_semi_axis = (outer_radius_max_px as f64 * 2.5).max(config.min_semi_axis);

    // Completion ROI
    config.completion.roi_radius_px = ((d_nom as f64 * 0.75).clamp(24.0, 80.0)) as f32;

    // Projective center max shift
    config.projective_center.max_center_shift_px = Some((2.0 * r_nom) as f64);
}

fn apply_target_geometry_priors(config: &mut DetectConfig) {
    let outer = config.board.marker_outer_radius_mm();
    let inner = config.board.marker_inner_radius_mm();
    let ring_width = config.board.marker_ring_width_mm();
    if !(outer.is_finite() && inner.is_finite() && ring_width.is_finite())
        || outer <= 0.0
        || inner <= 0.0
        || ring_width <= 0.0
        || inner >= outer
    {
        return;
    }

    let edge_pad = 0.5 * ring_width;
    let inner_edge = (inner - edge_pad).max(outer * 0.05);
    let outer_edge = outer + edge_pad;
    if inner_edge > 0.0 && inner_edge < outer_edge {
        let r_inner_expected = (inner_edge / outer_edge).clamp(0.1, 0.95);
        config.marker_spec.r_inner_expected = r_inner_expected;
        config.decode.code_band_ratio = (0.5 * (1.0 + r_inner_expected)).clamp(0.2, 0.98);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn inner_fit_config_defaults_are_stable() {
        let core = InnerFitConfig::default();
        assert_eq!(core.min_points, 20);
        assert!((core.min_inlier_ratio - 0.5).abs() < 1e-6);
        assert!((core.max_rms_residual - 1.0).abs() < 1e-9);
        assert!((core.max_center_shift_px - 12.0).abs() < 1e-9);
        assert!((core.max_ratio_abs_error - 0.15).abs() < 1e-9);
        assert_eq!(core.local_peak_halfwidth_idx, 3);
        assert_eq!(core.ransac.max_iters, 200);
        assert!((core.ransac.inlier_threshold - 1.5).abs() < 1e-9);
        assert_eq!(core.ransac.min_inliers, 8);
        assert_eq!(core.ransac.seed, 43);
        assert!((core.miss_confidence_factor - 0.7).abs() < 1e-6);
        assert!(
            (core.max_angular_gap_rad - std::f64::consts::FRAC_PI_2).abs() < 1e-9,
            "inner max_angular_gap_rad"
        );
        assert!(!core.require_inner_fit);
    }

    #[test]
    fn outer_fit_config_defaults_are_stable() {
        let core = OuterFitConfig::default();
        assert_eq!(core.min_direct_fit_points, 6);
        assert_eq!(core.min_ransac_points, 8);
        assert_eq!(core.ransac.max_iters, 200);
        assert!((core.ransac.inlier_threshold - 1.5).abs() < 1e-9);
        assert_eq!(core.ransac.min_inliers, 6);
        assert_eq!(core.ransac.seed, 42);
        assert!((core.size_score_weight - 0.15).abs() < 1e-6);
        assert!(
            (core.max_angular_gap_rad - std::f64::consts::FRAC_PI_2).abs() < 1e-9,
            "outer max_angular_gap_rad"
        );
    }

    #[test]
    fn outer_fit_config_deserialize_missing_size_weight_uses_default() {
        let json = r#"{
            "min_direct_fit_points": 6,
            "min_ransac_points": 8,
            "ransac": {
                "max_iters": 200,
                "inlier_threshold": 1.5,
                "min_inliers": 6,
                "seed": 42
            }
        }"#;
        let cfg: OuterFitConfig = serde_json::from_str(json).expect("deserialize outer fit config");
        assert!((cfg.size_score_weight - 0.15).abs() < 1e-6);
    }

    #[test]
    fn detect_config_includes_fit_configs() {
        let cfg = DetectConfig::default();
        assert_eq!(cfg.inner_fit.min_points, 20);
        assert_eq!(cfg.inner_fit.ransac.min_inliers, 8);
        assert_eq!(cfg.outer_fit.min_direct_fit_points, 6);
        assert_eq!(cfg.outer_fit.ransac.min_inliers, 6);
    }

    #[test]
    fn marker_scale_prior_derives_spacing_aware_proposal_geometry() {
        let cfg = DetectConfig::from_target(BoardLayout::default());
        let spacing_ratio =
            cfg.board.min_center_spacing_mm() / (2.0 * cfg.board.marker_outer_radius_mm());
        let [d_min, d_max] = cfg.marker_scale.diameter_range_px();
        let spacing_min_px = spacing_ratio * d_min;
        let spacing_max_px = spacing_ratio * d_max;
        let outer_radius_max_px = 0.5 * d_max;

        assert!((cfg.proposal_spacing_ratio() - spacing_ratio).abs() < 1.0e-6);
        assert!((cfg.proposal_spacing_min_px() - spacing_min_px).abs() < 1.0e-6);
        assert!((cfg.proposal_spacing_max_px() - spacing_max_px).abs() < 1.0e-6);
        assert!((cfg.proposal.r_min - (0.15 * spacing_min_px).max(2.0)).abs() < 1.0e-6);
        assert!(
            (cfg.proposal.r_max - (0.45 * spacing_max_px).min(1.35 * outer_radius_max_px)).abs()
                < 1.0e-6
        );
        let expected_nms = (0.16 * d_min).max(4.0);
        let expected_min_dist = expected_nms.max(0.85 * spacing_min_px);
        assert!((cfg.proposal.min_distance - expected_min_dist).abs() < 1.0e-6);
    }

    #[test]
    fn fixed_marker_hint_keeps_spacing_aware_seed_distance() {
        let cfg = DetectConfig::from_target_and_marker_diameter(BoardLayout::default(), 32.0);
        assert!((cfg.proposal.r_min - 6.928203).abs() < 1.0e-5);
        assert!((cfg.proposal.r_max - 20.784609).abs() < 1.0e-5);
        assert!((cfg.proposal.min_distance - 39.259_815).abs() < 1.0e-5);
    }

    #[test]
    fn id_correction_config_defaults_are_stable() {
        let cfg = IdCorrectionConfig::default();
        assert!(cfg.enable);
        assert_eq!(
            cfg.auto_search_radius_outer_muls,
            vec![2.4, 2.9, 3.5, 4.2, 5.0]
        );
        assert!((cfg.consistency_outer_mul - 3.2).abs() < 1e-9);
        assert_eq!(cfg.consistency_min_neighbors, 1);
        assert_eq!(cfg.consistency_min_support_edges, 1);
        assert!((cfg.consistency_max_contradiction_frac - 0.5).abs() < 1e-6);
        assert!(cfg.soft_lock_exact_decode);
        assert_eq!(cfg.min_votes, 2);
        assert_eq!(cfg.min_votes_recover, 1);
        assert!((cfg.min_vote_weight_frac - 0.55).abs() < 1e-6);
        assert!((cfg.h_reproj_gate_px - 30.0).abs() < 1e-9);
        assert!(cfg.homography_fallback_enable);
        assert_eq!(cfg.homography_min_trusted, 24);
        assert_eq!(cfg.homography_min_inliers, 12);
        assert_eq!(cfg.max_iters, 5);
        assert!(!cfg.remove_unverified);
        assert!((cfg.seed_min_decode_confidence - 0.7).abs() < 1e-6);
    }

    #[test]
    fn id_correction_config_unknown_fields_are_silently_ignored() {
        // Old config JSON with fields that no longer exist — serde should ignore them
        // and fill in current defaults for the missing new fields.
        let json = r#"{
            "enable": true,
            "neighbor_search_radius_px": null,
            "homography_ransac_max_iters": 1200,
            "homography_use_recovered_seeds": false,
            "homography_candidate_top_k": 19,
            "min_votes": 2,
            "min_votes_recover": 1,
            "min_vote_weight_frac": 0.55,
            "h_reproj_gate_px": 30.0,
            "max_iters": 5,
            "remove_unverified": false,
            "seed_min_decode_confidence": 0.7
        }"#;
        let cfg: IdCorrectionConfig =
            serde_json::from_str(json).expect("deserialize old id correction config");
        assert_eq!(
            cfg.auto_search_radius_outer_muls,
            vec![2.4, 2.9, 3.5, 4.2, 5.0]
        );
        assert!((cfg.consistency_outer_mul - 3.2).abs() < 1e-9);
        assert_eq!(cfg.consistency_min_neighbors, 1);
        assert_eq!(cfg.consistency_min_support_edges, 1);
        assert!(cfg.homography_fallback_enable);
        assert_eq!(cfg.homography_min_trusted, 24);
        assert_eq!(cfg.homography_min_inliers, 12);
    }
}