sampling_planning/roadmaps/spars.rs
1//! SPARS: sparse roadmap spanners with a dense graph (Dobson and Bekris 2014).
2
3mod dense;
4mod quality;
5
6use alloc::{
7 collections::{BTreeMap, BTreeSet},
8 vec::Vec,
9};
10
11use rand_core::Rng;
12
13use super::{
14 Error,
15 sparse::{GuardKind, SparseGraph},
16};
17use crate::radius::k_constant_lower_bound;
18use crate::{GoalRegion, LinearScan, NearestNeighbors, Path, Sampler, StateSpace, ValidityChecker};
19
20/// Settings for [`Spars`]. The defaults follow OMPL's `SPARS`.
21#[derive(Debug, Clone, Copy, PartialEq)]
22pub struct SparsConfig {
23 /// `Delta`: the visibility range of a guard. OMPL uses a quarter of the space's extent.
24 /// Positive and finite.
25 pub sparse_delta: f64,
26 /// `delta`: two dense nodes closer than this, joined by a dense edge and represented by
27 /// different guards, mark an interface between those guards. OMPL uses a thousandth of
28 /// the extent. Positive, finite and below `sparse_delta`.
29 ///
30 /// The dense graph connects each node to its `k ln n` nearest neighbors, so interfaces
31 /// appear only where dense edges get shorter than `dense_delta`; too small a value starves
32 /// the quality criterion until the dense graph is very large.
33 pub dense_delta: f64,
34 /// `t`: the stretch factor the quality criterion enforces. Above one; 3 by default.
35 pub stretch: f64,
36 /// `M`: construction is complete after this many consecutive valid samples for which all
37 /// four criteria failed. 1000 by default.
38 pub max_failures: usize,
39 /// Check every sparse and dense edge in both directions, for directional checkers (see
40 /// [`PrmConfig::check_both_directions`](super::PrmConfig::check_both_directions)). Off by
41 /// default.
42 pub check_both_directions: bool,
43}
44
45impl SparsConfig {
46 /// A config with the given visibility and interface ranges, stretch 3 and 1000 failures.
47 #[must_use]
48 pub const fn new(sparse_delta: f64, dense_delta: f64) -> Self {
49 Self {
50 sparse_delta,
51 dense_delta,
52 stretch: 3.0,
53 max_failures: 1000,
54 check_both_directions: false,
55 }
56 }
57
58 /// Checks every field against its documented range.
59 fn validate(&self) -> Result<(), Error> {
60 let positive = |value: f64| value.is_finite() && value > 0.0;
61 let valid = positive(self.sparse_delta)
62 && positive(self.dense_delta)
63 && self.dense_delta < self.sparse_delta
64 && self.stretch.is_finite()
65 && self.stretch > 1.0;
66
67 if valid {
68 Ok(())
69 } else {
70 Err(Error::InvalidRadius)
71 }
72 }
73}
74
75/// SPARS: an incremental sparse roadmap spanner that keeps a dense k-nearest PRM* graph next
76/// to the sparse one (Dobson and Bekris 2014, "Sparse roadmap spanners for asymptotically
77/// near-optimal motion planning"), ported from OMPL's `SPARS`.
78///
79/// Every valid sample `q` first joins the dense graph `D`: it connects to its
80/// `ceil(e (1 + 1/d) ln n)` nearest dense nodes by valid motions, and gets a
81/// *representative*, the closest guard (ties by id) it can see within `sparse_delta`. Dense
82/// nodes joined by a dense edge shorter than `dense_delta` but represented by different guards
83/// `v` and `v'` lie on the *interface* of `v` and `v'`; each guard keeps, per other guard, the
84/// list of its dense nodes on that interface. Then `q` is tested against four criteria, in
85/// order, using the guards it can see within `sparse_delta`:
86///
87/// 1. **Coverage:** it sees no guard, so it becomes a guard.
88/// 2. **Connectivity:** it sees guards of different components, so it becomes a guard joining
89/// them.
90/// 3. **Interface:** its two closest guards are both visible but not adjacent, so they are
91/// connected directly, or through `q`.
92/// 4. **Quality:** `q` lies on the interface of its representative `v` with a guard `v'`. For
93/// each neighbor `v''` of `v` not adjacent to `v'`, the estimate `s_max` of the sparse path
94/// from `v'` over `v` toward `v''` is compared with the shortest dense path from `q` to a
95/// dense node on the interface of `v` and `v''`; if `s_max` exceeds `stretch` times its
96/// length, that dense path (extended by one dense node on each side) is added to the sparse
97/// graph as quality guards.
98///
99/// Construction ends after `max_failures` consecutive valid samples fail all four criteria.
100/// The roadmap is then, with high probability, a spanner of the dense graph: paths through it
101/// cost at most about `stretch` times the optimum plus a term in `sparse_delta`, with far
102/// fewer nodes than the dense graph. [`Spars::query`] searches only the sparse graph.
103///
104/// ```mermaid
105/// graph LR
106/// Sample --> Dense["add to D, update representatives"]
107/// Dense --> Coverage
108/// Coverage -->|fails| Connectivity
109/// Connectivity -->|fails| Interface
110/// Interface -->|fails| Quality["quality: interface of q, dense paths"]
111/// Quality -->|fails| Failure["failures += 1"]
112/// ```
113///
114/// The four criteria, their order, the representative and interface-list bookkeeping
115/// (`addMilestone`, `calculateRepresentative`, `updateRepresentatives` over the dense nodes
116/// within `sparse_delta + dense_delta` of each new guard), the loop nesting of `checkAddPath`
117/// and the failure counting (incremented only when all four tests fail, reset by every new
118/// guard, the direct interface edge and the zero-length path case) follow OMPL. Differences to
119/// OMPL's `SPARS`, documented here so that results can be compared:
120///
121/// - OMPL connects the first state of an added quality path to `v''` and the last to `v'`
122/// (it passes them swapped to `addPathToSpanner`); here the first, which `v'` represents,
123/// connects to `v'` and the last to `v''`.
124/// - When `q` itself lies on the interface of `v` and `v''`, OMPL pushes `q` in front of the
125/// previous best dense path instead of replacing it; here the dense path is just `q`.
126/// - OMPL throws when a dense node has no interface neighbor with the expected representative
127/// (possible when the best dense path ends on another `v''` interface, or when interface
128/// lists went stale); here that violation is skipped and the search goes on.
129/// - Every sparse edge of a quality path is checked before anything is added, and the path is
130/// skipped if one is invalid; OMPL adds them unchecked.
131/// - OMPL's randomized `reduceVertices` is replaced by the deterministic greedy
132/// [`shortcut`](crate::shortcut()).
133/// - Dense paths come from Dijkstra (ties by id) instead of A*; their lengths agree.
134/// - A dense node without a visible guard has no representative (OMPL leaves an unset value);
135/// it is kept out of interface lists until a guard covers it, which the coverage criterion
136/// does in the same step.
137/// - Start and goal are not added as guards: [`Spars::query`] connects them to visible guards,
138/// so one roadmap answers many queries.
139/// - Invalid samples are drawn and dropped without counting as failures, as OMPL's valid-state
140/// sampler retries until it finds a valid state.
141///
142/// Like OMPL's, the quality test estimates the sparse path through `v` from guard distances
143/// alone (`s_max`), so an added path never makes the violation it repairs disappear; only the
144/// new guards taking over dense nodes do. Once many dense edges undercut `dense_delta`, every
145/// new quality path creates further violations and construction may not finish in practice,
146/// even at the default stretch 3 (on a 10 x 10 world with `sparse_delta` 2, from
147/// `dense_delta` of about 0.085 on; at stretch 1.2 already from about 0.06). Keep
148/// `dense_delta` small, as OMPL does, and bound [`Spars::construct`] by `max_samples`.
149///
150/// # Examples
151///
152/// ```
153/// use rand_core::SeedableRng;
154/// use sampling_planning::{
155/// Euclidean, GoalRegion, UniformBox, Validity, ValidityChecker,
156/// roadmaps::{Spars, SparsConfig},
157/// };
158///
159/// /// Free space everywhere.
160/// struct Free;
161///
162/// impl ValidityChecker<Euclidean<2>> for Free {
163/// fn check_state(&self, _: &[f64; 2]) -> Validity {
164/// Validity::Valid
165/// }
166///
167/// fn check_motion(&self, _: &Euclidean<2>, _: &[f64; 2], _: &[f64; 2]) -> Validity {
168/// Validity::Valid
169/// }
170/// }
171///
172/// let sampler = UniformBox::new([0.0, 0.0], [10.0, 10.0]);
173/// let mut config = SparsConfig::new(2.5, 0.05);
174/// config.max_failures = 200;
175/// let mut spars = Spars::new(Euclidean::<2>, sampler, Free, config).expect("valid");
176/// spars.construct(100_000, &mut rand_pcg::Pcg64Mcg::seed_from_u64(1));
177///
178/// assert!(spars.is_complete());
179/// assert!(spars.node_count() < spars.dense_node_count());
180/// let path = spars.query(&[1.0, 1.0], &GoalRegion::new([9.0, 9.0], 0.5)).expect("valid start");
181/// assert!(path.expect("free space").cost < 3.0 * 11.4);
182/// ```
183#[derive(Debug, Clone)]
184pub struct Spars<Sp: StateSpace, Sa, C, N = LinearScan<<Sp as StateSpace>::State>> {
185 /// The configuration space.
186 space: Sp,
187 /// Draws candidate states.
188 sampler: Sa,
189 /// Decides which states and motions are allowed.
190 checker: C,
191 /// The validated settings.
192 config: SparsConfig,
193 /// The k-nearest PRM* constant `e (1 + 1/d)` of the dense graph.
194 k_constant: f64,
195 /// The sparse roadmap.
196 graph: SparseGraph<Sp::State, N>,
197 /// The dense node states, by dense id. All checked as valid.
198 dense_states: Vec<Sp::State>,
199 /// The neighbors of each dense node, in the order the edges were added.
200 dense_adjacency: Vec<Vec<usize>>,
201 /// Index over the dense nodes.
202 dense_nn: N,
203 /// The representative guard of each dense node; `None` until a guard is visible from it.
204 representatives: Vec<Option<usize>>,
205 /// Per guard `v`, per other guard `v'`: the dense nodes represented by `v` that have a
206 /// dense neighbor closer than `dense_delta` represented by `v'`.
207 interface_lists: Vec<BTreeMap<usize, BTreeSet<usize>>>,
208 /// Per guard, the dense nodes it represents that lie on no interface.
209 non_interface_lists: Vec<BTreeSet<usize>>,
210 /// Consecutive valid samples for which all four criteria failed.
211 failures: usize,
212}
213
214impl<Sp, Sa, C> Spars<Sp, Sa, C>
215where
216 Sp: StateSpace,
217 Sa: Sampler<Sp::State>,
218 C: ValidityChecker<Sp>,
219{
220 /// Creates an empty roadmap with [`LinearScan`] indices over its guards and dense nodes.
221 ///
222 /// # Errors
223 ///
224 /// [`Error::InvalidRadius`] if a range is not positive and finite, `dense_delta` is not
225 /// below `sparse_delta`, or the stretch is not above one.
226 pub fn new(space: Sp, sampler: Sa, checker: C, config: SparsConfig) -> Result<Self, Error> {
227 Self::with_nearest_neighbors(space, sampler, checker, config, LinearScan::default())
228 }
229}
230
231impl<Sp, Sa, C, N> Spars<Sp, Sa, C, N>
232where
233 Sp: StateSpace,
234 Sa: Sampler<Sp::State>,
235 C: ValidityChecker<Sp>,
236 N: NearestNeighbors<Sp> + Clone,
237{
238 /// Creates an empty roadmap with the given empty index; a clone of it indexes the dense
239 /// nodes, the original the guards.
240 ///
241 /// # Errors
242 ///
243 /// The same as [`Spars::new`].
244 pub fn with_nearest_neighbors(
245 space: Sp,
246 sampler: Sa,
247 checker: C,
248 config: SparsConfig,
249 nn: N,
250 ) -> Result<Self, Error> {
251 config.validate()?;
252 let k_constant = k_constant_lower_bound(space.dimension());
253
254 Ok(Self {
255 space,
256 sampler,
257 checker,
258 config,
259 k_constant,
260 graph: SparseGraph::new(nn.clone()),
261 dense_states: Vec::new(),
262 dense_adjacency: Vec::new(),
263 dense_nn: nn,
264 representatives: Vec::new(),
265 interface_lists: Vec::new(),
266 non_interface_lists: Vec::new(),
267 failures: 0,
268 })
269 }
270}
271
272impl<Sp, Sa, C, N> Spars<Sp, Sa, C, N>
273where
274 Sp: StateSpace,
275 Sa: Sampler<Sp::State>,
276 C: ValidityChecker<Sp>,
277 N: NearestNeighbors<Sp>,
278{
279 /// Processes samples until construction is complete or `max_samples` were drawn, valid or
280 /// not. Returns the number of samples drawn.
281 pub fn construct<R: Rng + ?Sized>(&mut self, max_samples: usize, rng: &mut R) -> usize {
282 let mut drawn = 0;
283
284 while drawn < max_samples && !self.is_complete() {
285 self.step(rng);
286 drawn += 1;
287 }
288
289 drawn
290 }
291
292 /// Draws one sample; if it is valid, adds it to the dense graph and applies the four
293 /// criteria. Returns whether the sparse roadmap changed.
294 pub fn step<R: Rng + ?Sized>(&mut self, rng: &mut R) -> bool {
295 let state = self.sampler.sample(rng);
296
297 if !self.checker.check_state(&state).is_valid() {
298 return false;
299 }
300
301 let before = (self.graph.len(), self.graph.edge_count());
302 let q = self.add_milestone(state);
303
304 if !self.process(q) {
305 self.failures += 1;
306 }
307
308 before != (self.graph.len(), self.graph.edge_count())
309 }
310}
311
312impl<Sp, Sa, C, N> Spars<Sp, Sa, C, N>
313where
314 Sp: StateSpace,
315 C: ValidityChecker<Sp>,
316 N: NearestNeighbors<Sp>,
317{
318 /// Applies the four criteria, in order, to the new dense node `q` (OMPL's
319 /// `constructRoadmap` body). Returns whether one of them succeeded.
320 fn process(&mut self, q: usize) -> bool {
321 let state = self.dense_states[q].clone();
322 let (near, visible) = self.neighborhood(&state);
323
324 if visible.is_empty() {
325 self.add_guard(state, GuardKind::Coverage);
326 return true;
327 }
328
329 if self.check_connectivity(&state, &visible) || self.check_interface(q, &near, &visible) {
330 return true;
331 }
332
333 let interface = self.interface_neighborhood(q);
334
335 !interface.is_empty() && self.check_add_path(q, &interface)
336 }
337
338 /// The guards within `sparse_delta` of `state`, closest first (ties by id), and the ones
339 /// visible from `state`.
340 fn neighborhood(&self, state: &Sp::State) -> (Vec<usize>, Vec<usize>) {
341 self.graph
342 .neighborhood(&self.space, state, self.config.sparse_delta, |guard| {
343 self.is_edge_valid(state, guard)
344 })
345 }
346
347 /// Whether the motion between `a` and `b` checks as valid, both ways if configured.
348 fn is_edge_valid(&self, a: &Sp::State, b: &Sp::State) -> bool {
349 let forward = self.checker.check_motion(&self.space, a, b).is_valid();
350
351 forward
352 && (!self.config.check_both_directions
353 || self.checker.check_motion(&self.space, b, a).is_valid())
354 }
355
356 /// Whether the motion between guards `a` and `b` checks as valid.
357 fn is_guard_edge_valid(&self, a: usize, b: usize) -> bool {
358 self.is_edge_valid(&self.graph.states[a], &self.graph.states[b])
359 }
360
361 /// Adds `state` as a guard, re-assigns the representatives of the dense nodes it may now
362 /// represent, and resets the failure counter (OMPL's `addGuard`).
363 fn add_guard(&mut self, state: Sp::State, kind: GuardKind) -> usize {
364 let guard = self.graph.add_guard(state, kind);
365 self.interface_lists.push(BTreeMap::new());
366 self.non_interface_lists.push(BTreeSet::new());
367 self.update_representatives(guard);
368 self.failures = 0;
369
370 guard
371 }
372
373 /// Connectivity: if `state` sees guards of different components, adds it as a guard
374 /// joined to one guard of each. Returns whether it did.
375 fn check_connectivity(&mut self, state: &Sp::State, visible: &[usize]) -> bool {
376 let links = self.graph.connectivity_links(visible);
377
378 if links.is_empty() {
379 return false;
380 }
381
382 let guard = self.add_guard(state.clone(), GuardKind::Connectivity);
383 self.graph.connect_links(guard, &links);
384
385 true
386 }
387
388 /// Interface: if the two closest guards of dense node `q` are both visible but not
389 /// adjacent, connects them directly (resetting the failure counter) or through `q`.
390 /// Returns whether it did.
391 fn check_interface(&mut self, q: usize, near: &[usize], visible: &[usize]) -> bool {
392 let Some((v1, v2)) = self.graph.interface_pair(near, visible) else {
393 return false;
394 };
395
396 if self.is_guard_edge_valid(v1, v2) {
397 self.graph.connect(v1, v2);
398 self.failures = 0;
399 } else {
400 let guard = self.add_guard(self.dense_states[q].clone(), GuardKind::Interface);
401 self.graph.connect(guard, v1);
402 self.graph.connect(guard, v2);
403 }
404
405 true
406 }
407
408 /// The cheapest path from `start` to `goal` through the sparse roadmap, or `None` if the
409 /// roadmap does not connect them. Both endpoints connect to every visible guard within
410 /// `sparse_delta`; the dense graph is not searched.
411 ///
412 /// # Errors
413 ///
414 /// [`Error::InvalidStart`] if `start` does not check as valid.
415 pub fn query(
416 &self,
417 start: &Sp::State,
418 goal: &GoalRegion<Sp::State>,
419 ) -> Result<Option<Path<Sp::State>>, Error> {
420 let validity = self.checker.check_state(start);
421 if !validity.is_valid() {
422 return Err(Error::InvalidStart(validity));
423 }
424
425 Ok(self.graph.query(
426 &self.space,
427 &self.checker,
428 start,
429 goal,
430 self.config.sparse_delta,
431 ))
432 }
433
434 /// Whether `max_failures` consecutive valid samples failed all four criteria.
435 #[must_use]
436 pub const fn is_complete(&self) -> bool {
437 self.failures >= self.config.max_failures
438 }
439
440 /// The number of guards (sparse nodes).
441 #[must_use]
442 pub fn node_count(&self) -> usize {
443 self.graph.len()
444 }
445
446 /// The number of dense nodes: every valid sample drawn so far.
447 #[must_use]
448 pub fn dense_node_count(&self) -> usize {
449 self.dense_states.len()
450 }
451
452 /// The number of sparse roadmap edges.
453 #[must_use]
454 pub fn edge_count(&self) -> usize {
455 self.graph.edge_count()
456 }
457
458 /// The number of guards added for each criterion: coverage, connectivity, interface,
459 /// quality.
460 #[must_use]
461 pub fn guard_counts(&self) -> [usize; 4] {
462 let count = |kind| self.graph.kinds.iter().filter(|&&k| k == kind).count();
463
464 [
465 count(GuardKind::Coverage),
466 count(GuardKind::Connectivity),
467 count(GuardKind::Interface),
468 count(GuardKind::Quality),
469 ]
470 }
471}
472
473#[cfg(test)]
474mod tests {
475 use rand_core::SeedableRng;
476
477 use super::*;
478 use crate::{Euclidean, KdTree, UniformBox, Validity, discretized_motion};
479
480 /// A wall at `x` in `[4, 6]` for `y < 7` in a 10 x 10 box.
481 struct Wall;
482
483 impl ValidityChecker<Euclidean<2>> for Wall {
484 fn check_state(&self, s: &[f64; 2]) -> Validity {
485 if (4.0..=6.0).contains(&s[0]) && s[1] < 7.0 {
486 Validity::Invalid
487 } else {
488 Validity::Valid
489 }
490 }
491
492 fn check_motion(&self, space: &Euclidean<2>, from: &[f64; 2], to: &[f64; 2]) -> Validity {
493 discretized_motion(space, from, to, 0.02, |s| self.check_state(s))
494 }
495 }
496
497 /// A SPARS roadmap over the wall world with the given interface range, after at most
498 /// `max_samples` samples with a fixed seed.
499 fn roadmap(
500 dense_delta: f64,
501 max_samples: usize,
502 ) -> Spars<Euclidean<2>, UniformBox<2>, Wall, KdTree<2>> {
503 let config = SparsConfig::new(2.0, dense_delta);
504 let sampler = UniformBox::new([0.0, 0.0], [10.0, 10.0]);
505 let mut spars =
506 Spars::with_nearest_neighbors(Euclidean::<2>, sampler, Wall, config, KdTree::default())
507 .expect("valid");
508 spars.construct(max_samples, &mut rand_pcg::Pcg64Mcg::seed_from_u64(3));
509
510 spars
511 }
512
513 /// The two fixtures: one constructed to completion, and one cut short whose wide interface
514 /// range made the quality criterion add paths.
515 fn fixtures() -> [Spars<Euclidean<2>, UniformBox<2>, Wall, KdTree<2>>; 2] {
516 let complete = roadmap(0.05, 20_000);
517 let with_quality = roadmap(0.25, 1500);
518 assert!(complete.is_complete());
519 assert!(
520 with_quality.guard_counts()[3] > 0,
521 "{:?}",
522 with_quality.guard_counts()
523 );
524
525 [complete, with_quality]
526 }
527
528 /// Asserts that every dense node of `spars` is represented by a guard it sees within
529 /// `sparse_delta`.
530 fn assert_represented(spars: &Spars<Euclidean<2>, UniformBox<2>, Wall, KdTree<2>>) {
531 for (q, state) in spars.dense_states.iter().enumerate() {
532 let rep = spars.representatives[q].expect("every dense node is covered");
533 let guard = &spars.graph.states[rep];
534
535 assert!(spars.space.distance(state, guard) <= spars.config.sparse_delta);
536 assert!(
537 spars.is_edge_valid(state, guard),
538 "node {q} cannot see {rep}"
539 );
540 }
541 }
542
543 /// Asserts that every listed dense node of `spars` is listed under its representative,
544 /// and that both kinds of list are in use.
545 fn assert_listed_under_representative(
546 spars: &Spars<Euclidean<2>, UniformBox<2>, Wall, KdTree<2>>,
547 ) {
548 for (guard, lists) in spars.interface_lists.iter().enumerate() {
549 let listed = lists.values().flatten();
550
551 for &q in listed.chain(&spars.non_interface_lists[guard]) {
552 assert_eq!(spars.representatives[q], Some(guard), "node {q}");
553 }
554 }
555
556 let listed: usize = spars.non_interface_lists.iter().map(BTreeSet::len).sum();
557 let on_interfaces = spars
558 .interface_lists
559 .iter()
560 .any(|lists| lists.values().any(|list| !list.is_empty()));
561 assert!(listed > 0 && on_interfaces && spars.guard_counts()[0] > 0);
562 }
563
564 #[test]
565 fn every_dense_node_is_represented_by_a_visible_guard_within_range() {
566 for spars in fixtures() {
567 assert_represented(&spars);
568 }
569 }
570
571 #[test]
572 fn dense_nodes_are_listed_only_under_their_representative() {
573 for spars in fixtures() {
574 assert_listed_under_representative(&spars);
575 }
576 }
577}