Skip to main content

sampling_planning/roadmaps/
sparse.rs

1//! The sparse roadmap graph shared by SPARS and SPARS2: guards, undirected edges, connected
2//! components and multi-query shortest paths.
3
4use alloc::{collections::BTreeSet, vec::Vec};
5
6use crate::graph::{Arc, shortest_path};
7use crate::{GoalRegion, NearestNeighbors, Path, StateSpace, ValidityChecker};
8
9/// Why a guard was added to a sparse roadmap.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
11pub enum GuardKind {
12    /// The sample saw no guard within the sparse radius (coverage).
13    Coverage,
14    /// The sample saw guards from several connected components (connectivity).
15    Connectivity,
16    /// The sample bridged two neighboring guards that could not see each other (interface).
17    Interface,
18    /// The guard lies on a path added to restore the stretch bound (quality).
19    Quality,
20}
21
22/// Disjoint sets with path halving and union by size; components only ever merge.
23#[derive(Debug, Clone, Default)]
24struct UnionFind {
25    /// The parent of each element; roots point to themselves.
26    parent: Vec<usize>,
27    /// The size of the set rooted at each root.
28    size: Vec<usize>,
29}
30
31impl UnionFind {
32    /// Adds a singleton set and returns its element.
33    fn push(&mut self) -> usize {
34        let id = self.parent.len();
35        self.parent.push(id);
36        self.size.push(1);
37
38        id
39    }
40
41    /// The root of the set containing `x`, halving the path on the way.
42    fn find(&mut self, mut x: usize) -> usize {
43        while self.parent[x] != x {
44            self.parent[x] = self.parent[self.parent[x]];
45            x = self.parent[x];
46        }
47
48        x
49    }
50
51    /// Merges the sets containing `a` and `b`.
52    fn union(&mut self, a: usize, b: usize) {
53        let (mut a, mut b) = (self.find(a), self.find(b));
54
55        if a == b {
56            return;
57        }
58
59        if self.size[a] < self.size[b] {
60            core::mem::swap(&mut a, &mut b);
61        }
62
63        self.parent[b] = a;
64        self.size[a] += self.size[b];
65    }
66}
67
68/// The sparse graph: guard states, undirected edges and connected components.
69#[derive(Debug, Clone)]
70pub(super) struct SparseGraph<S, N> {
71    /// The guard states, by guard id.
72    pub(super) states: Vec<S>,
73    /// Why each guard was added.
74    pub(super) kinds: Vec<GuardKind>,
75    /// The neighbors of each guard, in the order the edges were added.
76    pub(super) adjacency: Vec<Vec<usize>>,
77    /// Every edge once, as `(smaller id, larger id)`.
78    edges: BTreeSet<(usize, usize)>,
79    /// Connected components.
80    components: UnionFind,
81    /// Index over the guard states.
82    pub(super) nn: N,
83}
84
85impl<S: Clone, N> SparseGraph<S, N> {
86    /// An empty graph over the given empty index.
87    pub(super) const fn new(nn: N) -> Self {
88        Self {
89            states: Vec::new(),
90            kinds: Vec::new(),
91            adjacency: Vec::new(),
92            edges: BTreeSet::new(),
93            components: UnionFind {
94                parent: Vec::new(),
95                size: Vec::new(),
96            },
97            nn,
98        }
99    }
100
101    /// The number of guards.
102    pub(super) fn len(&self) -> usize {
103        self.states.len()
104    }
105
106    /// The number of edges.
107    pub(super) fn edge_count(&self) -> usize {
108        self.edges.len()
109    }
110
111    /// Whether `a` and `b` share an edge.
112    pub(super) fn has_edge(&self, a: usize, b: usize) -> bool {
113        self.edges.contains(&(a.min(b), a.max(b)))
114    }
115
116    /// Adds the edge between `a` and `b` unless it exists or `a == b`.
117    pub(super) fn connect(&mut self, a: usize, b: usize) {
118        if a == b || !self.edges.insert((a.min(b), a.max(b))) {
119            return;
120        }
121
122        self.adjacency[a].push(b);
123        self.adjacency[b].push(a);
124        self.components.union(a, b);
125    }
126
127    /// Whether `a` and `b` lie in the same connected component.
128    pub(super) fn same_component(&mut self, a: usize, b: usize) -> bool {
129        self.components.find(a) == self.components.find(b)
130    }
131
132    /// The guards of `visible` that lie in a different component from another one of them,
133    /// in pair order: each pair `(a, b)` with `a` before `b` in different components adds both.
134    /// Empty if all visible guards are connected (OMPL's connectivity links).
135    pub(super) fn connectivity_links(&mut self, visible: &[usize]) -> Vec<usize> {
136        let mut links = Vec::new();
137
138        for (i, &a) in visible.iter().enumerate() {
139            for &b in &visible[i + 1..] {
140                if !self.same_component(a, b) {
141                    links.extend([a, b]);
142                }
143            }
144        }
145
146        links
147    }
148
149    /// Connects the new connectivity guard `guard` to each of `links` that is not yet adjacent
150    /// to it or in its component, so that each component is joined once.
151    pub(super) fn connect_links(&mut self, guard: usize, links: &[usize]) {
152        for &link in links {
153            if !self.has_edge(guard, link) && !self.same_component(link, guard) {
154                self.connect(guard, link);
155            }
156        }
157    }
158
159    /// The interface pair of a sample: its two closest guards `(v1, v2)` when both are visible
160    /// and not adjacent, else `None`. `near` and `visible` come from [`Self::neighborhood`].
161    pub(super) fn interface_pair(
162        &self,
163        near: &[usize],
164        visible: &[usize],
165    ) -> Option<(usize, usize)> {
166        let [v1, v2, ..] = *visible else {
167            return None;
168        };
169
170        (near[..2] == [v1, v2] && !self.has_edge(v1, v2)).then_some((v1, v2))
171    }
172
173    /// The neighbors `r'` of guard `v` other than `r` that are not adjacent to `r` (OMPL's
174    /// `computeVPP`), in edge order.
175    pub(super) fn non_adjacent_neighbors(&self, v: usize, r: usize) -> Vec<usize> {
176        self.adjacency[v]
177            .iter()
178            .copied()
179            .filter(|&other| other != r && !self.has_edge(other, r))
180            .collect()
181    }
182
183    /// Adds a guard and returns its id.
184    pub(super) fn add_guard<Sp>(&mut self, state: S, kind: GuardKind) -> usize
185    where
186        Sp: StateSpace<State = S>,
187        N: NearestNeighbors<Sp>,
188    {
189        let id = self.states.len();
190        self.nn.insert(id, state.clone());
191        self.states.push(state);
192        self.kinds.push(kind);
193        self.adjacency.push(Vec::new());
194        self.components.push();
195
196        id
197    }
198
199    /// The guards within `radius` of `state`, closest first (ties by id).
200    fn near_sorted<Sp>(&self, space: &Sp, state: &S, radius: f64) -> Vec<usize>
201    where
202        Sp: StateSpace<State = S>,
203        N: NearestNeighbors<Sp>,
204    {
205        let mut near = Vec::new();
206        self.nn.within_radius(space, state, radius, &mut near);
207        let distance = |id: usize| space.distance(state, &self.states[id]);
208        near.sort_by(|&a, &b| distance(a).total_cmp(&distance(b)).then(a.cmp(&b)));
209
210        near
211    }
212
213    /// The guards within `radius` of `state`, closest first (ties by id), and the subset that
214    /// `visible` accepts, in the same order.
215    pub(super) fn neighborhood<Sp>(
216        &self,
217        space: &Sp,
218        state: &S,
219        radius: f64,
220        visible: impl Fn(&S) -> bool,
221    ) -> (Vec<usize>, Vec<usize>)
222    where
223        Sp: StateSpace<State = S>,
224        N: NearestNeighbors<Sp>,
225    {
226        let near = self.near_sorted(space, state, radius);
227
228        let visible = near
229            .iter()
230            .copied()
231            .filter(|&id| visible(&self.states[id]))
232            .collect();
233
234        (near, visible)
235    }
236
237    /// The closest guard within `radius` of `state` (ties by id) that `visible` accepts, or
238    /// `None`. Tests visibility closest first and stops at the first accepted guard.
239    pub(super) fn closest_visible<Sp>(
240        &self,
241        space: &Sp,
242        state: &S,
243        radius: f64,
244        visible: impl Fn(&S) -> bool,
245    ) -> Option<usize>
246    where
247        Sp: StateSpace<State = S>,
248        N: NearestNeighbors<Sp>,
249    {
250        let near = self.near_sorted(space, state, radius);
251
252        near.into_iter().find(|&id| visible(&self.states[id]))
253    }
254
255    /// The cheapest path from `start` to `goal` over the graph, connecting both to every
256    /// visible guard within `radius` (and to each other when they are that close), or `None`
257    /// if they are not connected. Motions are checked in travel direction; graph edges were
258    /// checked when they were added.
259    pub(super) fn query<Sp, C>(
260        &self,
261        space: &Sp,
262        checker: &C,
263        start: &S,
264        goal: &GoalRegion<S>,
265        radius: f64,
266    ) -> Option<Path<S>>
267    where
268        Sp: StateSpace<State = S>,
269        C: ValidityChecker<Sp>,
270        N: NearestNeighbors<Sp>,
271    {
272        let n = self.len();
273        let (start_id, center_id) = (n, n + 1);
274        let center = goal.center();
275        let (_, from_start) = self.neighborhood(space, start, radius, |guard| {
276            checker.check_motion(space, start, guard).is_valid()
277        });
278        let mut to_center = alloc::vec![false; n];
279
280        if checker.check_state(center).is_valid() {
281            let mut near = Vec::new();
282            self.nn.within_radius(space, center, radius, &mut near);
283
284            for guard in near {
285                to_center[guard] = checker
286                    .check_motion(space, &self.states[guard], center)
287                    .is_valid();
288            }
289        }
290
291        let direct = space.distance(start, center) <= radius
292            && checker.check_state(center).is_valid()
293            && checker.check_motion(space, start, center).is_valid();
294        let state_of = |id: usize| match id {
295            id if id < n => &self.states[id],
296            id if id == start_id => start,
297            _ => center,
298        };
299
300        let arcs = |node: usize, out: &mut Vec<Arc>| {
301            out.clear();
302            let targets: Vec<usize> = if node == start_id {
303                from_start
304                    .iter()
305                    .copied()
306                    .chain(direct.then_some(center_id))
307                    .collect()
308            } else if node < n {
309                self.adjacency[node]
310                    .iter()
311                    .copied()
312                    .chain(to_center[node].then_some(center_id))
313                    .collect()
314            } else {
315                Vec::new()
316            };
317
318            out.extend(targets.into_iter().map(|to| Arc {
319                to,
320                cost: space.distance(state_of(node), state_of(to)),
321                edge: None,
322            }));
323        };
324        let is_goal = |id: usize| id == center_id || goal.contains(space, state_of(id));
325        let route = shortest_path(n + 2, start_id, is_goal, arcs)?;
326
327        Some(Path {
328            states: route.nodes.iter().map(|&id| state_of(id).clone()).collect(),
329            cost: route.cost,
330        })
331    }
332}
333
334#[cfg(test)]
335mod tests {
336    use super::*;
337
338    #[test]
339    fn union_find_merges_components() {
340        let mut sets = UnionFind::default();
341        let ids: Vec<usize> = (0..5).map(|_| sets.push()).collect();
342
343        sets.union(ids[0], ids[1]);
344        sets.union(ids[3], ids[4]);
345        sets.union(ids[1], ids[4]);
346
347        assert_eq!(sets.find(ids[0]), sets.find(ids[3]));
348        assert_ne!(sets.find(ids[2]), sets.find(ids[0]));
349    }
350}