Skip to main content

projective_grid/shared/
recovery_schedule.rs

1//! Geometry-only post-convergence recovery schedule (advanced tier).
2//!
3//! After a component-assembly pass has produced one self-consistent labelled
4//! component, recall on a foreshortened / partially-occluded grid is still
5//! bounded by how far the growth frontier reached before the per-edge band or
6//! the synthesized-axis voucher stalled it. This module composes the
7//! boundary-extension and interior-fill engines, interleaved with revalidation
8//! and the lattice-general drop filters, into a single fixed-point schedule
9//! that pushes recall up to the dense-recovery level the topological walk
10//! reaches — **without** any target-specific vocabulary.
11//!
12//! # Stage order
13//!
14//! The schedule mirrors the *geometry-only* subset of the chessboard
15//! detector's `run_converged_iteration` sequence (extension → fill → final
16//! geometry check), dropping the ChESS-coupled stages (slot-flip fix, cluster
17//! refit, NoCluster rescue) that have no meaning for a generic
18//! [`SquareAttachPolicy`]:
19//!
20//! 1. **boundary extension** — [`extend_via_local_homography`] fits a
21//!    per-candidate local homography from the K nearest labelled corners and
22//!    projects integer cells past the labelled boundary. Local-H tracks
23//!    perspective foreshortening where one global H cannot, so it is the
24//!    workhorse for the orientation-free perspective case. Followed by
25//!    [`extend_from_labelled`] (cardinal-BFS extension) which mops up cells the
26//!    local-H residual gate refused but a single-edge prediction can still
27//!    reach.
28//! 2. **interior fill** — [`fill_grid_holes`] enumerates still-empty cells
29//!    inside the labelled bounding box (plus a one-cell skirt) and attaches a
30//!    candidate at each using the same per-cell ladder as BFS grow.
31//! 3. **revalidation** — the shared [`validate`](crate::shared::validate::validate)
32//!    pass (line collinearity + local-H residual) drops any corner the
33//!    extension / fill attached that does not cohere with its neighbourhood.
34//! 4. **drop filters** — the lattice-general filters in
35//!    [`crate::shared::validate::wrong_label_filters`]: the topological wrong-label drops
36//!    (overlong / off-axis / duplicate-pixel edges), then the
37//!    largest-cardinally-connected-component filter (a square detection is one
38//!    connected planar graph; any stranded sub-component is a false positive).
39//!
40//! The whole sequence repeats until a full pass attaches zero new corners (a
41//! fixed point) or the iteration cap is reached. On a clean grid that the loop
42//! already recovered fully, the first extension pass attaches nothing and the
43//! schedule returns immediately.
44//!
45//! # Precision contract
46//!
47//! Every attachment runs through the same [`SquareAttachPolicy`] gates as BFS
48//! grow (`is_eligible`, `required_label_at` / `label_of`, `accept_candidate`,
49//! `edge_ok`) plus the extension residual gate, then through revalidation and
50//! the drop filters. A corner whose geometry does not cohere is *dropped*, not
51//! mislabelled. The schedule can therefore only ever *raise* recall toward the
52//! true grid or *shrink* a component it cannot justify — it can never introduce
53//! a wrong `(i, j)` label that the gates would not have caught on the BFS path.
54//!
55//! # Gating
56//!
57//! The schedule is opt-in via [`RecoverySchedule`] on the caller's params; the
58//! facade enables it for the orientation-free / position paths, while the
59//! chessboard topological adapter (which disables the facade validate/fit and
60//! runs its own `CornerStage`-coupled recovery) leaves it off so its production
61//! output stays byte-identical.
62
63use std::collections::{HashMap, HashSet};
64
65use nalgebra::{Point2, Vector2};
66
67use crate::shared::extension::{extend_via_local_homography, LocalExtensionParams};
68use crate::shared::fill::{fill_grid_holes, FillParams};
69use crate::shared::grow::{GrowParams, GrowResult, SquareAttachPolicy};
70use crate::shared::grow_extend::extend_from_labelled;
71use crate::shared::validate::{self as pg_validate, ValidationParams};
72
73/// Provenance relevant to the default square recovery policy.
74///
75/// This stays internal: callers select an [`Evidence`](crate::detect::Evidence)
76/// kind, while the facade records whether the Oriented2 evidence reaching the
77/// square detector was supplied natively or contains synthesized axes.
78#[derive(Clone, Copy, Debug, PartialEq, Eq)]
79pub(crate) enum SquareAxisProvenance {
80    /// Both square axis families were supplied by the caller.
81    FullyMeasured,
82    /// At least one square axis family was synthesized by the facade.
83    IncludesSynthesized,
84}
85
86/// Tuning for the geometry-only recovery schedule.
87///
88/// Defaults are conservative: a single fixed-point sweep of extension + fill
89/// with the engines' own defaults, followed by revalidation and the
90/// component / wrong-label drop filters. Raise [`max_sweeps`](Self::max_sweeps)
91/// to let a strongly foreshortened grid propagate further outward.
92#[non_exhaustive]
93#[derive(Clone, Debug)]
94pub struct RecoveryParams {
95    /// Local-homography boundary extension knobs.
96    pub local_extension: LocalExtensionParams,
97    /// Cardinal-BFS boundary extension knobs (the mop-up pass after local-H).
98    pub bfs_extension: GrowParams,
99    /// Interior-fill knobs.
100    pub fill: FillParams,
101    /// Maximum number of (extend → fill → validate → drop) sweeps. Each sweep
102    /// is idempotent on a converged grid, so the schedule stops early on the
103    /// first zero-attachment sweep.
104    pub max_sweeps: u32,
105    /// Whether to apply the topological wrong-label drop filter (overlong /
106    /// off-axis / duplicate-pixel edges) after revalidation. The orientation-
107    /// free path enables it; it is the strongest guard against a synthesized-
108    /// axis mislabel slipping through the per-edge band.
109    pub apply_wrong_label_drops: bool,
110    /// Whether to keep only the largest cardinally-connected component after
111    /// the drop filters. A square detection is one connected planar graph, so
112    /// any stranded sub-component a drop orphaned is a false positive.
113    pub apply_largest_component: bool,
114}
115
116impl Default for RecoveryParams {
117    fn default() -> Self {
118        Self {
119            local_extension: LocalExtensionParams::default(),
120            bfs_extension: GrowParams::default(),
121            fill: FillParams::default(),
122            max_sweeps: 4,
123            apply_wrong_label_drops: true,
124            apply_largest_component: true,
125        }
126    }
127}
128
129/// Whether a detection path runs the geometry-only recovery schedule.
130///
131/// The default is [`Auto`](Self::Auto): the detection facade enables the
132/// schedule for the synthesized-axis paths (`Evidence::Positions` /
133/// `Evidence::Oriented1`, whose recall is bounded by the BFS frontier) and
134/// leaves it off for the native `Evidence::Oriented2` path (which stays
135/// byte-compatible). A caller that runs its own `CornerStage`-coupled recovery
136/// downstream — the chessboard topological adapter — sets it explicitly to
137/// [`Off`](Self::Off) so the facade adds nothing, keeping production output
138/// byte-identical.
139#[non_exhaustive]
140#[derive(Clone, Debug, Default)]
141pub enum RecoverySchedule {
142    /// Facade decides per evidence kind (default): on for synthesized-axis
143    /// paths, off for native `Oriented2`.
144    #[default]
145    Auto,
146    /// Run no post-convergence recovery (the explicit byte-compat opt-out for
147    /// callers that recover downstream themselves).
148    Off,
149    /// Always run the geometry-only recovery schedule with the given tuning.
150    On(RecoveryParams),
151}
152
153impl RecoverySchedule {
154    /// Resolve the schedule for a concrete square-evidence provenance.
155    ///
156    /// `Auto` enables recovery only when the facade synthesized at least one
157    /// axis family. `Off` stays off; `On(p)` always runs with `p`.
158    pub(crate) fn resolve(&self, axis_provenance: SquareAxisProvenance) -> Option<RecoveryParams> {
159        match self {
160            RecoverySchedule::Auto
161                if axis_provenance == SquareAxisProvenance::IncludesSynthesized =>
162            {
163                Some(RecoveryParams::default())
164            }
165            RecoverySchedule::Auto => None,
166            RecoverySchedule::Off => None,
167            RecoverySchedule::On(p) => Some(p.clone()),
168        }
169    }
170}
171
172/// Summary of one [`run_schedule`] invocation. Data carrier.
173#[derive(Clone, Debug, Default)]
174pub struct RecoveryStats {
175    /// Number of (extend → fill → validate → drop) sweeps actually run.
176    pub sweeps: u32,
177    /// Net corners added across the whole schedule (attachments minus drops).
178    pub net_added: i64,
179    /// Total corners attached by the extension + fill engines.
180    pub attached: usize,
181    /// Total corners dropped by revalidation + the drop filters.
182    pub dropped: usize,
183}
184
185/// Run the geometry-only recovery schedule over a converged labelled component.
186///
187/// `grow` carries the converged labelled set plus the seed-derived axis
188/// vectors (used by the cardinal-BFS extension for its prediction direction).
189/// `cell_size` is the component's estimated cell pitch. `validate_params` is
190/// the same [`ValidationParams`] the convergence loop used, so revalidation is
191/// consistent with the inner gates. The schedule mutates `grow.labelled` /
192/// `grow.by_corner` in place and returns a [`RecoveryStats`] summary.
193///
194/// `strength_of` maps a corner index to a detector-response strength; it is
195/// reserved for callers that want a weak-leaf peel (the facade passes a
196/// constant, so the weak-leaf pass is a no-op and only the connectivity /
197/// wrong-label filters fire). Determinism: the engines and filters break ties
198/// by index / sorted coordinate, so repeated runs are byte-identical.
199pub fn run_schedule<V: SquareAttachPolicy>(
200    positions: &[Point2<f32>],
201    grow: &mut GrowResult,
202    cell_size: f32,
203    policy: &V,
204    params: &RecoveryParams,
205    validate_params: &ValidationParams,
206) -> RecoveryStats {
207    let mut stats = RecoveryStats::default();
208    if grow.labelled.len() < 4 {
209        return stats;
210    }
211    ensure_axes(grow, positions);
212
213    let start = grow.labelled.len() as i64;
214    for _sweep in 0..params.max_sweeps.max(1) {
215        stats.sweeps += 1;
216        let before = grow.labelled.len();
217
218        // Stage 1: boundary extension (local-H then cardinal-BFS mop-up).
219        let local = extend_via_local_homography(
220            positions,
221            grow,
222            cell_size,
223            &params.local_extension,
224            policy,
225        );
226        stats.attached += local.attached;
227        let bfs = extend_from_labelled(positions, grow, cell_size, &params.bfs_extension, policy);
228        stats.attached += bfs.attached;
229
230        // Stage 2: interior fill.
231        let fill = fill_grid_holes(positions, grow, cell_size, &params.fill, policy);
232        stats.attached += fill.added;
233
234        // Stage 3 + 4: revalidate, then apply the lattice-general drop filters.
235        let dropped = revalidate_and_filter(positions, grow, cell_size, params, validate_params);
236        stats.dropped += dropped;
237
238        // Fixed point: a sweep that neither grew nor shrank the labelled set
239        // cannot make progress on the next one (the engines are idempotent on
240        // a stable set), so stop.
241        if grow.labelled.len() == before {
242            break;
243        }
244    }
245
246    stats.net_added = grow.labelled.len() as i64 - start;
247    stats
248}
249
250/// Revalidate the labelled set and apply the wrong-label / largest-component
251/// drop filters. Returns the number of corners dropped this sweep.
252fn revalidate_and_filter(
253    positions: &[Point2<f32>],
254    grow: &mut GrowResult,
255    cell_size: f32,
256    params: &RecoveryParams,
257    validate_params: &ValidationParams,
258) -> usize {
259    // The validate + wrong-label + largest-component composition (and its
260    // deterministic input ordering) lives in the shared `drop_set` helper,
261    // which the chessboard detector's final geometry check also routes
262    // through; only the application to this `GrowResult` stays here.
263    let result = pg_validate::wrong_label_filters::drop_set(
264        &grow.labelled,
265        |idx| positions[idx],
266        cell_size,
267        validate_params,
268        params.apply_wrong_label_drops,
269        params.apply_largest_component,
270    );
271
272    if result.drop.is_empty() {
273        return 0;
274    }
275    let mut removed = 0usize;
276    grow.labelled.retain(|_, &mut idx| {
277        if result.drop.contains(&idx) {
278            removed += 1;
279            false
280        } else {
281            true
282        }
283    });
284    grow.by_corner.retain(|idx, _| !result.drop.contains(idx));
285    removed
286}
287
288/// Ensure `grow.axis_i` / `grow.axis_j` are usable unit vectors for the
289/// cardinal-BFS extension. The facade reconstructs `GrowResult` from a labelled
290/// map and may not carry seed axes, so estimate them from the labelled set's
291/// mean cardinal edges when they are degenerate.
292fn ensure_axes(grow: &mut GrowResult, positions: &[Point2<f32>]) {
293    let needs = grow.axis_i.norm() < 1e-3 || grow.axis_j.norm() < 1e-3;
294    if !needs {
295        return;
296    }
297    let (mut sum_i, mut n_i) = (Vector2::<f32>::zeros(), 0u32);
298    let (mut sum_j, mut n_j) = (Vector2::<f32>::zeros(), 0u32);
299    for (&(i, j), &idx) in &grow.labelled {
300        let here = positions[idx];
301        if let Some(&n) = grow.labelled.get(&(i + 1, j)) {
302            sum_i += positions[n] - here;
303            n_i += 1;
304        }
305        if let Some(&n) = grow.labelled.get(&(i, j + 1)) {
306            sum_j += positions[n] - here;
307            n_j += 1;
308        }
309    }
310    if n_i > 0 {
311        let v = sum_i / n_i as f32;
312        if v.norm() > 1e-3 {
313            grow.axis_i = v.normalize();
314        }
315    }
316    if n_j > 0 {
317        let v = sum_j / n_j as f32;
318        if v.norm() > 1e-3 {
319            grow.axis_j = v.normalize();
320        }
321    }
322    if grow.axis_i.norm() < 1e-3 {
323        grow.axis_i = Vector2::new(1.0, 0.0);
324    }
325    if grow.axis_j.norm() < 1e-3 {
326        grow.axis_j = Vector2::new(0.0, 1.0);
327    }
328}
329
330/// Run the geometry-only recovery schedule over a set of merged components,
331/// masking each component's recovery against the corners owned by the others
332/// (single-claim across components), then rebasing each recovered component to
333/// the non-negative `(i, j)` origin. Shared by both facades' synthesized-axis
334/// path.
335/// Shared borrows threaded through the recovery entry points. Bundling them
336/// keeps the public `recover_components` / `recover_positions_component`
337/// signatures within the workspace argument-count limit without an inline
338/// clippy allow.
339#[derive(Clone, Copy)]
340pub(crate) struct RecoveryInputs<'a> {
341    /// Features carrying positions + (synthesized) axes.
342    pub features: &'a [crate::feature::OrientedFeature<2>],
343    /// Corner positions, indexed 1:1 with `features`.
344    pub positions: &'a [Point2<f32>],
345    /// Per-corner robust local pitch (see [`local_pitch_of`]).
346    pub local_pitch: &'a [f32],
347    /// Recovery schedule tuning.
348    pub params: &'a RecoveryParams,
349    /// Validation tuning reused by the schedule's revalidation pass.
350    pub validate_params: &'a ValidationParams,
351}
352
353pub(crate) fn recover_components(
354    merged: Vec<HashMap<(i32, i32), usize>>,
355    inputs: RecoveryInputs<'_>,
356) -> Vec<HashMap<(i32, i32), usize>> {
357    let RecoveryInputs { positions, .. } = inputs;
358    // Recover largest-first. A perspective grid that the convergence loop
359    // fragmented into one large component plus a few small ones (the BFS
360    // frontier stalled on the foreshortened side, then re-seeded) is best
361    // healed by letting the *largest* component's extension / fill absorb the
362    // fragments' corners — the fragments carry their own (incompatible) local
363    // origin, so the merge could not reunite them, but the big component's
364    // local-H extension reaches them directly. So a corner is masked for a
365    // component only if an *already-recovered* (i.e. larger) component claimed
366    // it; a corner still sitting in a smaller, not-yet-recovered fragment is
367    // left available for the larger component to absorb.
368    let mut order: Vec<usize> = (0..merged.len()).collect();
369    order.sort_by(|&a, &b| {
370        merged[b]
371            .len()
372            .cmp(&merged[a].len())
373            .then_with(|| min_index(&merged[a]).cmp(&min_index(&merged[b])))
374    });
375
376    let mut claimed: HashSet<usize> = HashSet::new();
377    let mut recovered_by_slot: Vec<HashMap<(i32, i32), usize>> = vec![HashMap::new(); merged.len()];
378    for &k in &order {
379        // Drop any corner an already-recovered (larger) component absorbed, so
380        // two solutions never reference the same corner index. A fragment whose
381        // members were fully absorbed collapses to empty and is filtered out.
382        let comp: HashMap<(i32, i32), usize> = merged[k]
383            .iter()
384            .filter(|(_, &idx)| !claimed.contains(&idx))
385            .map(|(&k, &v)| (k, v))
386            .collect();
387        if comp.len() < 4 {
388            for &idx in comp.values() {
389                claimed.insert(idx);
390            }
391            recovered_by_slot[k] = if comp.is_empty() {
392                HashMap::new()
393            } else {
394                rebase_to_origin(&comp)
395            };
396            continue;
397        }
398        let cell_size = cell_size_of(&comp, positions);
399        let own: HashSet<usize> = comp.values().copied().collect();
400        let masked: HashSet<usize> = claimed.difference(&own).copied().collect();
401        let recovered = recover_positions_component(&comp, &masked, cell_size, inputs);
402        claimed.extend(recovered.values().copied());
403        recovered_by_slot[k] = rebase_to_origin(&recovered);
404    }
405    // Drop fragments that collapsed to empty after absorption.
406    recovered_by_slot.retain(|m| !m.is_empty());
407    recovered_by_slot
408}
409
410/// Smallest feature index in a labelled map (deterministic tie-break key).
411fn min_index(labelled: &HashMap<(i32, i32), usize>) -> usize {
412    labelled.values().copied().min().unwrap_or(usize::MAX)
413}
414
415/// Number of nearest neighbours pooled per corner for the robust local-pitch
416/// estimate.
417const LOCAL_PITCH_NEIGHBOURS: usize = 5;
418
419/// Per-corner robust local pitch (upper-median of the nearest-neighbour
420/// distances). Tracks perspective foreshortening while tolerating a minority of
421/// off-lattice points sitting closer than the pitch. The topological facade's
422/// synthesized-axis recovery entry uses this to gate per-edge growth against
423/// the local cell scale.
424pub(crate) fn local_pitch_of(positions: &[Point2<f32>]) -> Vec<f32> {
425    use kiddo::{KdTree, SquaredEuclidean};
426    let n = positions.len();
427    if n < 2 {
428        return vec![0.0; n];
429    }
430    let mut tree: KdTree<f32, 2> = KdTree::new();
431    for (i, p) in positions.iter().enumerate() {
432        tree.add(&[p.x, p.y], i as u64);
433    }
434    positions
435        .iter()
436        .enumerate()
437        .map(|(i, p)| {
438            let hits = tree.nearest_n::<SquaredEuclidean>(&[p.x, p.y], LOCAL_PITCH_NEIGHBOURS + 1);
439            let mut dists: Vec<f32> = hits
440                .into_iter()
441                .filter(|nn| nn.item as usize != i)
442                .map(|nn| nn.distance.sqrt())
443                .filter(|d| d.is_finite() && *d > 1e-3)
444                .collect();
445            if dists.is_empty() {
446                return 0.0;
447            }
448            dists.sort_by(|a, b| a.total_cmp(b));
449            dists[dists.len() / 2]
450        })
451        .collect()
452}
453
454/// Mean labelled-pair cardinal edge length for a component (the recovery
455/// schedule's `cell_size`). Mirrors the facade's `estimate_cell_size`.
456fn cell_size_of(labelled: &HashMap<(i32, i32), usize>, positions: &[Point2<f32>]) -> f32 {
457    let mut sum = 0.0_f32;
458    let mut count = 0usize;
459    for (&(i, j), &idx) in labelled {
460        let here = positions[idx];
461        for (di, dj) in [(1, 0), (0, 1), (-1, 0), (0, -1)] {
462            if let Some(&n) = labelled.get(&(i + di, j + dj)) {
463                sum += (positions[n] - here).norm();
464                count += 1;
465            }
466        }
467    }
468    if count == 0 {
469        1.0
470    } else {
471        sum / count as f32
472    }
473}
474
475/// Rebase a labelled component so its bounding-box minimum sits at `(0, 0)`.
476fn rebase_to_origin(labelled: &HashMap<(i32, i32), usize>) -> HashMap<(i32, i32), usize> {
477    let min_i = labelled.keys().map(|&(i, _)| i).min().unwrap_or(0);
478    let min_j = labelled.keys().map(|&(_, j)| j).min().unwrap_or(0);
479    if min_i == 0 && min_j == 0 {
480        return labelled.clone();
481    }
482    labelled
483        .iter()
484        .map(|(&(i, j), &idx)| ((i - min_i, j - min_j), idx))
485        .collect()
486}
487
488/// Run the geometry-only recovery schedule over a labelled `(i, j) → index`
489/// component using the geometry-first [`PositionsAttachPolicy`].
490///
491/// This is the entry the topological facade uses for the synthesized-axis
492/// (`Evidence::Positions` / `Evidence::Oriented1`) path. `features` carries
493/// positions + synthesized axes; `masked` lists corner
494/// indices owned by *other* components (so the recovery can't steal them).
495/// Returns the recovered (NOT yet rebased) labelled map; the caller rebases to
496/// the non-negative `(i, j)` origin.
497pub(crate) fn recover_positions_component(
498    labelled: &HashMap<(i32, i32), usize>,
499    masked: &HashSet<usize>,
500    cell_size: f32,
501    inputs: RecoveryInputs<'_>,
502) -> HashMap<(i32, i32), usize> {
503    use crate::shared::positions_policy::{PositionsAttachPolicy, PositionsTolerances};
504
505    // 50° soft axis tolerance / 0.40 edge band — the position-policy defaults
506    // documented in the facade.
507    let tol = PositionsTolerances {
508        soft_axis_tol_rad: 0.872_664_6,
509        edge_length_tol: 0.40,
510        cell_size,
511    };
512    let inner =
513        PositionsAttachPolicy::new(inputs.features, inputs.positions, inputs.local_pitch, tol);
514    let policy = MaskedPolicy {
515        inner: &inner,
516        masked,
517    };
518    let mut grow = grow_result_from_labelled(labelled, inputs.positions);
519    run_schedule(
520        inputs.positions,
521        &mut grow,
522        cell_size,
523        &policy,
524        inputs.params,
525        inputs.validate_params,
526    );
527    grow.labelled
528}
529
530/// Wrap a [`SquareAttachPolicy`] to additionally mask out corner indices owned
531/// by another component (single-claim across components during recovery).
532struct MaskedPolicy<'a, V: SquareAttachPolicy> {
533    inner: &'a V,
534    masked: &'a HashSet<usize>,
535}
536
537impl<V: SquareAttachPolicy> SquareAttachPolicy for MaskedPolicy<'_, V> {
538    fn is_eligible(&self, idx: usize) -> bool {
539        !self.masked.contains(&idx) && self.inner.is_eligible(idx)
540    }
541    fn required_label_at(&self, i: i32, j: i32) -> Option<u8> {
542        self.inner.required_label_at(i, j)
543    }
544    fn label_of(&self, idx: usize) -> Option<u8> {
545        self.inner.label_of(idx)
546    }
547    fn accept_candidate(
548        &self,
549        idx: usize,
550        at: (i32, i32),
551        prediction: Point2<f32>,
552        neighbours: &[crate::shared::grow::LabelledNeighbour],
553    ) -> crate::shared::grow::Admit {
554        self.inner.accept_candidate(idx, at, prediction, neighbours)
555    }
556    fn edge_ok(&self, c: usize, n: usize, ac: (i32, i32), an: (i32, i32)) -> bool {
557        self.inner.edge_ok(c, n, ac, an)
558    }
559}
560
561/// Reconstruct a [`GrowResult`] from a labelled `(i, j) → index` map for the
562/// recovery schedule. Estimates the axis vectors from the labelled set; the
563/// schedule's internal axis-repair step also defends against a degenerate
564/// estimate.
565pub(crate) fn grow_result_from_labelled(
566    labelled: &HashMap<(i32, i32), usize>,
567    positions: &[Point2<f32>],
568) -> GrowResult {
569    let by_corner: HashMap<usize, (i32, i32)> = labelled.iter().map(|(&k, &v)| (v, k)).collect();
570    let mut grow = GrowResult {
571        labelled: labelled.clone(),
572        by_corner,
573        ..Default::default()
574    };
575    ensure_axes(&mut grow, positions);
576    grow
577}
578
579#[cfg(test)]
580mod tests {
581    use super::*;
582    use crate::shared::grow::{Admit, LabelledNeighbour};
583
584    /// Open policy: every corner eligible, no label constraint, accept all,
585    /// edges within ±40% of the local cell size. Mirrors the geometry-only
586    /// facade policy on a synthetic grid.
587    struct OpenPolicy<'a> {
588        positions: &'a [Point2<f32>],
589        cell_size: f32,
590    }
591
592    impl SquareAttachPolicy for OpenPolicy<'_> {
593        fn is_eligible(&self, _idx: usize) -> bool {
594            true
595        }
596        fn required_label_at(&self, _i: i32, _j: i32) -> Option<u8> {
597            None
598        }
599        fn label_of(&self, _idx: usize) -> Option<u8> {
600            None
601        }
602        fn accept_candidate(
603            &self,
604            _idx: usize,
605            _at: (i32, i32),
606            _prediction: Point2<f32>,
607            _neighbours: &[LabelledNeighbour],
608        ) -> Admit {
609            Admit::Accept
610        }
611        fn edge_ok(&self, c: usize, n: usize, _ac: (i32, i32), _an: (i32, i32)) -> bool {
612            let len = (self.positions[c] - self.positions[n]).norm();
613            let r = len / self.cell_size;
614            (0.6..=1.4).contains(&r)
615        }
616    }
617
618    /// Positions in row-major order plus a `(i, j) → index` map.
619    type SyntheticGrid = (Vec<Point2<f32>>, HashMap<(i32, i32), usize>);
620
621    /// Build an axis-aligned `rows × cols` grid.
622    fn grid(rows: i32, cols: i32, s: f32) -> SyntheticGrid {
623        let mut pos = Vec::new();
624        let mut map = HashMap::new();
625        let mut idx = 0usize;
626        for j in 0..rows {
627            for i in 0..cols {
628                pos.push(Point2::new(i as f32 * s + 40.0, j as f32 * s + 40.0));
629                map.insert((i, j), idx);
630                idx += 1;
631            }
632        }
633        (pos, map)
634    }
635
636    #[test]
637    fn fills_interior_holes_and_extends_boundary() {
638        let s = 30.0_f32;
639        let (pos, full) = grid(7, 7, s);
640        // Seed only the inner 3x3 block; the schedule must extend outward and
641        // fill to recover the full 7x7.
642        let mut seed: HashMap<(i32, i32), usize> = HashMap::new();
643        for j in 2..5 {
644            for i in 2..5 {
645                seed.insert((i, j), full[&(i, j)]);
646            }
647        }
648        let mut grow = grow_result_from_labelled(&seed, &pos);
649        let policy = OpenPolicy {
650            positions: &pos,
651            cell_size: s,
652        };
653        let params = RecoveryParams::default();
654        let vp = ValidationParams::default();
655        let stats = run_schedule(&pos, &mut grow, s, &policy, &params, &vp);
656        assert!(
657            grow.labelled.len() >= 45,
658            "recovered only {}/49 (sweeps {})",
659            grow.labelled.len(),
660            stats.sweeps
661        );
662        // Zero wrong labels: every recovered cell maps to the same index the
663        // ground-truth grid assigned (up to the schedule's rebase, which is
664        // identity here because the seed block sat at the interior).
665        for (&cell, &idx) in &grow.labelled {
666            assert_eq!(
667                full.get(&cell),
668                Some(&idx),
669                "cell {cell:?} mislabelled to index {idx}"
670            );
671        }
672    }
673
674    #[test]
675    fn decoys_off_lattice_are_never_labelled() {
676        let s = 30.0_f32;
677        let (mut pos, full) = grid(6, 6, s);
678        let grid_n = pos.len();
679        // Add off-lattice decoys: points sitting between cells and far away.
680        // None of them sit on an integer lattice node, so a precision-correct
681        // schedule must never attach them.
682        let decoys = [
683            Point2::new(40.0 + 0.5 * s, 40.0 + 0.5 * s), // cell centre
684            Point2::new(40.0 + 2.5 * s, 40.0 + 1.5 * s),
685            Point2::new(40.0 - 3.0 * s, 40.0 + 2.0 * s), // far outside
686            Point2::new(40.0 + 9.0 * s, 40.0 + 9.0 * s),
687        ];
688        for d in decoys {
689            pos.push(d);
690        }
691        // Seed an inner block, recover, and assert no decoy index is labelled.
692        let mut seed: HashMap<(i32, i32), usize> = HashMap::new();
693        for j in 1..4 {
694            for i in 1..4 {
695                seed.insert((i, j), full[&(i, j)]);
696            }
697        }
698        let mut grow = grow_result_from_labelled(&seed, &pos);
699        let policy = OpenPolicy {
700            positions: &pos,
701            cell_size: s,
702        };
703        let stats = run_schedule(
704            &pos,
705            &mut grow,
706            s,
707            &policy,
708            &RecoveryParams::default(),
709            &ValidationParams::default(),
710        );
711        for &(_, idx) in grow
712            .by_corner
713            .iter()
714            .map(|(idx, c)| (c, idx))
715            .collect::<Vec<_>>()
716            .iter()
717        {
718            assert!(
719                *idx < grid_n,
720                "a decoy (index {idx} ≥ {grid_n}) was labelled (sweeps {})",
721                stats.sweeps
722            );
723        }
724        // And the true grid corners carry their true labels.
725        for (&cell, &idx) in &grow.labelled {
726            assert_eq!(full.get(&cell), Some(&idx), "cell {cell:?} mislabelled");
727        }
728    }
729
730    #[test]
731    fn idempotent_on_clean_full_grid() {
732        let s = 30.0_f32;
733        let (pos, full) = grid(5, 5, s);
734        let mut grow = grow_result_from_labelled(&full, &pos);
735        let policy = OpenPolicy {
736            positions: &pos,
737            cell_size: s,
738        };
739        let before = grow.labelled.len();
740        let stats = run_schedule(
741            &pos,
742            &mut grow,
743            s,
744            &policy,
745            &RecoveryParams::default(),
746            &ValidationParams::default(),
747        );
748        assert_eq!(grow.labelled.len(), before, "schedule altered a full grid");
749        assert_eq!(stats.net_added, 0);
750    }
751}