1use 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#[derive(Debug, Clone, Copy, PartialEq)]
16pub enum Connection {
17 Radius(f64),
19 Star {
23 gamma: f64,
25 },
26 KNearest(usize),
28 StarK {
32 k_constant: f64,
34 },
35}
36
37#[derive(Debug, Clone, Copy, PartialEq)]
39enum Neighborhood {
40 Radius(f64),
42 Nearest(usize),
44}
45
46#[derive(Debug, Clone, Copy, PartialEq)]
48pub struct PrmConfig {
49 pub connection: Connection,
54 pub lazy: bool,
59 pub check_both_directions: bool,
66}
67
68impl PrmConfig {
69 #[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 #[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 #[must_use]
91 pub const fn lazy(self) -> Self {
92 Self { lazy: true, ..self }
93 }
94
95 #[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 #[must_use]
108 pub fn k_constant_lower_bound(dimension: usize) -> f64 {
109 k_constant_lower_bound(dimension)
110 }
111
112 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
129enum EdgeStatus {
130 Valid,
132 Invalid,
134 Unchecked,
136}
137
138#[derive(Debug, Clone)]
140struct Edge {
141 a: usize,
143 b: usize,
145 cost: f64,
147 status: EdgeStatus,
149}
150
151#[derive(Debug, Clone)]
196pub struct Prm<Sp: StateSpace, Sa, C, N = LinearScan<<Sp as StateSpace>::State>> {
197 space: Sp,
199 sampler: Sa,
201 checker: C,
203 config: PrmConfig,
205 states: Vec<Sp::State>,
207 edges: Vec<Edge>,
209 incident: Vec<Vec<usize>>,
211 nn: N,
213 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 #[must_use]
578 pub fn node_count(&self) -> usize {
579 self.states.len()
580 }
581
582 #[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
592struct Endpoints {
594 from_start: Vec<(usize, f64)>,
596 to_center: Vec<f64>,
598 start_to_center: Option<f64>,
600 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 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 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 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 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 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}