projective-grid 0.10.0

Image-free, target-agnostic projective grid recovery: label 2D feature points with (i, j) lattice coordinates under perspective
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
//! Post-grow fill pass: interior holes + line extrapolation.
//!
//! [`fill_grid_holes`] is the pattern-agnostic "booster" pass that
//! runs **after** a component-assembly + validate pass has converged.
//! It enumerates `(i, j)` cells inside the labelled bounding box that
//! are still empty, plus `±1` cells immediately outside each row /
//! column boundary, and tries to attach a candidate at each one using
//! the same per-cell ladder as the [`crate::shared::grow`] candidate
//! search.
//!
//! # Precision contract
//!
//! Fill attachments must obey the same invariants as BFS-grow
//! attachments. The policy's existing gates (`is_eligible`,
//! `required_label_at`, `label_of`, `accept_candidate`) are reused
//! verbatim; the edge check delegates to [`SquareAttachPolicy::fill_edge_ok`]
//! which, by default, forwards to [`SquareAttachPolicy::edge_ok`].
//!
//! # Pattern extension points
//!
//! Two optional methods on [`SquareAttachPolicy`] let pattern crates
//! customise the fill pass without touching this module:
//!
//! - [`SquareAttachPolicy::eligible_for_fill`] — widen the admissible
//!   candidate set during the booster pass (e.g. admit near-cluster
//!   corners that the precision core dropped by a hair).
//! - [`SquareAttachPolicy::fill_edge_ok`] — replace the scalar-`cell_size`
//!   edge-length check with a labelled-set-aware (e.g. directional
//!   median) variant. Useful when a component is strongly anisotropic
//!   before final recovery has filled the boundary.
//!
//! Patterns whose precision core is strict enough that the booster
//! pass should not relax anything need not override either method —
//! the defaults forward to `is_eligible` and `edge_ok`.
//!
//! # Iteration
//!
//! The pass iterates until a full scan attaches zero new corners,
//! capped at `max_iters`. Each iteration rebuilds the KD-tree over
//! `eligible_for_fill` candidates because the previous iteration's
//! attachments shrink the eligible set.

use crate::shared::grow::{
    collect_labelled_neighbours, predict_from_neighbours, Admit, FillEdgeCtx, GrowResult,
    SquareAttachPolicy,
};
use kiddo::{KdTree, SquaredEuclidean};
use nalgebra::Point2;

/// Tunables for [`fill_grid_holes`].
#[non_exhaustive]
#[derive(Clone, Copy, Debug)]
pub struct FillParams {
    /// Candidate-search radius (fraction of `cell_size`) around each
    /// per-cell prediction.
    pub attach_search_rel: f32,
    /// Ambiguity factor: if the second-nearest candidate is within
    /// `factor × nearest_distance`, the cell is skipped.
    pub attach_ambiguity_factor: f32,
    /// Maximum number of full scans. Defaults to 1 — most boards
    /// converge in one pass, and the precision contract is identical
    /// per iteration, so additional iterations only help when an
    /// attached corner enables further attachments in the same
    /// cell's 3×3 window.
    pub max_iters: usize,
}

impl Default for FillParams {
    fn default() -> Self {
        Self {
            attach_search_rel: 0.35,
            attach_ambiguity_factor: 1.5,
            max_iters: 1,
        }
    }
}

impl FillParams {
    /// Construct fill parameters from the search radius (relative to
    /// `cell_size`), the ambiguity factor, and the maximum scan count.
    pub fn new(attach_search_rel: f32, attach_ambiguity_factor: f32, max_iters: usize) -> Self {
        Self {
            attach_search_rel,
            attach_ambiguity_factor,
            max_iters,
        }
    }
}

/// Counters returned by [`fill_grid_holes`].
#[non_exhaustive]
#[derive(Clone, Debug, Default)]
pub struct FillStats {
    /// Total number of corners attached across all iterations.
    pub added: usize,
    /// Number of full scans performed.
    pub iterations: usize,
    /// Corner indices of all attached corners (parallel to
    /// [`attached_cells`][FillStats::attached_cells]). Callers use
    /// this to update per-corner state without re-scanning
    /// `grow.labelled`.
    pub attached_indices: Vec<usize>,
    /// Grid cells at which each attached corner was placed.
    pub attached_cells: Vec<(i32, i32)>,
}

