projective_grid/square/validate/mod.rs
1//! Post-growth validation for a labelled square grid.
2//!
3//! Two independent checks run over the labelled set:
4//!
5//! 1. **Line collinearity.** For every row (`j = const`) and column
6//! (`i = const`) with `≥ line_min_members` labelled members, fit
7//! a least-squares line in pixel space and flag any member whose
8//! perpendicular residual exceeds `line_tol_rel × scale`.
9//!
10//! 2. **Local-H residual.** For every labelled corner with ≥ 4
11//! non-collinear labelled neighbors in `(i, j)`-space, fit a 4-point
12//! local homography from the 4 grid-closest neighbors, predict the
13//! corner's pixel position, and measure the residual. Corners whose
14//! residual exceeds `local_h_tol_rel × scale` are flagged.
15//!
16//! `scale` is either the caller-supplied global `cell_size` (default
17//! mode) or — when [`ValidationParams::use_step_aware`] is set — a
18//! **per-corner local step** computed from labelled grid neighbours
19//! via central or one-sided finite differences. Per-corner thresholds
20//! are anisotropic: cells in perspective-foreshortened regions get a
21//! tighter pixel tolerance proportional to their (smaller) local step;
22//! cells in radially-distorted regions get a looser one. Corners
23//! without enough labelled neighbours fall back to the global
24//! `cell_size`.
25//!
26//! Flags are combined via the attribution rules below into a
27//! blacklist of **indices into the input slice**:
28//!
29//! * A corner flagged in `≥ 2` lines is the outlier.
30//! * A corner with a *large* local-H residual (`> 2 × local_h_tol`) AND
31//! at least one line flag is the outlier.
32//! * A corner with a local-H flag but NO line flag, where at least one
33//! of its 4 base neighbors has `≥ 1` line flags, blames the worst-
34//! line-flagged base instead (the base is the outlier).
35//! * When [`ValidationParams::step_deviation_thresh_rel`] is set, a
36//! corner whose local step deviates from the labelled-set median by
37//! more than the threshold AND has ≥ 1 line flag is also an outlier.
38//! * Otherwise (isolated local-H flag with no supporting evidence),
39//! defer — no blacklist entry in this iteration.
40//!
41//! The caller is expected to re-run the seed/grow/validate loop after
42//! updating its blacklist.
43//!
44//! # Pattern-agnostic
45//!
46//! This module has no dependency on chessboard-specific vocabulary
47//! (parity, axis clusters, label enums). Any caller that can produce
48//! a `(corner_index, pixel_position, grid_coord)` slice can use it.
49//! Consumers that carry per-stage metadata should pre-filter to the
50//! "labelled" subset before calling.
51
52mod lines;
53mod local_h;
54mod step;
55
56use nalgebra::Point2;
57use std::collections::{HashMap, HashSet};
58
59/// Tolerances for the validation pass.
60///
61/// All spatial tolerances are expressed as ratios of either the
62/// caller-supplied global `cell_size` or — when [`use_step_aware`] is
63/// set — the per-corner local step derived from labelled grid
64/// neighbours.
65///
66/// [`use_step_aware`]: ValidationParams::use_step_aware
67#[non_exhaustive]
68#[derive(Clone, Copy, Debug)]
69pub struct ValidationParams {
70 /// Straight-line fit collinearity tolerance (fraction of the
71 /// per-corner scale).
72 pub line_tol_rel: f32,
73 /// Minimum members required to fit a line / column.
74 pub line_min_members: usize,
75 /// Local-H prediction tolerance (fraction of the per-corner
76 /// scale).
77 pub local_h_tol_rel: f32,
78 /// When `true`, line and local-H thresholds use a per-corner
79 /// local step computed from labelled grid neighbours via central
80 /// or one-sided finite differences (`(step_u + step_v) / 2`).
81 /// Corners without enough labelled neighbours fall back to the
82 /// global `cell_size`.
83 ///
84 /// Set this when the grid is non-uniform in pixel space —
85 /// perspective foreshortening, radial distortion, or rectified-
86 /// then-rasterised images. Has no effect on uniform grids.
87 pub use_step_aware: bool,
88 /// When `> 0` and [`use_step_aware`] is set, an additional flag
89 /// fires for corners whose local step deviates from the labelled-
90 /// set median by more than `step_deviation_thresh_rel` (relative).
91 /// E.g. `0.5` flags corners whose step is < 1/(1+0.5) of the
92 /// median or > (1+0.5)× the median.
93 ///
94 /// Combined with line flags via the existing attribution rules
95 /// (rule 4: step-deviation flag + ≥ 1 line flag → outlier).
96 /// Set to `0.0` to disable.
97 ///
98 /// [`use_step_aware`]: ValidationParams::use_step_aware
99 pub step_deviation_thresh_rel: f32,
100}
101
102impl Default for ValidationParams {
103 fn default() -> Self {
104 // Matches `calib_targets_chessboard::DetectorParams`'s
105 // validation defaults so the thin chessboard wrapper stays a
106 // pure forward of the same numbers. Step-aware mode is opt-in.
107 Self {
108 line_tol_rel: 0.15,
109 line_min_members: 3,
110 local_h_tol_rel: 0.20,
111 use_step_aware: false,
112 step_deviation_thresh_rel: 0.0,
113 }
114 }
115}
116
117impl ValidationParams {
118 /// Construct fully-specified core tolerances. Step-aware mode is
119 /// off by default; call [`with_step_aware`] to enable it.
120 ///
121 /// [`with_step_aware`]: ValidationParams::with_step_aware
122 pub fn new(line_tol_rel: f32, line_min_members: usize, local_h_tol_rel: f32) -> Self {
123 Self {
124 line_tol_rel,
125 line_min_members,
126 local_h_tol_rel,
127 use_step_aware: false,
128 step_deviation_thresh_rel: 0.0,
129 }
130 }
131
132 /// Enable per-corner step-aware thresholds. Pass
133 /// `deviation_thresh_rel = 0.0` for thresholds-only without the
134 /// extra step-deviation flag.
135 pub fn with_step_aware(mut self, deviation_thresh_rel: f32) -> Self {
136 self.use_step_aware = true;
137 self.step_deviation_thresh_rel = deviation_thresh_rel;
138 self
139 }
140}
141
142/// A single labelled corner fed into [`validate`]: its caller-chosen
143/// index (carried back in `ValidationResult::blacklist`), its pixel
144/// position, and its integer grid coordinate.
145///
146/// The index is opaque to this module — callers may pick any scheme
147/// (direct slice indices, corner struct fields, etc.) as long as the
148/// same scheme maps `blacklist` entries back to their originals.
149#[derive(Clone, Copy, Debug)]
150pub struct LabelledEntry {
151 pub idx: usize,
152 pub pixel: Point2<f32>,
153 pub grid: (i32, i32),
154}
155
156/// Outcome of one validation pass.
157#[derive(Debug, Default)]
158pub struct ValidationResult {
159 /// Corner indices to blacklist (attribution has been applied).
160 pub blacklist: HashSet<usize>,
161 /// For each labelled corner, its local-H residual in pixels
162 /// (`None` when fewer than 4 non-collinear neighbors were
163 /// available).
164 pub local_h_residuals: HashMap<usize, f32>,
165}
166
167/// Run both validation passes and produce a blacklist.
168#[cfg_attr(
169 feature = "tracing",
170 tracing::instrument(
171 level = "info",
172 skip_all,
173 fields(num_labelled = entries.len(), cell_size = cell_size),
174 )
175)]
176pub fn validate(
177 entries: &[LabelledEntry],
178 cell_size: f32,
179 params: &ValidationParams,
180) -> ValidationResult {
181 // Quick lookup maps (built once per call).
182 let by_idx: HashMap<usize, &LabelledEntry> = entries.iter().map(|e| (e.idx, e)).collect();
183 let by_grid: HashMap<(i32, i32), usize> = entries.iter().map(|e| (e.grid, e.idx)).collect();
184
185 // Per-corner scale: in step-aware mode this is the labelled-
186 // neighbour finite-difference step; otherwise it's the global
187 // cell_size for every corner.
188 let per_corner_step = if params.use_step_aware {
189 step::local_step_per_corner(&by_idx, &by_grid)
190 } else {
191 HashMap::new()
192 };
193 let scale_at = |idx: usize| -> f32 {
194 if params.use_step_aware {
195 per_corner_step.get(&idx).copied().unwrap_or(cell_size)
196 } else {
197 cell_size
198 }
199 };
200
201 // --- 7a. Line collinearity ------------------------------------------
202 let line_flags = lines::line_collinearity_flags(&by_idx, &by_grid, params, &scale_at);
203
204 // --- 7b. Local-H residual -------------------------------------------
205 let mut residuals: HashMap<usize, f32> = HashMap::new();
206 let mut local_h_flagged: HashMap<usize, f32> = HashMap::new();
207 let mut local_h_high: HashMap<usize, f32> = HashMap::new();
208 for entry in entries {
209 let base = local_h::pick_local_h_base(&by_grid, entry.idx, entry.grid);
210 if base.len() < 4 {
211 continue;
212 }
213 let Some(resid) =
214 local_h::local_h_residual(&by_idx, entry.idx, entry.grid, &base, &by_grid)
215 else {
216 continue;
217 };
218 residuals.insert(entry.idx, resid);
219 let scale = scale_at(entry.idx);
220 let local_h_tol_px = params.local_h_tol_rel * scale;
221 if resid > local_h_tol_px {
222 local_h_flagged.insert(entry.idx, resid);
223 if resid > 2.0 * local_h_tol_px {
224 local_h_high.insert(entry.idx, resid);
225 }
226 }
227 }
228
229 // --- 7c. Step-deviation flags (optional) ----------------------------
230 let step_dev_flags = if params.use_step_aware && params.step_deviation_thresh_rel > 0.0 {
231 step::flag_step_deviations(&per_corner_step, params.step_deviation_thresh_rel)
232 } else {
233 HashSet::new()
234 };
235
236 // --- 7d. Attribution ------------------------------------------------
237 let mut blacklist: HashSet<usize> = HashSet::new();
238 // Rule 1: ≥ 2 line flags → outlier.
239 for (&idx, &count) in &line_flags {
240 if count >= 2 {
241 blacklist.insert(idx);
242 }
243 }
244 // Rule 2: high local-H residual AND ≥ 1 line flag → outlier.
245 for &idx in local_h_high.keys() {
246 if line_flags.get(&idx).copied().unwrap_or(0) >= 1 {
247 blacklist.insert(idx);
248 }
249 }
250 // Rule 3: local-H flag with no line flag BUT base neighbor flagged
251 // in a line → blacklist the worst base instead.
252 for &idx in local_h_flagged.keys() {
253 if line_flags.get(&idx).copied().unwrap_or(0) >= 1 {
254 continue;
255 }
256 if blacklist.contains(&idx) {
257 continue;
258 }
259 let Some(entry) = by_idx.get(&idx) else {
260 continue;
261 };
262 let base = local_h::pick_local_h_base(&by_grid, idx, entry.grid);
263 let mut worst: Option<(usize, u32)> = None;
264 for base_idx in &base {
265 if let Some(&flags) = line_flags.get(base_idx) {
266 if flags >= 1 && worst.map(|w| flags > w.1).unwrap_or(true) {
267 worst = Some((*base_idx, flags));
268 }
269 }
270 }
271 if let Some((base_idx, _)) = worst {
272 blacklist.insert(base_idx);
273 }
274 }
275 // Rule 4: step-deviation flag AND ≥ 1 line flag → outlier.
276 // Rationale: a corner whose finite-difference step disagrees with
277 // the labelled-set median is a topology-consistency signal
278 // independent of line / local-H residuals. Combined with a line
279 // flag, it's strong evidence the corner is mis-labelled or sits
280 // on a different sub-grid (e.g., marker-internal corner that
281 // slipped past parity).
282 for &idx in &step_dev_flags {
283 if line_flags.get(&idx).copied().unwrap_or(0) >= 1 {
284 blacklist.insert(idx);
285 }
286 }
287
288 ValidationResult {
289 blacklist,
290 local_h_residuals: residuals,
291 }
292}
293
294#[cfg(test)]
295mod tests {
296 use super::*;
297
298 fn entry(idx: usize, x: f32, y: f32, i: i32, j: i32) -> LabelledEntry {
299 LabelledEntry {
300 idx,
301 pixel: Point2::new(x, y),
302 grid: (i, j),
303 }
304 }
305
306 fn clean_grid(rows: i32, cols: i32, s: f32) -> Vec<LabelledEntry> {
307 let mut out = Vec::new();
308 let mut idx = 0;
309 for j in 0..rows {
310 for i in 0..cols {
311 out.push(entry(idx, i as f32 * s + 50.0, j as f32 * s + 50.0, i, j));
312 idx += 1;
313 }
314 }
315 out
316 }
317
318 #[test]
319 fn clean_grid_empty_blacklist() {
320 let entries = clean_grid(7, 7, 20.0);
321 let res = validate(&entries, 20.0, &ValidationParams::default());
322 assert!(res.blacklist.is_empty(), "{:?}", res.blacklist);
323 }
324
325 #[test]
326 fn displaced_interior_is_blacklisted() {
327 let mut entries = clean_grid(7, 7, 20.0);
328 // Displace (3, 3) by ~6px in both directions — failing both
329 // line fits and the local-H residual check.
330 let target = entries
331 .iter_mut()
332 .find(|e| e.grid == (3, 3))
333 .expect("(3,3) present");
334 target.pixel.x += 6.0;
335 target.pixel.y += 6.0;
336 let target_idx = target.idx;
337 let res = validate(&entries, 20.0, &ValidationParams::default());
338 assert!(
339 res.blacklist.contains(&target_idx),
340 "expected {target_idx} blacklisted, got {:?}",
341 res.blacklist
342 );
343 }
344
345 #[test]
346 fn too_few_members_per_line_is_ignored() {
347 let entries = vec![entry(0, 0.0, 0.0, 0, 0), entry(1, 20.0, 0.0, 1, 0)];
348 let res = validate(&entries, 20.0, &ValidationParams::default());
349 assert!(res.blacklist.is_empty());
350 }
351
352 #[test]
353 fn step_aware_matches_global_on_uniform_grid() {
354 // On a uniform grid, per-corner step ≈ cell_size everywhere,
355 // so step-aware mode must agree with the default mode.
356 let entries = clean_grid(7, 7, 20.0);
357 let res_default = validate(&entries, 20.0, &ValidationParams::default());
358 let res_step_aware = validate(
359 &entries,
360 20.0,
361 &ValidationParams::default().with_step_aware(0.0),
362 );
363 assert_eq!(res_default.blacklist, res_step_aware.blacklist);
364 }
365
366 #[test]
367 fn step_aware_flags_perspective_foreshortened_outlier() {
368 // Build a grid whose right column has cell pitch ~10 px (half
369 // of the rest at 20 px). On a uniform-`cell_size = 20` global
370 // tolerance, a corner displaced by 4 px in the dense column
371 // sits at 4 / 20 = 0.20 of the global cell. With step-aware
372 // (local step ~10 px), the same residual sits at 4 / 10 = 0.40
373 // — the tighter per-corner threshold catches it where the
374 // global one would defer.
375 //
376 // Layout: 5x4 grid. Columns 0..3 at 20 px pitch; column 4 at
377 // 10 px from column 3.
378 let s = 20.0_f32;
379 let mut entries = Vec::new();
380 let mut idx = 0;
381 for j in 0..4_i32 {
382 for i in 0..4_i32 {
383 entries.push(entry(idx, i as f32 * s + 50.0, j as f32 * s + 50.0, i, j));
384 idx += 1;
385 }
386 }
387 // Column 4: half-pitch (foreshortened).
388 for j in 0..4_i32 {
389 entries.push(entry(
390 idx,
391 3.0 * s + 50.0 + 0.5 * s, // x = 110 (one half-step past column 3 at x = 110)
392 j as f32 * s + 50.0,
393 4,
394 j,
395 ));
396 idx += 1;
397 }
398 // Verify baseline: no outliers.
399 let baseline = validate(&entries, s, &ValidationParams::default());
400 assert!(baseline.blacklist.is_empty(), "{:?}", baseline.blacklist);
401
402 // Displace (4, 1) — the dense-column corner — by 3 px in y.
403 let target_idx = entries
404 .iter()
405 .find(|e| e.grid == (4, 1))
406 .map(|e| e.idx)
407 .expect("(4, 1) present");
408 for e in entries.iter_mut() {
409 if e.idx == target_idx {
410 e.pixel.y += 3.0;
411 }
412 }
413
414 let global_res = validate(&entries, s, &ValidationParams::default());
415 let step_aware_res = validate(
416 &entries,
417 s,
418 &ValidationParams::default().with_step_aware(0.0),
419 );
420
421 assert!(
422 step_aware_res.blacklist.contains(&target_idx)
423 || !global_res.blacklist.contains(&target_idx),
424 "step-aware should be at least as sensitive: global={:?} step-aware={:?}",
425 global_res.blacklist,
426 step_aware_res.blacklist
427 );
428 }
429
430 #[test]
431 fn step_deviation_flag_fires_on_off_scale_corner() {
432 let s = 20.0_f32;
433 let mut entries = clean_grid(5, 5, s);
434 let new_idx = entries.len();
435 entries.push(entry(
436 new_idx,
437 4.0 * s + 0.5 * s + 50.0,
438 2.0 * s + 50.0,
439 5,
440 2,
441 ));
442 entries[new_idx].pixel.y += 4.0;
443
444 let res = validate(
445 &entries,
446 s,
447 &ValidationParams::default().with_step_aware(0.5),
448 );
449 assert!(
450 res.blacklist.contains(&new_idx),
451 "expected new corner {new_idx} blacklisted: {:?}",
452 res.blacklist
453 );
454 }
455
456 #[test]
457 fn local_step_per_corner_central_diff() {
458 // Verify the helper produces central-difference values when
459 // both neighbours are present, and one-sided otherwise.
460 let entries = [
461 entry(0, 0.0, 0.0, 0, 0),
462 entry(1, 10.0, 0.0, 1, 0),
463 entry(2, 30.0, 0.0, 2, 0), // i-step at (1, 0): central = (30 - 0)/2 = 15
464 entry(3, 30.0, 20.0, 2, 1), // j-step at (2, 0): one-sided forward = 20
465 ];
466 let by_idx: HashMap<usize, &LabelledEntry> = entries.iter().map(|e| (e.idx, e)).collect();
467 let by_grid: HashMap<(i32, i32), usize> = entries.iter().map(|e| (e.grid, e.idx)).collect();
468 let steps = step::local_step_per_corner(&by_idx, &by_grid);
469
470 // (1, 0): central i-step = 15; no j neighbours → step = 15.
471 assert!((steps[&1] - 15.0).abs() < 1e-4, "got {}", steps[&1]);
472 // (2, 0): one-sided i-step backward = 20; j-step forward = 20 → mean = 20.
473 assert!((steps[&2] - 20.0).abs() < 1e-4, "got {}", steps[&2]);
474 }
475}