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
//! Outer edge estimation from a center prior and expected marker scale.
//!
//! The outer edge can be confused with stronger inner-ring or code-band edges
//! under blur/high contrast. This estimator anchors the search to the expected
//! outer radius (derived from marker scale prior) and aggregates radial edge
//! responses over theta, similarly to the inner estimator.

use image::GrayImage;

use crate::marker::{AngularAggregator, GradPolarity};
use crate::pixelmap::PixelMapper;

use super::edge_sample::DistortionAwareSampler;
use super::radial_estimator::{RadialSampleGrid, RadialScanResult, scan_radial_derivatives};
use super::radial_profile;
use super::radial_profile::Polarity;

/// Outcome category for outer-edge estimation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum OuterStatus {
    /// Outer-radius estimate is valid and passed quality gates.
    Ok,
    /// Estimation failed (invalid inputs or insufficient data).
    Failed,
}

/// Typed failure reason for outer-edge estimation.
///
/// Replaces the old `reason: Option<String>` field so callers receive
/// structured data instead of a formatted string to be parsed back.
#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum OuterEstimateFailure {
    /// The radial search window is degenerate (window width ≤ 0).
    InvalidSearchWindow,
    /// Fewer than `min_theta_coverage` fraction of rays produced a valid sample.
    InsufficientThetaCoverage { observed: f32, min_required: f32 },
    /// No polarity produced a hypothesis that passed quality gates.
    NoPolarityCandidates,
}

/// Candidate outer-radius hypothesis from aggregated radial response.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct OuterHypothesis {
    /// Outer radius in pixels.
    pub r_outer_px: f32,
    /// Absolute aggregated peak magnitude.
    pub peak_strength: f32,
    /// Fraction of per-theta peaks close to `r_outer_px`.
    pub theta_consistency: f32,
}

/// Outer-radius estimation result with optional debug traces.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct OuterEstimate {
    /// Expected outer radius (pixels) from current scale prior.
    pub r_outer_expected_px: f32,
    /// Radial search window `[min, max]` in pixels.
    pub search_window_px: [f32; 2],
    /// Selected response polarity.
    pub polarity: Option<Polarity>,
    /// Candidate hypotheses sorted by quality (best first).
    pub hypotheses: Vec<OuterHypothesis>,
    /// Final estimator status.
    pub status: OuterStatus,
    /// Typed failure reason (present when `status` is `Failed`).
    pub failure: Option<OuterEstimateFailure>,
    /// Optional aggregated radial response profile (for debug/analysis).
    pub radial_response_agg: Option<Vec<f32>>,
    /// Optional sampled radii corresponding to `radial_response_agg`.
    pub r_samples: Option<Vec<f32>>,
}

/// Configuration for outer-radius estimation around a center prior.
///
/// The number of theta samples (rays) is **not** stored here; it is passed
/// explicitly to `estimate_outer_from_prior_with_mapper` so the caller can
/// synchronise it with the edge-sampling resolution without a silent override.
/// Set [`crate::EdgeSampleConfig::n_rays`] to control angular density for both stages.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(default)]
pub struct OuterEstimationConfig {
    /// Search half-width around the expected outer radius, in pixels.
    pub search_halfwidth_px: f32,
    /// Number of radial samples used to build the aggregated response.
    ///
    /// Same convention as [`crate::MarkerSpec::radial_samples`], calibrated
    /// independently for the outer estimation stage.
    pub radial_samples: usize,
    /// Aggregation method across theta.
    ///
    /// Same convention as [`crate::MarkerSpec::aggregator`], applied to the outer
    /// radial profile.
    pub aggregator: AngularAggregator,
    /// Expected polarity of `dI/dr` at the outer edge.
    pub grad_polarity: GradPolarity,
    /// Minimum fraction of theta samples required for an estimate.
    ///
    /// Same convention as [`crate::MarkerSpec::min_theta_coverage`], calibrated
    /// independently for the outer estimation stage.
    pub min_theta_coverage: f32,
    /// Minimum fraction of theta samples that must agree with the selected peak.
    ///
    /// Same convention as [`crate::MarkerSpec::min_theta_consistency`]; the outer
    /// estimator uses a stricter default (0.35) than the inner estimator (0.25)
    /// because the outer edge is anchored to a scale prior.
    pub min_theta_consistency: f32,
    /// If set, emit up to two hypotheses (best + runner-up) when runner-up is comparable.
    pub allow_two_hypotheses: bool,
    /// Runner-up must be at least this fraction of the best peak strength.
    pub second_peak_min_rel: f32,
    /// Per-theta local refinement half-width around the chosen radius.
    pub refine_halfwidth_px: f32,
}