/// Run the unified fill pass: interior gap fill + line extrapolation.
///
/// Mutates `grow.labelled` and `grow.by_corner` in place. The caller
/// is responsible for downstream per-corner state updates (e.g.
/// marking newly-attached corners as "Labeled" in a local stage enum)
/// — `fill_grid_holes` records the attached indices in
/// [`FillStats::attached_indices`] so the caller can sweep them
/// without re-scanning the labelled map.
///
/// Returns a [`FillStats`] summary.
pub fn fill_grid_holes<V: SquareAttachPolicy>(
    positions: &[Point2<f32>],
    grow: &mut GrowResult,
    cell_size: f32,
    params: &FillParams,
    policy: &V,
) -> FillStats {
    let mut stats = FillStats::default();
    if grow.labelled.is_empty() {
        return stats;
    }

    for _iter in 0..params.max_iters.max(1) {
        stats.iterations += 1;
        let (tree, slot_to_corner) = build_fill_tree(positions, grow, policy);
        let ctx = FillCtx {
            positions,
            cell_size,
            params,
            tree: &tree,
            slot_to_corner: &slot_to_corner,
            policy,
        };

        let cells = enumerate_fill_cells(grow);
        let mut added_this_iter = 0usize;
        for cell in cells {
            if grow.labelled.contains_key(&cell) {
                continue;
            }
            if let Some(attached_idx) = try_fill_cell(cell, grow, &ctx) {
                stats.attached_indices.push(attached_idx);
                stats.attached_cells.push(cell);
                added_this_iter += 1;
            }
        }
        stats.added += added_this_iter;
        if added_this_iter == 0 {
            break;
        }
    }

    stats
}

fn build_fill_tree<V: SquareAttachPolicy>(
    positions: &[Point2<f32>],
    grow: &GrowResult,
    policy: &V,
) -> (KdTree<f32, 2>, Vec<usize>) {
    let mut tree: KdTree<f32, 2> = KdTree::new();
    let mut slot_to_corner: Vec<usize> = Vec::new();
    for (idx, pos) in positions.iter().enumerate() {
        if policy.eligible_for_fill(idx) && !grow.by_corner.contains_key(&idx) {
            tree.add(&[pos.x, pos.y], slot_to_corner.len() as u64);
            slot_to_corner.push(idx);
        }
    }
    (tree, slot_to_corner)
}

/// Cells to try: every unlabelled cell inside the labelled bbox plus
/// `±1` rows / columns just outside.
fn enumerate_fill_cells(grow: &GrowResult) -> Vec<(i32, i32)> {
    use std::collections::HashSet;
    let mut out: HashSet<(i32, i32)> = HashSet::new();
    let (mut min_i, mut max_i, mut min_j, mut max_j) = (i32::MAX, i32::MIN, i32::MAX, i32::MIN);
    for &(i, j) in grow.labelled.keys() {
        min_i = min_i.min(i);
        max_i = max_i.max(i);
        min_j = min_j.min(j);
        max_j = max_j.max(j);
    }

    // Interior gap fill: every unlabelled cell inside the bbox.
    for j in min_j..=max_j {
        for i in min_i..=max_i {
            if !grow.labelled.contains_key(&(i, j)) {
                out.insert((i, j));
            }
        }
    }

    // Line extrapolation: ±1 beyond the bbox ends, at every row
    // and column that has any labelled member.
    for j in min_j..=max_j {
        out.insert((min_i - 1, j));
        out.insert((max_i + 1, j));
    }
    for i in min_i..=max_i {
        out.insert((i, min_j - 1));
        out.insert((i, max_j + 1));
    }

    // Determinism: the fill pass attaches corners greedily in scan
    // order, and two adjacent candidate cells can compete for the same
    // boundary corner (whichever cell is visited first claims it). A
    // `HashSet` iteration order is randomized per process, so returning
    // the raw set order makes the labelled boundary extent vary run to
    // run for identical input. Sort by `(i, j)` to pin the scan order;
    // this is byte-stable across runs and does not change the outcome
    // for inputs whose attachments are uncontested (the common case for
    // the topological recovery caller).
    let mut cells: Vec<(i32, i32)> = out.into_iter().collect();
    cells.sort_unstable();
    cells
}

/// Per-iteration context for the fill pass.
///
/// Bundles the references that every per-cell call would otherwise
/// have to re-thread. Each iteration of [`fill_grid_holes`] builds one
/// of these once and reuses it for all candidate cells.
struct FillCtx<'a, V: SquareAttachPolicy> {
    positions: &'a [Point2<f32>],
    cell_size: f32,
    params: &'a FillParams,
    tree: &'a KdTree<f32, 2>,
    slot_to_corner: &'a [usize],
    policy: &'a V,
}

