sampling_planning/roadmaps/
sparse.rs1use alloc::{collections::BTreeSet, vec::Vec};
5
6use crate::graph::{Arc, shortest_path};
7use crate::{GoalRegion, NearestNeighbors, Path, StateSpace, ValidityChecker};
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
11pub enum GuardKind {
12 Coverage,
14 Connectivity,
16 Interface,
18 Quality,
20}
21
22#[derive(Debug, Clone, Default)]
24struct UnionFind {
25 parent: Vec<usize>,
27 size: Vec<usize>,
29}
30
31impl UnionFind {
32 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 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 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#[derive(Debug, Clone)]
70pub(super) struct SparseGraph<S, N> {
71 pub(super) states: Vec<S>,
73 pub(super) kinds: Vec<GuardKind>,
75 pub(super) adjacency: Vec<Vec<usize>>,
77 edges: BTreeSet<(usize, usize)>,
79 components: UnionFind,
81 pub(super) nn: N,
83}
84
85impl<S: Clone, N> SparseGraph<S, N> {
86 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 pub(super) fn len(&self) -> usize {
103 self.states.len()
104 }
105
106 pub(super) fn edge_count(&self) -> usize {
108 self.edges.len()
109 }
110
111 pub(super) fn has_edge(&self, a: usize, b: usize) -> bool {
113 self.edges.contains(&(a.min(b), a.max(b)))
114 }
115
116 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 pub(super) fn same_component(&mut self, a: usize, b: usize) -> bool {
129 self.components.find(a) == self.components.find(b)
130 }
131
132 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 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 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 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 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 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 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 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 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}