Skip to main content

sampling_planning/roadmaps/
prm.rs

1//! PRM, PRM* and lazy PRM: multi-query probabilistic roadmaps.
2
3use alloc::vec::Vec;
4
5use rand_core::Rng;
6
7use super::Error;
8use crate::graph::{Arc, Route, shortest_path};
9use crate::radius::{
10    dimension_f64, k_constant_lower_bound, k_nearest_count, shrinking_radius, unit_ball_volume,
11};
12use crate::{GoalRegion, LinearScan, NearestNeighbors, Path, Sampler, StateSpace, ValidityChecker};
13
14/// How a new roadmap node picks the nodes it tries to connect to.
15#[derive(Debug, Clone, Copy, PartialEq)]
16pub enum Connection {
17    /// Classic PRM: every node within this fixed radius. Positive and finite.
18    Radius(f64),
19    /// PRM* (Karaman and Frazzoli 2011): every node within `gamma * (ln n / n)^(1/d)`, with `n`
20    /// counting the new node. Asymptotic optimality needs `gamma` above
21    /// [`PrmConfig::gamma_lower_bound`]. Positive and finite.
22    Star {
23        /// The radius constant.
24        gamma: f64,
25    },
26    /// k-nearest PRM: the `k` nearest nodes. At least one.
27    KNearest(usize),
28    /// k-nearest PRM* (Karaman and Frazzoli 2011): the `ceil(k_constant * ln n)` nearest
29    /// nodes, with `n` counting the new node. Asymptotic optimality needs `k_constant` above
30    /// [`PrmConfig::k_constant_lower_bound`]. Positive and finite.
31    StarK {
32        /// The neighbor count constant.
33        k_constant: f64,
34    },
35}
36
37/// Which nodes a state connects to, as resolved for one roadmap size.
38#[derive(Debug, Clone, Copy, PartialEq)]
39enum Neighborhood {
40    /// Every node within this radius.
41    Radius(f64),
42    /// The `k` nearest nodes.
43    Nearest(usize),
44}
45
46/// Settings for [`Prm`].
47#[derive(Debug, Clone, Copy, PartialEq)]
48pub struct PrmConfig {
49    /// The neighbor rule for new nodes and for query endpoints.
50    ///
51    /// k-nearest rules connect a new node to its `k` nearest older nodes; an older node gains
52    /// edges only when it is among the `k` nearest of a newer one, so degrees differ.
53    pub connection: Connection,
54    /// Lazy PRM (Bohlin and Kavraki 2000): store edges unchecked and check only the edges of
55    /// candidate shortest paths at query time, dropping invalid ones and searching again.
56    ///
57    /// Nodes are still state-checked when they are added. Off by default.
58    pub lazy: bool,
59    /// Check every roadmap edge in both directions.
60    ///
61    /// Roadmap edges are traveled both ways, but checked once, from the older to the newer node.
62    /// That is sound only for a symmetric [`ValidityChecker::check_motion`]; switch this on for
63    /// directional checkers (reachable sets, one-way constraints). Query edges from the start
64    /// and to the goal are always checked in travel direction only. Off by default.
65    pub check_both_directions: bool,
66}
67
68impl PrmConfig {
69    /// Classic PRM with a fixed connection radius, eager checks.
70    #[must_use]
71    pub const fn fixed(radius: f64) -> Self {
72        Self {
73            connection: Connection::Radius(radius),
74            lazy: false,
75            check_both_directions: false,
76        }
77    }
78
79    /// PRM* with the radius constant `gamma`, eager checks.
80    #[must_use]
81    pub const fn star(gamma: f64) -> Self {
82        Self {
83            connection: Connection::Star { gamma },
84            lazy: false,
85            check_both_directions: false,
86        }
87    }
88
89    /// This config with lazy edge checking.
90    #[must_use]
91    pub const fn lazy(self) -> Self {
92        Self { lazy: true, ..self }
93    }
94
95    /// k-nearest PRM* with the neighbor count constant `k_constant`, eager checks.
96    #[must_use]
97    pub const fn star_k(k_constant: f64) -> Self {
98        Self {
99            connection: Connection::StarK { k_constant },
100            lazy: false,
101            check_both_directions: false,
102        }
103    }
104
105    /// The smallest k-nearest constant for which k-nearest PRM* is asymptotically optimal
106    /// (Karaman and Frazzoli 2011, Theorem 35): `e (1 + 1/d)`.
107    #[must_use]
108    pub fn k_constant_lower_bound(dimension: usize) -> f64 {
109        k_constant_lower_bound(dimension)
110    }
111
112    /// The smallest `gamma` for which PRM* is asymptotically optimal (Karaman and Frazzoli
113    /// 2011, Theorem 34): `2 (1 + 1/d)^(1/d) (free_volume / zeta_d)^(1/d)`, where `zeta_d` is the
114    /// volume of the unit `d`-ball.
115    ///
116    /// `free_volume` is the Lebesgue measure of the obstacle-free space; the volume of the
117    /// sampling box is a safe over-estimate. Pick `gamma` somewhat above this value.
118    #[must_use]
119    pub fn gamma_lower_bound(dimension: usize, free_volume: f64) -> f64 {
120        let d = dimension_f64(dimension);
121
122        2.0 * libm::pow(1.0 + 1.0 / d, 1.0 / d)
123            * libm::pow(free_volume / unit_ball_volume(d), 1.0 / d)
124    }
125}
126
127/// Whether a roadmap edge has been collision-checked.
128#[derive(Debug, Clone, Copy, PartialEq, Eq)]
129enum EdgeStatus {
130    /// Checked and valid.
131    Valid,
132    /// Checked and invalid (or unknown); never traveled. Only lazy roadmaps keep such edges.
133    Invalid,
134    /// Not checked yet; only in lazy roadmaps.
135    Unchecked,
136}
137
138/// An undirected roadmap edge.
139#[derive(Debug, Clone)]
140struct Edge {
141    /// The older endpoint.
142    a: usize,
143    /// The newer endpoint.
144    b: usize,
145    /// The edge length under [`StateSpace::distance`].
146    cost: f64,
147    /// Whether the edge was checked, and how.
148    status: EdgeStatus,
149}
150
151/// A probabilistic roadmap: a graph of valid sampled states connected by valid motions, built
152/// once and queried for many start and goal pairs.
153///
154/// [`Prm::grow`] adds samples, [`Prm::query`] connects a start and a goal region to the roadmap
155/// and runs Dijkstra. Queries do not change the roadmap, except that a lazy roadmap remembers
156/// which edges it has checked. With [`Connection::Star`] the roadmap is PRM*, whose query cost
157/// converges to the optimum as it grows.
158///
159/// PRM needs no [`Steering`](crate::Steering): edges are direct motions along
160/// [`StateSpace::interpolate`].
161///
162/// # Examples
163///
164/// ```
165/// use rand_core::SeedableRng;
166/// use sampling_planning::{
167///     Euclidean, GoalRegion, UniformBox, Validity, ValidityChecker,
168///     roadmaps::{Prm, PrmConfig},
169/// };
170///
171/// /// Free space everywhere.
172/// struct Free;
173///
174/// impl ValidityChecker<Euclidean<2>> for Free {
175///     fn check_state(&self, _: &[f64; 2]) -> Validity {
176///         Validity::Valid
177///     }
178///
179///     fn check_motion(&self, _: &Euclidean<2>, _: &[f64; 2], _: &[f64; 2]) -> Validity {
180///         Validity::Valid
181///     }
182/// }
183///
184/// let sampler = UniformBox::new([0.0, 0.0], [10.0, 10.0]);
185/// let gamma = 1.5 * PrmConfig::gamma_lower_bound(2, 100.0);
186/// let mut prm = Prm::new(Euclidean::<2>, sampler, Free, PrmConfig::star(gamma)).expect("valid");
187/// prm.grow(500, &mut rand_pcg::Pcg64Mcg::seed_from_u64(1));
188///
189/// // The same roadmap answers several queries.
190/// for goal in [[9.0, 9.0], [9.0, 1.0]] {
191///     let path = prm.query(&[1.0, 1.0], &GoalRegion::new(goal, 0.5)).expect("valid start");
192///     assert!(path.is_some());
193/// }
194/// ```
195#[derive(Debug, Clone)]
196pub struct Prm<Sp: StateSpace, Sa, C, N = LinearScan<<Sp as StateSpace>::State>> {
197    /// The configuration space.
198    space: Sp,
199    /// Draws candidate roadmap states.
200    sampler: Sa,
201    /// Decides which states and motions are allowed.
202    checker: C,
203    /// The settings.
204    config: PrmConfig,
205    /// The roadmap states, indexed by node id. All checked as valid.
206    states: Vec<Sp::State>,
207    /// All edges, including checked-invalid ones in lazy roadmaps.
208    edges: Vec<Edge>,
209    /// The ids of the edges touching each node, ascending.
210    incident: Vec<Vec<usize>>,
211    /// Index over all roadmap nodes.
212    nn: N,
213    /// Reused buffer for neighbor queries.
214    near: Vec<usize>,
215}
216
217impl<Sp, Sa, C> Prm<Sp, Sa, C>
218where
219    Sp: StateSpace,
220    Sa: Sampler<Sp::State>,
221    C: ValidityChecker<Sp>,
222{
223    /// Creates an empty roadmap with a [`LinearScan`] nearest-neighbor index.
224    ///
225    /// # Errors
226    ///
227    /// [`Error::InvalidRadius`] if the radius, `gamma` or `k_constant` is not positive and finite,
228    /// or `k` is zero.
229    pub fn new(space: Sp, sampler: Sa, checker: C, config: PrmConfig) -> Result<Self, Error> {
230        Self::with_nearest_neighbors(space, sampler, checker, config, LinearScan::default())
231    }
232}
233
234impl<Sp, Sa, C, N> Prm<Sp, Sa, C, N>
235where
236    Sp: StateSpace,
237    Sa: Sampler<Sp::State>,
238    C: ValidityChecker<Sp>,
239    N: NearestNeighbors<Sp>,
240{
241    /// Creates an empty roadmap with the given empty nearest-neighbor index.
242    ///
243    /// # Errors
244    ///
245    /// [`Error::InvalidRadius`] if the radius, `gamma` or `k_constant` is not positive and finite,
246    /// or `k` is zero.
247    pub fn with_nearest_neighbors(
248        space: Sp,
249        sampler: Sa,
250        checker: C,
251        config: PrmConfig,
252        nn: N,
253    ) -> Result<Self, Error> {
254        let valid = match config.connection {
255            Connection::Radius(value)
256            | Connection::Star { gamma: value }
257            | Connection::StarK { k_constant: value } => value.is_finite() && value > 0.0,
258            Connection::KNearest(k) => k > 0,
259        };
260        if !valid {
261            return Err(Error::InvalidRadius);
262        }
263
264        Ok(Self {
265            space,
266            sampler,
267            checker,
268            config,
269            states: Vec::new(),
270            edges: Vec::new(),
271            incident: Vec::new(),
272            nn,
273            near: Vec::new(),
274        })
275    }
276
277    /// Draws `samples` states and adds the valid ones to the roadmap, each connected to its
278    /// neighbors. Returns the number of nodes added.
279    pub fn grow<R: Rng + ?Sized>(&mut self, samples: usize, rng: &mut R) -> usize {
280        let before = self.states.len();
281
282        for _ in 0..samples {
283            let state = self.sampler.sample(rng);
284
285            if self.checker.check_state(&state).is_valid() {
286                self.add_node(state);
287            }
288        }
289
290        self.states.len() - before
291    }
292
293    /// Adds a valid state as a node and connects it to the nodes within the current radius.
294    fn add_node(&mut self, state: Sp::State) {
295        let id = self.states.len();
296        let mut near = core::mem::take(&mut self.near);
297        self.neighbors(&state, self.neighborhood(id + 1), &mut near);
298
299        self.states.push(state.clone());
300        self.incident.push(Vec::new());
301
302        for &other in &near {
303            self.try_connect(other, id);
304        }
305
306        self.nn.insert(id, state);
307        self.near = near;
308    }
309
310    /// Adds the edge between the older node `a` and the newer node `b`, checked unless lazy.
311    fn try_connect(&mut self, a: usize, b: usize) {
312        let status = if self.config.lazy {
313            EdgeStatus::Unchecked
314        } else if self.is_edge_valid(a, b) {
315            EdgeStatus::Valid
316        } else {
317            return;
318        };
319
320        let edge = self.edges.len();
321        self.edges.push(Edge {
322            a,
323            b,
324            cost: self.space.distance(&self.states[a], &self.states[b]),
325            status,
326        });
327        self.incident[a].push(edge);
328        self.incident[b].push(edge);
329    }
330
331    /// Whether the roadmap edge between nodes `a` and `b` checks as valid, in both directions
332    /// if configured.
333    fn is_edge_valid(&self, a: usize, b: usize) -> bool {
334        let (sa, sb) = (&self.states[a], &self.states[b]);
335        let forward = self.checker.check_motion(&self.space, sa, sb).is_valid();
336
337        forward
338            && (!self.config.check_both_directions
339                || self.checker.check_motion(&self.space, sb, sa).is_valid())
340    }
341
342    /// The neighbor rule for a roadmap of `n` nodes.
343    fn neighborhood(&self, n: usize) -> Neighborhood {
344        match self.config.connection {
345            Connection::Radius(radius) => Neighborhood::Radius(radius),
346            Connection::Star { gamma } => Neighborhood::Radius(shrinking_radius(
347                gamma,
348                n,
349                dimension_f64(self.space.dimension()),
350            )),
351            Connection::KNearest(k) => Neighborhood::Nearest(k),
352            Connection::StarK { k_constant } => {
353                Neighborhood::Nearest(k_nearest_count(k_constant, n))
354            }
355        }
356    }
357
358    /// Replaces `out` with the roadmap nodes that `state` connects to under `rule`, and returns
359    /// the reach of the rule: the radius, or for k-nearest the distance of the farthest
360    /// neighbor (infinite while fewer than `k` nodes exist).
361    fn neighbors(&self, state: &Sp::State, rule: Neighborhood, out: &mut Vec<usize>) -> f64 {
362        match rule {
363            Neighborhood::Radius(radius) => {
364                self.nn.within_radius(&self.space, state, radius, out);
365
366                radius
367            }
368            Neighborhood::Nearest(k) => {
369                self.nn.k_nearest(&self.space, state, k, out);
370
371                if out.len() < k {
372                    f64::INFINITY
373                } else {
374                    out.last().map_or(f64::INFINITY, |&far| {
375                        self.space.distance(&self.states[far], state)
376                    })
377                }
378            }
379        }
380    }
381
382    /// The cheapest path from `start` to `goal` through the roadmap, or `None` if the roadmap
383    /// does not connect them yet.
384    ///
385    /// The start connects to every node within the current connection radius by a valid
386    /// motion. The path ends at a roadmap node inside `goal` or at `goal`'s center, which
387    /// connects like the start when it is valid. A lazy roadmap checks the edges of each
388    /// candidate path, drops invalid ones and searches again, so its result equals the eager
389    /// one for the same samples.
390    ///
391    /// # Errors
392    ///
393    /// [`Error::InvalidStart`] if `start` does not check as valid.
394    pub fn query(
395        &mut self,
396        start: &Sp::State,
397        goal: &GoalRegion<Sp::State>,
398    ) -> Result<Option<Path<Sp::State>>, Error> {
399        let validity = self.checker.check_state(start);
400        if !validity.is_valid() {
401            return Err(Error::InvalidStart(validity));
402        }
403
404        let ends = self.connect_endpoints(start, goal);
405
406        loop {
407            let Some(route) = self.search(&ends, goal) else {
408                return Ok(None);
409            };
410
411            if self.confirm_lazy_edges(&route) {
412                return Ok(Some(self.to_path(&route, start, goal)));
413            }
414        }
415    }
416
417    /// The query-local arcs from the start into the roadmap and from the roadmap to the goal
418    /// center, each checked in travel direction.
419    ///
420    /// Both endpoints connect like a new node would. The direct start-to-center motion is
421    /// tried when the center lies within the start's reach: inside the radius, or no farther
422    /// than the start's `k`-th nearest node.
423    fn connect_endpoints(&self, start: &Sp::State, goal: &GoalRegion<Sp::State>) -> Endpoints {
424        let rule = self.neighborhood(self.states.len().max(1));
425        let center = goal.center();
426        let center_valid = self.checker.check_state(center).is_valid();
427        let mut near = Vec::new();
428
429        let reach = self.neighbors(start, rule, &mut near);
430        let from_start = near
431            .iter()
432            .filter(|&&node| self.is_motion_valid(start, &self.states[node]))
433            .map(|&node| (node, self.space.distance(start, &self.states[node])))
434            .collect();
435
436        let mut to_center = alloc::vec![f64::INFINITY; self.states.len()];
437        if center_valid {
438            self.neighbors(center, rule, &mut near);
439
440            for &node in &near {
441                if self.is_motion_valid(&self.states[node], center) {
442                    to_center[node] = self.space.distance(&self.states[node], center);
443                }
444            }
445        }
446
447        let direct = self.space.distance(start, center);
448        let start_to_center =
449            (center_valid && direct <= reach && self.is_motion_valid(start, center))
450                .then_some(direct);
451
452        Endpoints {
453            from_start,
454            to_center,
455            start_to_center,
456            start_in_goal: goal.contains(&self.space, start),
457        }
458    }
459
460    /// Whether the motion from `from` to `to` checks as valid.
461    fn is_motion_valid(&self, from: &Sp::State, to: &Sp::State) -> bool {
462        self.checker.check_motion(&self.space, from, to).is_valid()
463    }
464
465    /// Dijkstra from the start over the roadmap, skipping edges known to be invalid.
466    ///
467    /// Node ids: roadmap nodes `0..n`, the start `n`, the goal center `n + 1`.
468    fn search(&self, ends: &Endpoints, goal: &GoalRegion<Sp::State>) -> Option<Route> {
469        let n = self.states.len();
470        let (start, center) = (n, n + 1);
471
472        let is_goal = |node: usize| {
473            node == center
474                || (node == start && ends.start_in_goal)
475                || (node < n && goal.contains(&self.space, &self.states[node]))
476        };
477
478        let arcs = |node: usize, out: &mut Vec<Arc>| {
479            out.clear();
480
481            if node == start {
482                out.extend(ends.from_start.iter().map(|&(to, cost)| Arc {
483                    to,
484                    cost,
485                    edge: None,
486                }));
487                out.extend(ends.start_to_center.map(|cost| Arc {
488                    to: center,
489                    cost,
490                    edge: None,
491                }));
492            } else if node < n {
493                self.roadmap_arcs(node, out);
494
495                if ends.to_center[node].is_finite() {
496                    out.push(Arc {
497                        to: center,
498                        cost: ends.to_center[node],
499                        edge: None,
500                    });
501                }
502            }
503        };
504
505        shortest_path(n + 2, start, is_goal, arcs)
506    }
507
508    /// Appends the arcs along the not-invalid roadmap edges of `node`.
509    fn roadmap_arcs(&self, node: usize, out: &mut Vec<Arc>) {
510        for &id in &self.incident[node] {
511            let edge = &self.edges[id];
512
513            if edge.status != EdgeStatus::Invalid {
514                let to = if edge.a == node { edge.b } else { edge.a };
515                out.push(Arc {
516                    to,
517                    cost: edge.cost,
518                    edge: Some(id),
519                });
520            }
521        }
522    }
523
524    /// Checks the unchecked roadmap edges along `route` in travel order. Returns whether all are
525    /// valid; marks the first invalid one and stops there otherwise.
526    fn confirm_lazy_edges(&mut self, route: &Route) -> bool {
527        for (step, edge) in route.edges.iter().enumerate() {
528            let Some(id) = *edge else { continue };
529
530            if self.edges[id].status != EdgeStatus::Unchecked {
531                continue;
532            }
533
534            let (from, to) = (route.nodes[step], route.nodes[step + 1]);
535            let valid = self.is_motion_valid(&self.states[from], &self.states[to])
536                && (!self.config.check_both_directions
537                    || self.is_motion_valid(&self.states[to], &self.states[from]));
538
539            self.edges[id].status = if valid {
540                EdgeStatus::Valid
541            } else {
542                EdgeStatus::Invalid
543            };
544            if !valid {
545                return false;
546            }
547        }
548
549        true
550    }
551
552    /// Converts a route over query node ids into a path of states.
553    fn to_path(
554        &self,
555        route: &Route,
556        start: &Sp::State,
557        goal: &GoalRegion<Sp::State>,
558    ) -> Path<Sp::State> {
559        let n = self.states.len();
560        let states = route
561            .nodes
562            .iter()
563            .map(|&node| match node {
564                node if node < n => self.states[node].clone(),
565                node if node == n => start.clone(),
566                _ => goal.center().clone(),
567            })
568            .collect();
569
570        Path {
571            states,
572            cost: route.cost,
573        }
574    }
575
576    /// The number of roadmap nodes.
577    #[must_use]
578    pub fn node_count(&self) -> usize {
579        self.states.len()
580    }
581
582    /// The number of roadmap edges that are valid or not checked yet.
583    #[must_use]
584    pub fn edge_count(&self) -> usize {
585        self.edges
586            .iter()
587            .filter(|edge| edge.status != EdgeStatus::Invalid)
588            .count()
589    }
590}
591
592/// Query-local connections of a start state and a goal region to the roadmap.
593struct Endpoints {
594    /// Roadmap nodes reachable from the start by a valid motion, with the motion cost.
595    from_start: Vec<(usize, f64)>,
596    /// Per roadmap node, the cost of a valid motion to the goal center, or infinity.
597    to_center: Vec<f64>,
598    /// The cost of a valid direct motion from the start to the goal center, if any.
599    start_to_center: Option<f64>,
600    /// Whether the start itself lies in the goal region.
601    start_in_goal: bool,
602}
603
604#[cfg(test)]
605mod tests {
606    use super::*;
607    use crate::{Euclidean, UniformBox, Validity, discretized_motion};
608    use rand_core::SeedableRng;
609
610    /// A wall at `x` in `[4, 6]` for `y < 8` in a 10 x 10 box.
611    struct Wall;
612
613    impl ValidityChecker<Euclidean<2>> for Wall {
614        fn check_state(&self, s: &[f64; 2]) -> Validity {
615            if (4.0..=6.0).contains(&s[0]) && s[1] < 8.0 {
616                Validity::Invalid
617            } else {
618                Validity::Valid
619            }
620        }
621
622        fn check_motion(&self, space: &Euclidean<2>, from: &[f64; 2], to: &[f64; 2]) -> Validity {
623            discretized_motion(space, from, to, 0.02, |s| self.check_state(s))
624        }
625    }
626
627    /// A PRM* over the wall world grown by 400 samples with a fixed seed.
628    fn roadmap(lazy: bool) -> Prm<Euclidean<2>, UniformBox<2>, Wall> {
629        let gamma = 1.5 * PrmConfig::gamma_lower_bound(2, 100.0);
630        let config = if lazy {
631            PrmConfig::star(gamma).lazy()
632        } else {
633            PrmConfig::star(gamma)
634        };
635        let mut prm = Prm::new(
636            Euclidean::<2>,
637            UniformBox::new([0.0; 2], [10.0; 2]),
638            Wall,
639            config,
640        )
641        .expect("valid config");
642        prm.grow(400, &mut rand_pcg::Pcg64Mcg::seed_from_u64(3));
643
644        prm
645    }
646
647    #[test]
648    fn lazy_and_eager_roadmaps_agree() {
649        let (mut eager, mut lazy) = (roadmap(false), roadmap(true));
650        let goal = GoalRegion::new([9.0, 1.0], 0.3);
651
652        let a = eager
653            .query(&[1.0, 1.0], &goal)
654            .expect("valid")
655            .expect("connected");
656        let b = lazy
657            .query(&[1.0, 1.0], &goal)
658            .expect("valid")
659            .expect("connected");
660
661        assert!((a.cost - b.cost).abs() < 1e-9, "{} vs {}", a.cost, b.cost);
662        assert!(
663            lazy.edge_count() > eager.edge_count(),
664            "lazy keeps unchecked edges"
665        );
666        for pair in b.states.windows(2) {
667            assert_eq!(
668                Wall.check_motion(&Euclidean::<2>, &pair[0], &pair[1]),
669                Validity::Valid
670            );
671        }
672    }
673
674    /// A one-way gate at `x = 5`: motions may cross it only while `x` increases.
675    struct OneWay;
676
677    impl ValidityChecker<Euclidean<1>> for OneWay {
678        fn check_state(&self, _: &[f64; 1]) -> Validity {
679            Validity::Valid
680        }
681
682        fn check_motion(&self, _: &Euclidean<1>, from: &[f64; 1], to: &[f64; 1]) -> Validity {
683            if (from[0] < 5.0) != (to[0] < 5.0) && to[0] < from[0] {
684                Validity::Invalid
685            } else {
686                Validity::Valid
687            }
688        }
689    }
690
691    /// The first result of querying from 9 to 1 across the gate on a 1D roadmap.
692    fn leftward(config: PrmConfig) -> Option<Path<[f64; 1]>> {
693        let sampler = UniformBox::new([0.0], [10.0]);
694        let mut prm = Prm::new(Euclidean::<1>, sampler, OneWay, config).expect("valid");
695        prm.grow(1000, &mut rand_pcg::Pcg64Mcg::seed_from_u64(5));
696
697        prm.query(&[9.0], &GoalRegion::new([1.0], 0.1))
698            .expect("valid start")
699    }
700
701    #[test]
702    fn two_way_checks_keep_directional_checkers_sound() {
703        let both = |config: PrmConfig| PrmConfig {
704            check_both_directions: true,
705            ..config
706        };
707
708        assert_eq!(leftward(both(PrmConfig::fixed(0.5))), None);
709        assert_eq!(leftward(both(PrmConfig::fixed(0.5).lazy())), None);
710
711        // One-way checks only suit symmetric checkers: here they accept an edge that is
712        // invalid in the direction it is traveled.
713        let unsound = leftward(PrmConfig::fixed(0.5)).expect("one-way checks find a path");
714        let crossing = unsound.states.windows(2).any(|pair| {
715            OneWay.check_motion(&Euclidean::<1>, &pair[0], &pair[1]) == Validity::Invalid
716        });
717        assert!(crossing);
718    }
719
720    #[test]
721    fn rejects_bad_radius_and_invalid_start() {
722        let make = |config| {
723            Prm::new(
724                Euclidean::<2>,
725                UniformBox::new([0.0; 2], [1.0; 2]),
726                Wall,
727                config,
728            )
729        };
730
731        assert_eq!(
732            make(PrmConfig::fixed(0.0)).err(),
733            Some(Error::InvalidRadius)
734        );
735        assert_eq!(
736            make(PrmConfig::star(f64::NAN)).err(),
737            Some(Error::InvalidRadius)
738        );
739        assert_eq!(
740            roadmap(false).query(&[5.0, 1.0], &GoalRegion::new([9.0, 1.0], 0.3)),
741            Err(Error::InvalidStart(Validity::Invalid))
742        );
743    }
744}