fn try_fill_cell<V: SquareAttachPolicy>(
    cell: (i32, i32),
    grow: &mut GrowResult,
    ctx: &FillCtx<'_, V>,
) -> Option<usize> {
    let positions = ctx.positions;
    let cell_size = ctx.cell_size;
    let params = ctx.params;
    let tree = ctx.tree;
    let slot_to_corner = ctx.slot_to_corner;
    let policy = ctx.policy;
    // Collect 8-connected labelled neighbours of `cell`. For interior
    // gaps this will usually be 4+; for line extensions it will be 1
    // (the last corner of the line) up to 3 (with diagonals from
    // adjacent labelled rows).
    let neighbours = collect_labelled_neighbours(cell, 1, &grow.labelled, positions);
    if neighbours.is_empty() {
        return None;
    }

    // Adaptive prediction: each labelled neighbour contributes a
    // finite-difference local-step from its own labelled peers when
    // available, falling back to the global `(u, v) × cell_size` step
    // otherwise.
    let pred = predict_from_neighbours(
        cell,
        &neighbours,
        grow.axis_i,
        grow.axis_j,
        cell_size,
        &grow.labelled,
        positions,
    );

    // Optional caller-defined label required at this cell.
    let required_label = policy.required_label_at(cell.0, cell.1);

    // Candidate search.
    let search_r = params.attach_search_rel * cell_size;
    let r2 = search_r * search_r;
    let mut hits: Vec<(usize, f32)> = Vec::new();
    for nn in tree
        .within_unsorted::<SquaredEuclidean>(&[pred.x, pred.y], r2)
        .into_iter()
    {
        let slot = nn.item as usize;
        let idx = slot_to_corner[slot];
        if grow.by_corner.contains_key(&idx) {
            continue;
        }
        if let Some(req) = required_label {
            if policy.label_of(idx) != Some(req) {
                continue;
            }
        }
        if matches!(
            policy.accept_candidate(idx, cell, pred, &neighbours),
            Admit::Reject
        ) {
            continue;
        }
        hits.push((idx, nn.distance.sqrt()));
    }
    hits.sort_by(|a, b| a.1.total_cmp(&b.1));

    let candidate_idx = match hits.len() {
        0 => return None,
        1 => hits[0].0,
        _ => {
            let d0 = hits[0].1.max(f32::EPSILON);
            let d1 = hits[1].1;
            if d1 / d0 < params.attach_ambiguity_factor {
                return None;
            }
            hits[0].0
        }
    };

    // Edge-invariant check via the policy's fill-aware variant.
    // At least one cardinal labelled neighbour must accept the
    // candidate; a policy can swap the scalar
    // `cell_size` for a directional median here when its component
    // is strongly anisotropic.
    if !any_cardinal_fill_edge_ok(
        candidate_idx,
        cell,
        positions,
        &grow.labelled,
        policy,
        cell_size,
    ) {
        return None;
    }

    // Attach.
    grow.labelled.insert(cell, candidate_idx);
    grow.by_corner.insert(candidate_idx, cell);
    Some(candidate_idx)
}

fn any_cardinal_fill_edge_ok<V: SquareAttachPolicy>(
    c_idx: usize,
    pos: (i32, i32),
    positions: &[Point2<f32>],
    labelled: &std::collections::HashMap<(i32, i32), usize>,
    policy: &V,
    cell_size: f32,
) -> bool {
    let mut found_any = false;
    for (di, dj) in [(1, 0), (-1, 0), (0, 1), (0, -1)] {
        let neigh = (pos.0 + di, pos.1 + dj);
        if let Some(&n_idx) = labelled.get(&neigh) {
            found_any = true;
            let ctx = FillEdgeCtx {
                candidate_idx: c_idx,
                neighbour_idx: n_idx,
                at_candidate: pos,
                at_neighbour: neigh,
                labelled,
                positions,
                cell_size,
            };
            if policy.fill_edge_ok(ctx) {
                return true;
            }
        }
    }
    !found_any
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::shared::grow::{Admit, LabelledNeighbour};
    use std::collections::HashMap;

    /// Trivial policy: every corner eligible, no label constraint,
    /// accept everything, accept all edges.
    struct OpenValidator;

    impl SquareAttachPolicy for OpenValidator {
        fn is_eligible(&self, _idx: usize) -> bool {
            true
        }
        fn required_label_at(&self, _i: i32, _j: i32) -> Option<u8> {
            None
        }
        fn label_of(&self, _idx: usize) -> Option<u8> {
            None
        }
        fn accept_candidate(
            &self,
            _idx: usize,
            _at: (i32, i32),
            _prediction: Point2<f32>,
            _neighbours: &[LabelledNeighbour],
        ) -> Admit {
            Admit::Accept
        }
    }

    #[test]
    fn fill_pass_attaches_interior_hole() {
        // 3×3 grid; (1, 1) un-labelled, surrounded by 8 neighbours.
        let s = 20.0_f32;
        let mut positions: Vec<Point2<f32>> = Vec::new();
        for j in 0..3 {
            for i in 0..3 {
                positions.push(Point2::new(50.0 + i as f32 * s, 50.0 + j as f32 * s));
            }
        }
        let mut labelled: HashMap<(i32, i32), usize> = HashMap::new();
        let mut by_corner: HashMap<usize, (i32, i32)> = HashMap::new();
        for j in 0..3 {
            for i in 0..3 {
                if (i, j) == (1, 1) {
                    continue;
                }
                let idx = (j * 3 + i) as usize;
                labelled.insert((i, j), idx);
                by_corner.insert(idx, (i, j));
            }
        }
        let mut grow = GrowResult {
            labelled,
            by_corner,
            ambiguous: Default::default(),
            holes: Default::default(),
            axis_i: nalgebra::Vector2::new(1.0, 0.0),
            axis_j: nalgebra::Vector2::new(0.0, 1.0),
            rebase_i_mod2: 0,
            rebase_j_mod2: 0,
        };
        let stats = fill_grid_holes(
            &positions,
            &mut grow,
            s,
            &FillParams::default(),
            &OpenValidator,
        );
        assert_eq!(stats.added, 1);
        assert_eq!(grow.labelled.get(&(1, 1)), Some(&4));
        assert_eq!(stats.attached_indices, vec![4]);
        assert_eq!(stats.attached_cells, vec![(1, 1)]);
    }
}