condor-pathfinding-grid 0.4.0

Grid pathfinding, preprocessing, replanning, and multi-agent algorithms for Condor.
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
//! Prepared-grid sparse subgoal graph over free-space corners.
//!
//! [`SubgoalGraphBuilder`] selects subgoals on a uniform-cost grid; each
//! [`PreparedSubgoalGraph`] query runs abstract A* with lazy BFS edge costs and
//! returns the standard invalid/found/no-path outcome. Empty, oversized, or failed
//! abstractions fall back to online [`AStar`]. Prefer [`AStar`] for the ordinary
//! one-shot route, or [`super::jps_plus::JpsPlusBuilder`] for a durable jump-table lane.

use std::{
    cmp::Ordering,
    collections::{BinaryHeap, HashMap, VecDeque},
};

use crate::{
    AStar, Grid, Path, Pathfinder, Point,
    preprocessed_grid::{
        PreparedGridSearch, PreprocessedGridBuildError, PreprocessedGridBuilder,
        PreprocessedGridMetadata, metadata_for_grid,
    },
    search::{SearchRequest, SearchResult},
};

/// [`PreprocessedGridBuilder`] for sparse corner subgoal graphs.
///
/// Uniform hop cost only (`traversal_cost == 1`). Correctness-first foundation with
/// online A* fallback when the subgoal set is empty, large, or abstract search fails.
/// Prefer as a multi-query experiment baseline, not a large-map acceleration claim.
#[derive(Debug, Clone, Copy, Default)]
pub struct SubgoalGraphBuilder;

impl SubgoalGraphBuilder {
    /// Creates a subgoal-graph builder (no configuration knobs in v0).
    #[must_use]
    pub const fn new() -> Self {
        Self
    }
}

impl PreprocessedGridBuilder for SubgoalGraphBuilder {
    type Map = PreparedSubgoalGraph;

    fn name(&self) -> &'static str {
        "subgoal-graph"
    }

    fn preprocess(&self, grid: &Grid) -> Result<Self::Map, PreprocessedGridBuildError> {
        ensure_uniform_traversal_costs(grid)?;
        let subgoals = select_corner_subgoals(grid);
        Ok(PreparedSubgoalGraph {
            grid: grid.clone(),
            metadata: metadata_for_grid(grid, self.name(), "subgoal-graph-query"),
            subgoals,
        })
    }
}

/// Prepared subgoal graph implementing [`PreparedGridSearch`].
///
/// Sparse corner-subgoal abstract search with online A* fallback; correctness-first,
/// not a performance claim for huge maps. Uniform hop cost only.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PreparedSubgoalGraph {
    grid: Grid,
    metadata: PreprocessedGridMetadata,
    subgoals: Vec<Point>,
}

impl PreparedSubgoalGraph {
    /// Returns a [`SubgoalGraphBuilder`] for preprocess entry.
    #[must_use]
    pub fn builder() -> SubgoalGraphBuilder {
        SubgoalGraphBuilder
    }

    /// Number of corner subgoals retained after preprocess.
    #[must_use]
    pub fn subgoal_count(&self) -> usize {
        self.subgoals.len()
    }
}