impl Default for OuterEstimationConfig {
    fn default() -> Self {
        Self {
            search_halfwidth_px: 4.0,
            radial_samples: 64,
            aggregator: AngularAggregator::Median,
            grad_polarity: GradPolarity::DarkToLight,
            min_theta_coverage: 0.6,
            min_theta_consistency: 0.35,
            allow_two_hypotheses: true,
            second_peak_min_rel: 0.85,
            refine_halfwidth_px: 1.0,
        }
    }
}

fn failed_outer_estimate(
    r_outer_expected_px: f32,
    search_window_px: [f32; 2],
    failure: OuterEstimateFailure,
    r_samples: Option<Vec<f32>>,
) -> OuterEstimate {
    OuterEstimate {
        r_outer_expected_px,
        search_window_px,
        polarity: None,
        hypotheses: Vec::new(),
        status: OuterStatus::Failed,
        failure: Some(failure),
        radial_response_agg: None,
        r_samples,
    }
}

fn find_local_peaks(score: &[f32]) -> Vec<usize> {
    if score.len() < 3 {
        return Vec::new();
    }
    let mut out = Vec::new();
    for i in 1..(score.len() - 1) {
        if score[i].is_finite() && score[i] >= score[i - 1] && score[i] >= score[i + 1] {
            out.push(i);
        }
    }
    out
}

/// Build the search window and construct the `RadialSampleGrid` for outer estimation.
///
/// Returns `(window, polarity_candidates, track_pos, track_neg, grid)` on
/// success, or an early-return `OuterEstimate` on failure.
#[allow(clippy::type_complexity)]
fn setup_outer_search_window(
    r_outer_expected_px: f32,
    cfg: &OuterEstimationConfig,
) -> Result<([f32; 2], Vec<Polarity>, bool, bool, RadialSampleGrid), OuterEstimate> {
    let r_expected = r_outer_expected_px.max(1.0);
    let hw = cfg.search_halfwidth_px.max(0.5);
    let mut window = [r_expected - hw, r_expected + hw];
    window[0] = window[0].max(1.0);
    if window[1] <= window[0] + 1e-3 {
        return Err(failed_outer_estimate(
            r_expected,
            window,
            OuterEstimateFailure::InvalidSearchWindow,
            None,
        ));
    }

    let n_r = cfg.radial_samples.max(7);
    let polarity_candidates: Vec<Polarity> = match cfg.grad_polarity {
        GradPolarity::DarkToLight => vec![Polarity::Pos],
        GradPolarity::LightToDark => vec![Polarity::Neg],
        GradPolarity::Auto => vec![Polarity::Pos, Polarity::Neg],
    };
    let track_pos = polarity_candidates.contains(&Polarity::Pos);
    let track_neg = polarity_candidates.contains(&Polarity::Neg);
    let Some(grid) = RadialSampleGrid::from_window(window, n_r) else {
        return Err(failed_outer_estimate(
            r_expected,
            window,
            OuterEstimateFailure::InvalidSearchWindow,
            None,
        ));
    };

    Ok((window, polarity_candidates, track_pos, track_neg, grid))
}

