Skip to main content

sampling_planning/roadmaps/
spars2.rs

1//! SPARS2: sparse roadmap spanners without a dense graph (Dobson and Bekris 2013).
2
3use alloc::{collections::BTreeMap, vec::Vec};
4
5use rand_core::Rng;
6
7use super::{
8    Error,
9    sparse::{GuardKind, SparseGraph},
10};
11use crate::{
12    GoalRegion, LinearScan, NearestNeighbors, Path, Sampler, StateSpace, ValidityChecker, unit_f64,
13};
14
15/// Settings for [`Spars2`]. The defaults follow OMPL's `SPARStwo`.
16#[derive(Debug, Clone, Copy, PartialEq)]
17pub struct Spars2Config {
18    /// `Delta`: the visibility range of a guard. OMPL uses a quarter of the space's extent.
19    /// Positive and finite.
20    pub sparse_delta: f64,
21    /// `delta`: the range in which interface points are sampled around a sample. OMPL uses a
22    /// thousandth of the extent. Positive, finite and below `sparse_delta`.
23    pub dense_delta: f64,
24    /// `t`: the stretch factor the quality criterion enforces. Above one; 3 by default.
25    pub stretch: f64,
26    /// `M`: construction is complete after this many consecutive samples that changed nothing.
27    /// 5000 by default.
28    pub max_failures: usize,
29    /// `k`: the samples drawn near each sample to find neighboring representatives; OMPL uses
30    /// twice the state dimension.
31    pub near_samples: usize,
32    /// Check every sparse edge in both directions, for directional checkers (see
33    /// [`PrmConfig::check_both_directions`](super::PrmConfig::check_both_directions)). Off by
34    /// default.
35    pub check_both_directions: bool,
36}
37
38impl Spars2Config {
39    /// A config with the given visibility and interface ranges, stretch 3, 5000 failures and
40    /// `near_samples` four (twice a planar dimension).
41    #[must_use]
42    pub const fn new(sparse_delta: f64, dense_delta: f64) -> Self {
43        Self {
44            sparse_delta,
45            dense_delta,
46            stretch: 3.0,
47            max_failures: 5000,
48            near_samples: 4,
49            check_both_directions: false,
50        }
51    }
52
53    /// Checks every field against its documented range.
54    fn validate(&self) -> Result<(), Error> {
55        let positive = |value: f64| value.is_finite() && value > 0.0;
56        let valid = positive(self.sparse_delta)
57            && positive(self.dense_delta)
58            && self.dense_delta < self.sparse_delta
59            && self.stretch.is_finite()
60            && self.stretch > 1.0;
61
62        if valid {
63            Ok(())
64        } else {
65            Err(Error::InvalidRadius)
66        }
67    }
68}
69
70/// What a guard knows about one pair of its neighbors `(r, r')`: the closest pair of samples
71/// in its visibility region seen next to each of them.
72#[derive(Debug, Clone)]
73struct InterfaceData<S> {
74    /// `(point, sigma)` on the side of the smaller-id neighbor: `point` lies in this guard's
75    /// region, `sigma` just outside, in the neighbor's.
76    first: Option<(S, S)>,
77    /// The same on the side of the larger-id neighbor.
78    second: Option<(S, S)>,
79}
80
81impl<S> Default for InterfaceData<S> {
82    fn default() -> Self {
83        Self {
84            first: None,
85            second: None,
86        }
87    }
88}
89
90/// One guard's interface data, keyed by neighbor pair `(smaller id, larger id)`.
91type Interfaces<S> = BTreeMap<(usize, usize), InterfaceData<S>>;
92
93/// SPARS2: an incremental sparse roadmap spanner that needs no dense graph (Dobson and Bekris
94/// 2013, "Improving sparse roadmap spanners"), ported from OMPL's `SPARStwo`.
95///
96/// Every valid sample `q` is tested against four criteria, in order, using the guards it can
97/// see within `sparse_delta`:
98///
99/// 1. **Coverage:** it sees no guard, so it becomes a guard.
100/// 2. **Connectivity:** it sees guards of different components, so it becomes a guard joining
101///    them.
102/// 3. **Interface:** its two closest guards are both visible but not adjacent, so they are
103///    connected directly, or through `q`.
104/// 4. **Quality:** `near_samples` states near `q` reveal neighboring guards' regions; the pair
105///    points next to each interface are recorded per guard, and when the graph distance between
106///    two neighbors of a guard exceeds `stretch` times the distance between their interface
107///    points, a shortcut is added: the direct edge if valid, else the path through the points.
108///
109/// Construction ends after `max_failures` consecutive samples change nothing. The roadmap is
110/// then, with high probability, a spanner: paths through it cost at most about `stretch` times
111/// the optimum plus a term in `sparse_delta` (asymptotic near-optimality), with far fewer nodes
112/// than a PRM.
113///
114/// Differences to OMPL's `SPARStwo`, documented here so that results can be compared: the
115/// quality criterion uses OMPL's midpoint estimate `(d(r, v) + d(v, r'')) / 2` for the path
116/// through `v`, as OMPL does (the paper takes a graph shortest path), but adds the path of
117/// interface points without OMPL's smoothing step; the stretch test around a guard stops at the
118/// first violation, even when no shortcut could be added (OMPL finishes the neighbor's inner
119/// loop); any change to the graph resets the failure
120/// counter (OMPL resets it only for new guards and direct interface edges); and sampling near
121/// a state follows the geodesic toward a uniform sample, [`NEAR_ATTEMPTS`] tries at most, instead
122/// of OMPL's unbounded retry.
123///
124/// # Examples
125///
126/// ```
127/// use rand_core::SeedableRng;
128/// use sampling_planning::{
129///     Euclidean, GoalRegion, UniformBox, Validity, ValidityChecker,
130///     roadmaps::{Spars2, Spars2Config},
131/// };
132///
133/// /// Free space everywhere.
134/// struct Free;
135///
136/// impl ValidityChecker<Euclidean<2>> for Free {
137///     fn check_state(&self, _: &[f64; 2]) -> Validity {
138///         Validity::Valid
139///     }
140///
141///     fn check_motion(&self, _: &Euclidean<2>, _: &[f64; 2], _: &[f64; 2]) -> Validity {
142///         Validity::Valid
143///     }
144/// }
145///
146/// let sampler = UniformBox::new([0.0, 0.0], [10.0, 10.0]);
147/// let mut config = Spars2Config::new(2.5, 0.05);
148/// config.max_failures = 500;
149/// let mut spars = Spars2::new(Euclidean::<2>, sampler, Free, config).expect("valid");
150/// spars.construct(100_000, &mut rand_pcg::Pcg64Mcg::seed_from_u64(1));
151///
152/// assert!(spars.is_complete());
153/// let path = spars.query(&[1.0, 1.0], &GoalRegion::new([9.0, 9.0], 0.5)).expect("valid start");
154/// assert!(path.expect("free space").cost < 3.0 * 11.4);
155/// ```
156#[derive(Debug, Clone)]
157pub struct Spars2<Sp: StateSpace, Sa, C, N = LinearScan<<Sp as StateSpace>::State>> {
158    /// The configuration space.
159    space: Sp,
160    /// Draws candidate states.
161    sampler: Sa,
162    /// Decides which states and motions are allowed.
163    checker: C,
164    /// The validated settings.
165    config: Spars2Config,
166    /// The sparse roadmap.
167    graph: SparseGraph<Sp::State, N>,
168    /// Per guard, the interface data of each neighbor pair `(smaller id, larger id)`.
169    interfaces: Vec<Interfaces<Sp::State>>,
170    /// Consecutive samples that changed nothing.
171    failures: usize,
172}
173
174/// The most attempts [`Spars2`] makes to draw one valid state near a sample.
175pub const NEAR_ATTEMPTS: usize = 16;
176
177impl<Sp, Sa, C> Spars2<Sp, Sa, C>
178where
179    Sp: StateSpace,
180    Sa: Sampler<Sp::State>,
181    C: ValidityChecker<Sp>,
182{
183    /// Creates an empty roadmap with a [`LinearScan`] index over its guards.
184    ///
185    /// # Errors
186    ///
187    /// [`Error::InvalidRadius`] if a range is not positive and finite, `dense_delta` is not
188    /// below `sparse_delta`, or the stretch is not above one.
189    pub fn new(space: Sp, sampler: Sa, checker: C, config: Spars2Config) -> Result<Self, Error> {
190        Self::with_nearest_neighbors(space, sampler, checker, config, LinearScan::default())
191    }
192}
193
194impl<Sp, Sa, C, N> Spars2<Sp, Sa, C, N>
195where
196    Sp: StateSpace,
197    Sa: Sampler<Sp::State>,
198    C: ValidityChecker<Sp>,
199    N: NearestNeighbors<Sp>,
200{
201    /// Creates an empty roadmap with the given empty index over its guards.
202    ///
203    /// # Errors
204    ///
205    /// The same as [`Spars2::new`].
206    pub fn with_nearest_neighbors(
207        space: Sp,
208        sampler: Sa,
209        checker: C,
210        config: Spars2Config,
211        nn: N,
212    ) -> Result<Self, Error> {
213        config.validate()?;
214
215        Ok(Self {
216            space,
217            sampler,
218            checker,
219            config,
220            graph: SparseGraph::new(nn),
221            interfaces: Vec::new(),
222            failures: 0,
223        })
224    }
225
226    /// Processes samples until construction is complete or `max_samples` were drawn. Returns
227    /// the number of samples drawn.
228    pub fn construct<R: Rng + ?Sized>(&mut self, max_samples: usize, rng: &mut R) -> usize {
229        let mut drawn = 0;
230
231        while drawn < max_samples && !self.is_complete() {
232            self.step(rng);
233            drawn += 1;
234        }
235
236        drawn
237    }
238
239    /// Draws one sample and applies the four criteria. Returns whether the roadmap changed.
240    pub fn step<R: Rng + ?Sized>(&mut self, rng: &mut R) -> bool {
241        let before = (self.graph.len(), self.graph.edge_count());
242        let q = self.sampler.sample(rng);
243
244        if self.checker.check_state(&q).is_valid() {
245            self.process(q, rng);
246        }
247
248        let changed = before != (self.graph.len(), self.graph.edge_count());
249        self.failures = if changed { 0 } else { self.failures + 1 };
250
251        changed
252    }
253
254    /// Applies the criteria to the valid sample `q`; the quality test runs only if none of the
255    /// other three added anything.
256    fn process<R: Rng + ?Sized>(&mut self, q: Sp::State, rng: &mut R) {
257        let (near, visible) = self.neighborhood(&q);
258
259        if visible.is_empty() {
260            self.add_guard(q, GuardKind::Coverage);
261        } else if !self.check_connectivity(&q, &visible)
262            && !self.check_interface(&q, &near, &visible)
263        {
264            self.check_quality(&q, visible[0], rng);
265        }
266    }
267
268    /// The guards within `sparse_delta` of `state`, closest first, and the visible ones.
269    fn neighborhood(&self, state: &Sp::State) -> (Vec<usize>, Vec<usize>) {
270        self.graph
271            .neighborhood(&self.space, state, self.config.sparse_delta, |guard| {
272                self.is_edge_valid(state, guard)
273            })
274    }
275
276    /// Whether the motion between `a` and `b` checks as valid, both ways if configured.
277    fn is_edge_valid(&self, a: &Sp::State, b: &Sp::State) -> bool {
278        let forward = self.checker.check_motion(&self.space, a, b).is_valid();
279
280        forward
281            && (!self.config.check_both_directions
282                || self.checker.check_motion(&self.space, b, a).is_valid())
283    }
284
285    /// Adds `state` as a guard and forgets the interface data of every guard that can see it,
286    /// since their regions just shrank.
287    fn add_guard(&mut self, state: Sp::State, kind: GuardKind) -> usize {
288        let mut near = Vec::new();
289        self.graph
290            .nn
291            .within_radius(&self.space, &state, self.config.sparse_delta, &mut near);
292
293        for guard in near {
294            self.interfaces[guard].clear();
295        }
296
297        self.interfaces.push(BTreeMap::new());
298
299        self.graph.add_guard(state, kind)
300    }
301
302    /// Connectivity: if `q` sees guards of different components, adds it as a guard joined to
303    /// one guard of each. Returns whether it did.
304    fn check_connectivity(&mut self, q: &Sp::State, visible: &[usize]) -> bool {
305        let links = self.graph.connectivity_links(visible);
306
307        if links.is_empty() {
308            return false;
309        }
310
311        let guard = self.add_guard(q.clone(), GuardKind::Connectivity);
312        self.graph.connect_links(guard, &links);
313
314        true
315    }
316
317    /// Interface: if the two closest guards of `q` are both visible but not adjacent, connects
318    /// them directly or through `q`. Returns whether it did.
319    fn check_interface(&mut self, q: &Sp::State, near: &[usize], visible: &[usize]) -> bool {
320        let Some((v1, v2)) = self.graph.interface_pair(near, visible) else {
321            return false;
322        };
323
324        if self.is_edge_valid(&self.graph.states[v1], &self.graph.states[v2]) {
325            self.graph.connect(v1, v2);
326        } else {
327            let guard = self.add_guard(q.clone(), GuardKind::Interface);
328            self.graph.connect(guard, v1);
329            self.graph.connect(guard, v2);
330        }
331
332        true
333    }
334
335    /// Quality: finds the guards of states near `q` (whose representative is `v`), records the
336    /// interface points they reveal, and tests the stretch bound around `v` and around each of
337    /// them.
338    fn check_quality<R: Rng + ?Sized>(&mut self, q: &Sp::State, v: usize, rng: &mut R) {
339        let Some(representatives) = self.close_representatives(q, v, rng) else {
340            return;
341        };
342
343        for (r, sigma) in &representatives {
344            self.update_pair_points(v, q, *r, sigma);
345            self.update_pair_points(*r, sigma, v, q);
346        }
347
348        self.test_add_path(v);
349        for (r, _) in &representatives {
350            self.test_add_path(*r);
351        }
352    }
353
354    /// Up to `near_samples` states `sigma` near `q` that see a guard other than `v`, one per
355    /// such guard, as `(guard, sigma)`. Returns `None` if a near state sees no guard at all; it
356    /// then became a coverage guard.
357    fn close_representatives<R: Rng + ?Sized>(
358        &mut self,
359        q: &Sp::State,
360        v: usize,
361        rng: &mut R,
362    ) -> Option<Vec<(usize, Sp::State)>> {
363        let mut found: Vec<(usize, Sp::State)> = Vec::new();
364
365        for _ in 0..self.config.near_samples {
366            let Some(sigma) = self.sample_near(q, rng) else {
367                continue;
368            };
369
370            let (_, visible) = self.neighborhood(&sigma);
371            let Some(&representative) = visible.first() else {
372                self.add_guard(sigma, GuardKind::Coverage);
373                return None;
374            };
375
376            if representative != v && found.iter().all(|(r, _)| *r != representative) {
377                found.push((representative, sigma));
378            }
379        }
380
381        Some(found)
382    }
383
384    /// A valid state within `dense_delta` of `q` that `q` can reach: a random fraction of
385    /// `dense_delta` along the geodesic toward a fresh sample. `None` after
386    /// [`NEAR_ATTEMPTS`] failures.
387    fn sample_near<R: Rng + ?Sized>(&mut self, q: &Sp::State, rng: &mut R) -> Option<Sp::State> {
388        for _ in 0..NEAR_ATTEMPTS {
389            let toward = self.sampler.sample(rng);
390            let distance = self.space.distance(q, &toward);
391            let step = self.config.dense_delta * unit_f64(rng);
392
393            if distance <= 0.0 {
394                continue;
395            }
396
397            let sigma = self
398                .space
399                .interpolate(q, &toward, (step / distance).min(1.0));
400
401            if self.space.distance(q, &sigma) <= self.config.dense_delta
402                && self.checker.check_state(&sigma).is_valid()
403                && self.is_edge_valid(q, &sigma)
404            {
405                return Some(sigma);
406            }
407        }
408
409        None
410    }
411
412    /// Records `point` (in the region of guard `v`, next to the region of its neighbor `r`,
413    /// where `sigma` lies) for every pair `(r, r')` of `v`'s neighbors that are not adjacent,
414    /// if it brings the pair's points closer.
415    fn update_pair_points(&mut self, v: usize, point: &Sp::State, r: usize, sigma: &Sp::State) {
416        for r_prime in self.graph.non_adjacent_neighbors(v, r) {
417            self.distance_check(v, point, r, sigma, r_prime);
418        }
419    }
420
421    /// Stores `(point, sigma)` as `v`'s interface point toward `r` for the pair `(r, r')` when
422    /// the slot is empty or the new point is closer to the other side's point (OMPL's
423    /// `distanceCheck`).
424    fn distance_check(
425        &mut self,
426        v: usize,
427        point: &Sp::State,
428        r: usize,
429        sigma: &Sp::State,
430        r_prime: usize,
431    ) {
432        let space = &self.space;
433        let data = self.interfaces[v].entry(pair(r, r_prime)).or_default();
434        let (mine, other) = if r < r_prime {
435            (&mut data.first, &data.second)
436        } else {
437            (&mut data.second, &data.first)
438        };
439
440        let replace = match (&*mine, other) {
441            (None, _) => true,
442            (Some(_), None) => false,
443            (Some((current, _)), Some((opposite, _))) => {
444                space.distance(point, opposite) < space.distance(current, opposite)
445            }
446        };
447
448        if replace {
449            *mine = Some((point.clone(), sigma.clone()));
450        }
451    }
452
453    /// The distance between the two interface points of pair `(r, r')` at guard `v`, or
454    /// infinity while one is missing.
455    fn interface_distance(&self, v: usize, r: usize, r_prime: usize) -> f64 {
456        match self.interfaces[v].get(&pair(r, r_prime)) {
457            Some(InterfaceData {
458                first: Some((a, _)),
459                second: Some((b, _)),
460            }) => self.space.distance(a, b),
461            _ => f64::INFINITY,
462        }
463    }
464
465    /// Whether guard `v` holds the interface point on `r''`'s side of the pair `(r'', x)`.
466    fn has_point_toward(&self, v: usize, r_pp: usize, x: usize) -> bool {
467        self.interfaces[v].get(&pair(r_pp, x)).is_some_and(|data| {
468            if r_pp < x {
469                data.first.is_some()
470            } else {
471                data.second.is_some()
472            }
473        })
474    }
475
476    /// The stretch test around guard `v` (OMPL's `checkAddPath`): for each neighbor `r` and
477    /// each non-adjacent neighbor `r'`, compares the estimated path through `v` with the
478    /// interface distance, and adds a shortcut at the first violation. Returns whether it added
479    /// one.
480    fn test_add_path(&mut self, v: usize) -> bool {
481        let neighbors = self.graph.adjacency[v].clone();
482
483        for r in neighbors {
484            for r_prime in self.graph.non_adjacent_neighbors(v, r) {
485                let through_v = self.longest_path_estimate(v, r, r_prime);
486
487                if through_v > self.config.stretch * self.interface_distance(v, r, r_prime) {
488                    self.add_shortcut(v, r, r_prime);
489                    return true;
490                }
491            }
492        }
493
494        false
495    }
496
497    /// `max over x of (d(r, v) + d(v, x)) / 2`, where `x` is `r'` or a neighbor of `r'` adjacent
498    /// to `v` but not to `r` for which `v` holds an interface point (OMPL's `computeX`).
499    fn longest_path_estimate(&self, v: usize, r: usize, r_prime: usize) -> f64 {
500        let states = &self.graph.states;
501        let to_r = self.space.distance(&states[r], &states[v]);
502
503        self.graph.adjacency[r_prime]
504            .iter()
505            .copied()
506            .filter(|&x| {
507                self.graph.has_edge(x, v)
508                    && !self.graph.has_edge(x, r)
509                    && self.has_point_toward(v, r_prime, x)
510            })
511            .chain([r_prime])
512            .map(|x| f64::midpoint(to_r, self.space.distance(&states[v], &states[x])))
513            .fold(0.0, f64::max)
514    }
515
516    /// Connects `r` and `r'`: directly if that motion is valid, otherwise through the stored
517    /// interface points `sigma_r, point_r, v, point_r', sigma_r'` when every motion along that
518    /// chain is valid.
519    fn add_shortcut(&mut self, v: usize, r: usize, r_prime: usize) {
520        if self.is_edge_valid(&self.graph.states[r], &self.graph.states[r_prime]) {
521            self.graph.connect(r, r_prime);
522            return;
523        }
524
525        let Some(data) = self.interfaces[v].get(&pair(r, r_prime)).cloned() else {
526            return;
527        };
528        let (Some((point_a, sigma_a)), Some((point_b, sigma_b))) = (data.first, data.second) else {
529            return;
530        };
531        let ((point_r, sigma_r), (point_rp, sigma_rp)) = if r < r_prime {
532            ((point_a, sigma_a), (point_b, sigma_b))
533        } else {
534            ((point_b, sigma_b), (point_a, sigma_a))
535        };
536
537        self.add_chain(r, [sigma_r, point_r], v, [point_rp, sigma_rp], r_prime);
538    }
539
540    /// Adds the guards `before` between `r` and `v` and `after` between `v` and `r'`, chained
541    /// by edges, if every motion along `r, before, v, after, r'` checks as valid.
542    fn add_chain(
543        &mut self,
544        r: usize,
545        before: [Sp::State; 2],
546        v: usize,
547        after: [Sp::State; 2],
548        r_prime: usize,
549    ) {
550        let states = &self.graph.states;
551        let chain: Vec<&Sp::State> = [&states[r]]
552            .into_iter()
553            .chain(&before)
554            .chain([&states[v]])
555            .chain(&after)
556            .chain([&states[r_prime]])
557            .collect();
558
559        if !chain
560            .windows(2)
561            .all(|pair| self.is_edge_valid(pair[0], pair[1]))
562        {
563            return;
564        }
565
566        let mut prior = r;
567        for state in before {
568            let guard = self.add_guard(state, GuardKind::Quality);
569            self.graph.connect(prior, guard);
570            prior = guard;
571        }
572
573        self.graph.connect(prior, v);
574        prior = v;
575
576        for state in after {
577            let guard = self.add_guard(state, GuardKind::Quality);
578            self.graph.connect(prior, guard);
579            prior = guard;
580        }
581
582        self.graph.connect(prior, r_prime);
583    }
584
585    /// The cheapest path from `start` to `goal` through the roadmap, or `None` if the roadmap
586    /// does not connect them. Both endpoints connect to every visible guard within
587    /// `sparse_delta`.
588    ///
589    /// # Errors
590    ///
591    /// [`Error::InvalidStart`] if `start` does not check as valid.
592    pub fn query(
593        &self,
594        start: &Sp::State,
595        goal: &GoalRegion<Sp::State>,
596    ) -> Result<Option<Path<Sp::State>>, Error> {
597        let validity = self.checker.check_state(start);
598        if !validity.is_valid() {
599            return Err(Error::InvalidStart(validity));
600        }
601
602        Ok(self.graph.query(
603            &self.space,
604            &self.checker,
605            start,
606            goal,
607            self.config.sparse_delta,
608        ))
609    }
610
611    /// Whether `max_failures` consecutive samples changed nothing.
612    #[must_use]
613    pub const fn is_complete(&self) -> bool {
614        self.failures >= self.config.max_failures
615    }
616
617    /// The number of guards.
618    #[must_use]
619    pub fn node_count(&self) -> usize {
620        self.graph.len()
621    }
622
623    /// The number of roadmap edges.
624    #[must_use]
625    pub fn edge_count(&self) -> usize {
626        self.graph.edge_count()
627    }
628
629    /// The number of guards added for each criterion: coverage, connectivity, interface,
630    /// quality.
631    #[must_use]
632    pub fn guard_counts(&self) -> [usize; 4] {
633        let count = |kind| self.graph.kinds.iter().filter(|&&k| k == kind).count();
634
635        [
636            count(GuardKind::Coverage),
637            count(GuardKind::Connectivity),
638            count(GuardKind::Interface),
639            count(GuardKind::Quality),
640        ]
641    }
642}
643
644/// The interface-data key of the neighbor pair `(a, b)`: `(smaller id, larger id)`.
645fn pair(a: usize, b: usize) -> (usize, usize) {
646    (a.min(b), a.max(b))
647}