impl PreparedGridSearch for PreparedSubgoalGraph {
    fn name(&self) -> &'static str {
        self.metadata.builder_name
    }

    fn grid(&self) -> &Grid {
        &self.grid
    }

    fn metadata(&self) -> &PreprocessedGridMetadata {
        &self.metadata
    }

    fn search(&self, request: SearchRequest) -> SearchResult {
        crate::search::validate_request(&self.grid, request)?;
        // Keep abstract search sparse: too many corners degrades to online A*.
        if request.start == request.goal || self.subgoals.is_empty() || self.subgoals.len() > 64 {
            return AStar.search(&self.grid, request);
        }

        abstract_search(self, request).unwrap_or_else(|| AStar.search(&self.grid, request))
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum AbstractNode {
    Start,
    Goal,
    Subgoal(usize),
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct HeapEntry {
    cost: usize,
    node: AbstractNode,
}

impl Ord for HeapEntry {
    fn cmp(&self, other: &Self) -> Ordering {
        other
            .cost
            .cmp(&self.cost)
            .then_with(|| node_rank(self.node).cmp(&node_rank(other.node)))
    }
}

impl PartialOrd for HeapEntry {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

fn node_rank(node: AbstractNode) -> u8 {
    match node {
        AbstractNode::Start => 0,
        AbstractNode::Goal => 1,
        AbstractNode::Subgoal(_) => 2,
    }
}

fn abstract_search(map: &PreparedSubgoalGraph, request: SearchRequest) -> Option<SearchResult> {
    let mut distances_from: HashMap<Point, HashMap<Point, usize>> = HashMap::new();
    let mut best = HashMap::new();
    let mut parent: HashMap<AbstractNode, AbstractNode> = HashMap::new();
    let mut heap = BinaryHeap::new();

    best.insert(AbstractNode::Start, 0usize);
    heap.push(HeapEntry {
        cost: 0,
        node: AbstractNode::Start,
    });

    let mut visited_nodes = 0usize;
    let watch = crate::search::BudgetWatch::start(request.budget);

    while let Some(HeapEntry { cost, node }) = heap.pop() {
        if best.get(&node).is_some_and(|&known| cost > known) {
            continue;
        }
        visited_nodes += 1;

        if matches!(node, AbstractNode::Goal) {
            let points = reconstruct_path(map, request, &parent)?;
            let path = Path::from_steps(points).ok()?;
            return Some(crate::search::found(path, visited_nodes));
        }

        if let Err(reason) = watch.check(visited_nodes) {
            return Some(Err(crate::search::budget_error(reason)));
        }

        for (next, step_cost) in outgoing_edges(map, node, request, &mut distances_from) {
            let next_cost = cost.saturating_add(step_cost);
            if best.get(&next).is_some_and(|&known| next_cost >= known) {
                continue;
            }
            best.insert(next, next_cost);
            parent.insert(next, node);
            heap.push(HeapEntry {
                cost: next_cost,
                node: next,
            });
        }
    }

    None
}

fn outgoing_edges(
    map: &PreparedSubgoalGraph,
    node: AbstractNode,
    request: SearchRequest,
    distances_from: &mut HashMap<Point, HashMap<Point, usize>>,
) -> Vec<(AbstractNode, usize)> {
    let from = match node_point(map, node, request) {
        Some(point) => point,
        None => return Vec::new(),
    };

    let distances = distances_from
        .entry(from)
        .or_insert_with(|| bfs_distances(&map.grid, from));

    let mut targets: Vec<(AbstractNode, Point)> = Vec::new();
    match node {
        AbstractNode::Start => {
            for (index, &subgoal) in map.subgoals.iter().enumerate() {
                targets.push((AbstractNode::Subgoal(index), subgoal));
            }
            targets.push((AbstractNode::Goal, request.goal));
        }
        AbstractNode::Subgoal(index) => {
            for (j, &subgoal) in map.subgoals.iter().enumerate() {
                if j != index {
                    targets.push((AbstractNode::Subgoal(j), subgoal));
                }
            }
            targets.push((AbstractNode::Goal, request.goal));
        }
        AbstractNode::Goal => return Vec::new(),
    }

    let mut out = Vec::new();
    for (next, to) in targets {
        if let Some(cost) = distances.get(&to).copied() {
            out.push((next, cost));
        }
    }
    out
}

fn reconstruct_path(
    map: &PreparedSubgoalGraph,
    request: SearchRequest,
    parent: &HashMap<AbstractNode, AbstractNode>,
) -> Option<Vec<Point>> {
    let mut chain = vec![AbstractNode::Goal];
    let mut current = AbstractNode::Goal;
    while !matches!(current, AbstractNode::Start) {
        current = *parent.get(&current)?;
        chain.push(current);
    }
    chain.reverse();

    let mut points = Vec::new();
    for window in chain.windows(2) {
        let from = node_point(map, window[0], request)?;
        let to = node_point(map, window[1], request)?;
        let segment = bfs_path(&map.grid, from, to)?;
        if points.is_empty() {
            points = segment;
        } else {
            points.extend(segment.into_iter().skip(1));
        }
    }
    Some(points)
}

fn node_point(
    map: &PreparedSubgoalGraph,
    node: AbstractNode,
    request: SearchRequest,
) -> Option<Point> {
    match node {
        AbstractNode::Start => Some(request.start),
        AbstractNode::Goal => Some(request.goal),
        AbstractNode::Subgoal(index) => map.subgoals.get(index).copied(),
    }
}

/// Walkable cells that sit at free-space corners relative to obstacles.
fn select_corner_subgoals(grid: &Grid) -> Vec<Point> {
    let mut subgoals = Vec::new();
    let width = grid.width();
    let height = grid.height();

    for y in 0..height {
        for x in 0..width {
            let point = Point::new(x, y);
            if grid.is_walkable(point) && is_free_space_corner(grid, point) {
                subgoals.push(point);
            }
        }
    }

    subgoals
}

fn is_free_space_corner(grid: &Grid, point: Point) -> bool {
    // 8-neighbor corner pattern: two consecutive cardinals free and the
    // intervening diagonal blocked (or out of bounds).
    let dirs = [
        (1isize, 0isize),
        (1, 1),
        (0, 1),
        (-1, 1),
        (-1, 0),
        (-1, -1),
        (0, -1),
        (1, -1),
    ];

    for i in (0..8).step_by(2) {
        let (c1x, c1y) = dirs[i];
        let (dx, dy) = dirs[(i + 1) % 8];
        let (c2x, c2y) = dirs[(i + 2) % 8];
        let cardinal_a = offset_point(point, c1x, c1y);
        let diagonal = offset_point(point, dx, dy);
        let cardinal_b = offset_point(point, c2x, c2y);

        if is_free(grid, cardinal_a)
            && is_free(grid, cardinal_b)
            && is_blocked_or_oob(grid, diagonal)
        {
            return true;
        }
    }

    false
}

fn offset_point(point: Point, dx: isize, dy: isize) -> Option<Point> {
    let x = point.x as isize + dx;
    let y = point.y as isize + dy;
    if x < 0 || y < 0 {
        return None;
    }
    Some(Point::new(x as usize, y as usize))
}

fn is_free(grid: &Grid, point: Option<Point>) -> bool {
    point.is_some_and(|p| grid.index_of(p).is_some() && grid.is_walkable(p))
}

fn is_blocked_or_oob(grid: &Grid, point: Option<Point>) -> bool {
    match point {
        None => true,
        Some(p) => grid.index_of(p).is_none() || !grid.is_walkable(p),
    }
}

fn ensure_uniform_traversal_costs(grid: &Grid) -> Result<(), PreprocessedGridBuildError> {
    for y in 0..grid.height() {
        for x in 0..grid.width() {
            let point = Point::new(x, y);
            if let Some(cost) = grid.traversal_cost(point)
                && cost != 1
            {
                return Err(PreprocessedGridBuildError::NonUniformCost {
                    algorithm: "subgoal-graph",
                    point,
                    cost,
                });
            }
        }
    }
    Ok(())
}

fn bfs_distances(grid: &Grid, start: Point) -> HashMap<Point, usize> {
    let mut distances = HashMap::new();
    if !grid.is_walkable(start) {
        return distances;
    }
    let mut queue = VecDeque::from([start]);
    distances.insert(start, 0usize);

    while let Some(current) = queue.pop_front() {
        let current_cost = distances[&current];
        for neighbor in four_neighbors(current) {
            if grid.index_of(neighbor).is_none() || !grid.is_walkable(neighbor) {
                continue;
            }
            if distances.contains_key(&neighbor) {
                continue;
            }
            distances.insert(neighbor, current_cost + 1);
            queue.push_back(neighbor);
        }
    }

    distances
}

fn bfs_path(grid: &Grid, start: Point, goal: Point) -> Option<Vec<Point>> {
    if start == goal {
        return Some(vec![start]);
    }
    if !grid.is_walkable(start) || !grid.is_walkable(goal) {
        return None;
    }

    let mut parent: HashMap<Point, Point> = HashMap::new();
    let mut queue = VecDeque::from([start]);
    parent.insert(start, start);

    while let Some(current) = queue.pop_front() {
        if current == goal {
            break;
        }
        for neighbor in four_neighbors(current) {
            if grid.index_of(neighbor).is_none() || !grid.is_walkable(neighbor) {
                continue;
            }
            if parent.contains_key(&neighbor) {
                continue;
            }
            parent.insert(neighbor, current);
            queue.push_back(neighbor);
        }
    }

    if !parent.contains_key(&goal) {
        return None;
    }

    let mut path = vec![goal];
    let mut cursor = goal;
    while cursor != start {
        cursor = parent[&cursor];
        path.push(cursor);
    }
    path.reverse();
    Some(path)
}

fn four_neighbors(point: Point) -> [Point; 4] {
    [
        Point::new(point.x.wrapping_sub(1), point.y),
        Point::new(point.x + 1, point.y),
        Point::new(point.x, point.y.wrapping_sub(1)),
        Point::new(point.x, point.y + 1),
    ]
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Cell, SearchRequest};

    #[test]
    fn subgoal_graph_matches_astar_on_simple_gap() {
        let mut grid = Grid::new(7, 5).expect("grid");
        for y in 0..5 {
            if y != 2 {
                grid.set_cell(Point::new(3, y), Cell::Blocked)
                    .expect("valid grid edit");
            }
        }

        let prepared = SubgoalGraphBuilder
            .preprocess(&grid)
            .expect("preprocess should succeed");
        let request = SearchRequest::new(Point::new(0, 2), Point::new(6, 2));
        let subgoal = prepared.search(request);
        let exact = AStar.search(&grid, request);

        assert!(subgoal.as_ref().expect("valid search request").is_found());
        assert_eq!(
            subgoal.as_ref().expect("valid search request").cost(),
            exact.as_ref().expect("valid search request").cost()
        );
    }

    #[test]
    fn subgoal_graph_rejects_weighted_grids() {
        let mut grid = Grid::new(4, 3).expect("grid dimensions are valid");
        grid.set_traversal_cost(Point::new(1, 1), 3)
            .expect("cost should be valid");

        let error = SubgoalGraphBuilder
            .preprocess(&grid)
            .expect_err("weighted grid should fail");
        assert!(error.to_string().contains("uniform"));
    }

    #[test]
    fn subgoal_graph_queries_an_immutable_snapshot() {
        let mut grid = Grid::new(5, 1).expect("grid dimensions are valid");
        let request = SearchRequest::new(Point::new(0, 0), Point::new(4, 0));
        let prepared = SubgoalGraphBuilder
            .preprocess(&grid)
            .expect("preprocess should succeed");
        grid.set_cell(Point::new(2, 0), Cell::Blocked)
            .expect("cell should be in bounds");

        let prepared_result = prepared.search(request).expect("valid search request");
        let changed = AStar.search(&grid, request).expect("valid search request");

        assert!(prepared_result.is_found());
        assert_eq!(prepared_result.path().map(|path| path.cost()), Some(4));
        assert!(!changed.is_found());
    }

    #[test]
    fn subgoal_graph_matches_astar_on_a_uniform_obstacle_course() {
        let mut grid = Grid::new(7, 5).expect("grid dimensions are valid");
        for y in 0..5 {
            if y != 2 {
                grid.set_cell(Point::new(3, y), Cell::Blocked)
                    .expect("fixture point is in bounds");
            }
        }
        let request = SearchRequest::new(Point::new(0, 2), Point::new(6, 2));

        let prepared = SubgoalGraphBuilder
            .preprocess(&grid)
            .expect("subgoal preprocessing succeeds");
        let prepared_result = prepared.search(request).expect("request is valid");
        let exact = AStar.search(&grid, request).expect("request is valid");

        assert_eq!(prepared_result.cost(), exact.cost());
        assert_eq!(prepared_result.is_found(), exact.is_found());
        assert!(
            prepared_result
                .path()
                .is_some_and(|path| prepared.grid().path_is_walkable(path.steps()))
        );
    }
}