/// Run the radial derivative scan and check theta coverage.
///
/// Returns the `RadialScanResult` on success, or an early-return
/// `OuterEstimate` on failure.
///
/// `fail_ctx` holds `(r_expected, window, store_response)` for the error path.
fn execute_outer_radial_scan(
    gray: &GrayImage,
    center_prior: [f32; 2],
    grid: RadialSampleGrid,
    polarity: (usize, bool, bool),
    mapper: Option<&dyn PixelMapper>,
    cfg: &OuterEstimationConfig,
    fail_ctx: (f32, [f32; 2], bool),
) -> Result<RadialScanResult, OuterEstimate> {
    let (n_t, track_pos, track_neg) = polarity;
    let (r_expected, window, store_response) = fail_ctx;
    let sampler = DistortionAwareSampler::new(gray, mapper);
    let cx = center_prior[0];
    let cy = center_prior[1];

    let scan = scan_radial_derivatives(
        grid,
        n_t,
        track_pos,
        track_neg,
        |ct, st, r_samples, i_vals| {
            for (ri, &r) in r_samples.iter().enumerate() {
                let x = cx + ct * r;
                let y = cy + st * r;
                let Some(sample) = sampler.sample_checked(x, y) else {
                    return false;
                };
                i_vals[ri] = sample;
            }
            true
        },
    );

    let coverage = scan.coverage();
    if scan.n_valid_theta == 0 || coverage < cfg.min_theta_coverage {
        return Err(failed_outer_estimate(
            r_expected,
            window,
            OuterEstimateFailure::InsufficientThetaCoverage {
                observed: coverage,
                min_required: cfg.min_theta_coverage,
            },
            store_response.then(|| scan.grid.r_samples.clone()),
        ));
    }

    Ok(scan)
}

/// Find peaks in the aggregated response for a single polarity and assemble
/// up to two `OuterHypothesis` entries that pass theta-consistency gating.
fn build_hypotheses_for_polarity(
    agg_resp: &[f32],
    pol: Polarity,
    scan: &RadialScanResult,
    n_r: usize,
    cfg: &OuterEstimationConfig,
) -> Vec<OuterHypothesis> {
    // Convert to a score where "larger is better" regardless of polarity.
    let score_vec: Vec<f32> = match pol {
        Polarity::Pos => agg_resp.to_vec(),
        Polarity::Neg => agg_resp.iter().map(|v| -v).collect(),
    };

    // Candidate peaks: local maxima in score_vec.
    let mut peaks = find_local_peaks(&score_vec);
    if peaks.is_empty() {
        // Fallback: global max if no local maxima found.
        if let Some((idx, _)) = score_vec
            .iter()
            .enumerate()
            .max_by(|a, b| a.1.partial_cmp(b.1).unwrap())
        {
            peaks.push(idx);
        }
    }

    // Sort peaks by score desc.
    peaks.sort_by(|&a, &b| score_vec[b].partial_cmp(&score_vec[a]).unwrap());

    let per_theta = scan.per_theta_peaks(pol);

    let mut hypotheses: Vec<OuterHypothesis> = Vec::new();
    let mut best_strength = None::<f32>;

    for &pi in &peaks {
        if pi == 0 || pi + 1 == n_r {
            continue;
        }
        let r_star = scan.grid.r_samples[pi];
        let peak_strength = agg_resp[pi].abs();
        if best_strength.is_none() {
            best_strength = Some(peak_strength);
        } else if !cfg.allow_two_hypotheses {
            break;
        } else if let Some(bs) = best_strength
            && peak_strength < (cfg.second_peak_min_rel.clamp(0.0, 1.0) * bs)
        {
            break;
        }

        let theta_consistency =
            radial_profile::theta_consistency(per_theta, r_star, scan.grid.r_step, 0.75);

        if theta_consistency < cfg.min_theta_consistency {
            continue;
        }

        hypotheses.push(OuterHypothesis {
            r_outer_px: r_star,
            peak_strength,
            theta_consistency,
        });

        if hypotheses.len() >= 2 {
            break;
        }
    }

    hypotheses
}

/// Estimate outer radius around a center prior using radial derivatives.
///
/// `theta_samples` sets the number of angular rays. Pass
/// `edge_sample.n_rays` to keep the outer-estimation and edge-sampling
/// resolutions in sync without a silent config override.
///
/// Uses an optional working<->image mapper for distortion-aware sampling.
pub fn estimate_outer_from_prior_with_mapper(
    gray: &GrayImage,
    center_prior: [f32; 2],
    r_outer_expected_px: f32,
    cfg: &OuterEstimationConfig,
    theta_samples: usize,
    mapper: Option<&dyn PixelMapper>,
    store_response: bool,
) -> OuterEstimate {
    let r_expected = r_outer_expected_px.max(1.0);
    let n_t = theta_samples.max(8);

    let (window, polarity_candidates, track_pos, track_neg, grid) =
        match setup_outer_search_window(r_outer_expected_px, cfg) {
            Ok(v) => v,
            Err(est) => return est,
        };

    let scan = match execute_outer_radial_scan(
        gray,
        center_prior,
        grid,
        (n_t, track_pos, track_neg),
        mapper,
        cfg,
        (r_expected, window, store_response),
    ) {
        Ok(s) => s,
        Err(est) => return est,
    };
    let n_r = scan.grid.r_samples.len();

    let agg_resp = scan.aggregate_response(&cfg.aggregator);

    let mut best: Option<(OuterEstimate, f32)> = None;

    for pol in polarity_candidates {
        let hypotheses = build_hypotheses_for_polarity(&agg_resp, pol, &scan, n_r, cfg);

        if hypotheses.is_empty() {
            continue;
        }

        let primary = &hypotheses[0];
        let score = primary.peak_strength * primary.theta_consistency;

        let est = OuterEstimate {
            r_outer_expected_px: r_expected,
            search_window_px: window,
            polarity: Some(pol),
            hypotheses,
            status: OuterStatus::Ok,
            failure: None,
            radial_response_agg: if store_response {
                Some(agg_resp.clone())
            } else {
                None
            },
            r_samples: if store_response {
                Some(scan.grid.r_samples.clone())
            } else {
                None
            },
        };

        match &best {
            Some((_, best_score)) if *best_score >= score => {}
            _ => {
                best = Some((est, score));
            }
        }
    }

    best.map(|(e, _)| e).unwrap_or_else(|| {
        failed_outer_estimate(
            r_expected,
            window,
            OuterEstimateFailure::NoPolarityCandidates,
            store_response.then(|| scan.grid.r_samples.clone()),
        )
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use image::{GrayImage, Luma};

    fn blur_gray(img: &GrayImage, sigma: f32) -> GrayImage {
        crate::test_utils::blur_gray(img, sigma)
    }

    #[test]
    fn outer_estimator_prefers_expected_outer_over_strong_inner_edge() {
        // Synthetic circular marker:
        // - Outer edge at r_outer (weak contrast)
        // - Strong edge at r_strong (< r_outer), simulating inner/code edges.
        let w = 128u32;
        let h = 128u32;
        let cx = 64.0f32;
        let cy = 64.0f32;
        let r_outer = 30.0f32;
        let r_strong = 22.0f32;

        let mut img = GrayImage::new(w, h);
        for y in 0..h {
            for x in 0..w {
                let dx = x as f32 - cx;
                let dy = y as f32 - cy;
                let r = (dx * dx + dy * dy).sqrt();
                let mut val = 0.85f32;

                // Outer dark band (weak)
                if (r - r_outer).abs() <= 1.5 {
                    val = 0.40;
                }

                // Strong inner dark band
                if (r - r_strong).abs() <= 1.5 {
                    val = 0.05;
                }

                img.put_pixel(x, y, Luma([(val * 255.0).round() as u8]));
            }
        }
        let img = blur_gray(&img, 1.0);

        let cfg = OuterEstimationConfig {
            search_halfwidth_px: 4.0,
            radial_samples: 64,
            aggregator: AngularAggregator::Median,
            grad_polarity: GradPolarity::DarkToLight,
            min_theta_coverage: 0.5,
            min_theta_consistency: 0.35,
            allow_two_hypotheses: true,
            second_peak_min_rel: 0.7,
            refine_halfwidth_px: 1.0,
        };

        // If we search around r_outer, we should land near r_outer, not the stronger inner edge.
        let est =
            estimate_outer_from_prior_with_mapper(&img, [cx, cy], r_outer, &cfg, 64, None, true);
        assert_eq!(
            est.status,
            OuterStatus::Ok,
            "outer estimate failed: {:?}",
            est.failure
        );
        assert_eq!(est.polarity, Some(Polarity::Pos));
        let r_found = est.hypotheses[0].r_outer_px;
        assert!(
            (r_found - r_outer).abs() < 2.0,
            "r_found {:.2} should be near expected {:.2}",
            r_found,
            r_outer
        );
    }
}