use alloc::vec::Vec;
use rand_core::Rng;
use super::Error;
use crate::graph::{Arc, Route, shortest_path};
use crate::radius::{
dimension_f64, k_constant_lower_bound, k_nearest_count, shrinking_radius, unit_ball_volume,
};
use crate::{GoalRegion, LinearScan, NearestNeighbors, Path, Sampler, StateSpace, ValidityChecker};
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Connection {
Radius(f64),
Star {
gamma: f64,
},
KNearest(usize),
StarK {
k_constant: f64,
},
}
#[derive(Debug, Clone, Copy, PartialEq)]
enum Neighborhood {
Radius(f64),
Nearest(usize),
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct PrmConfig {
pub connection: Connection,
pub lazy: bool,
pub check_both_directions: bool,
}
impl PrmConfig {
#[must_use]
pub const fn fixed(radius: f64) -> Self {
Self {
connection: Connection::Radius(radius),
lazy: false,
check_both_directions: false,
}
}
#[must_use]
pub const fn star(gamma: f64) -> Self {
Self {
connection: Connection::Star { gamma },
lazy: false,
check_both_directions: false,
}
}
#[must_use]
pub const fn lazy(self) -> Self {
Self { lazy: true, ..self }
}
#[must_use]
pub const fn star_k(k_constant: f64) -> Self {
Self {
connection: Connection::StarK { k_constant },
lazy: false,
check_both_directions: false,
}
}
#[must_use]
pub fn k_constant_lower_bound(dimension: usize) -> f64 {
k_constant_lower_bound(dimension)
}
#[must_use]
pub fn gamma_lower_bound(dimension: usize, free_volume: f64) -> f64 {
let d = dimension_f64(dimension);
2.0 * libm::pow(1.0 + 1.0 / d, 1.0 / d)
* libm::pow(free_volume / unit_ball_volume(d), 1.0 / d)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum EdgeStatus {
Valid,
Invalid,
Unchecked,
}
#[derive(Debug, Clone)]
struct Edge {
a: usize,
b: usize,
cost: f64,
status: EdgeStatus,
}
#[derive(Debug, Clone)]
pub struct Prm<Sp: StateSpace, Sa, C, N = LinearScan<<Sp as StateSpace>::State>> {
space: Sp,
sampler: Sa,
checker: C,
config: PrmConfig,
states: Vec<Sp::State>,
edges: Vec<Edge>,
incident: Vec<Vec<usize>>,
nn: N,
near: Vec<usize>,
}
impl<Sp, Sa, C> Prm<Sp, Sa, C>
where
Sp: StateSpace,
Sa: Sampler<Sp::State>,
C: ValidityChecker<Sp>,
{
pub fn new(space: Sp, sampler: Sa, checker: C, config: PrmConfig) -> Result<Self, Error> {
Self::with_nearest_neighbors(space, sampler, checker, config, LinearScan::default())
}
}
impl<Sp, Sa, C, N> Prm<Sp, Sa, C, N>
where
Sp: StateSpace,
Sa: Sampler<Sp::State>,
C: ValidityChecker<Sp>,
N: NearestNeighbors<Sp>,
{
pub fn with_nearest_neighbors(
space: Sp,
sampler: Sa,
checker: C,
config: PrmConfig,
nn: N,
) -> Result<Self, Error> {
let valid = match config.connection {
Connection::Radius(value)
| Connection::Star { gamma: value }
| Connection::StarK { k_constant: value } => value.is_finite() && value > 0.0,
Connection::KNearest(k) => k > 0,
};
if !valid {
return Err(Error::InvalidRadius);
}
Ok(Self {
space,
sampler,
checker,
config,
states: Vec::new(),
edges: Vec::new(),
incident: Vec::new(),
nn,
near: Vec::new(),
})
}
pub fn grow<R: Rng + ?Sized>(&mut self, samples: usize, rng: &mut R) -> usize {
let before = self.states.len();
for _ in 0..samples {
let state = self.sampler.sample(rng);
if self.checker.check_state(&state).is_valid() {
self.add_node(state);
}
}
self.states.len() - before
}
fn add_node(&mut self, state: Sp::State) {
let id = self.states.len();
let mut near = core::mem::take(&mut self.near);
self.neighbors(&state, self.neighborhood(id + 1), &mut near);
self.states.push(state.clone());
self.incident.push(Vec::new());
for &other in &near {
self.try_connect(other, id);
}
self.nn.insert(id, state);
self.near = near;
}
fn try_connect(&mut self, a: usize, b: usize) {
let status = if self.config.lazy {
EdgeStatus::Unchecked
} else if self.is_edge_valid(a, b) {
EdgeStatus::Valid
} else {
return;
};
let edge = self.edges.len();
self.edges.push(Edge {
a,
b,
cost: self.space.distance(&self.states[a], &self.states[b]),
status,
});
self.incident[a].push(edge);
self.incident[b].push(edge);
}
fn is_edge_valid(&self, a: usize, b: usize) -> bool {
let (sa, sb) = (&self.states[a], &self.states[b]);
let forward = self.checker.check_motion(&self.space, sa, sb).is_valid();
forward
&& (!self.config.check_both_directions
|| self.checker.check_motion(&self.space, sb, sa).is_valid())
}
fn neighborhood(&self, n: usize) -> Neighborhood {
match self.config.connection {
Connection::Radius(radius) => Neighborhood::Radius(radius),
Connection::Star { gamma } => Neighborhood::Radius(shrinking_radius(
gamma,
n,
dimension_f64(self.space.dimension()),
)),
Connection::KNearest(k) => Neighborhood::Nearest(k),
Connection::StarK { k_constant } => {
Neighborhood::Nearest(k_nearest_count(k_constant, n))
}
}
}
fn neighbors(&self, state: &Sp::State, rule: Neighborhood, out: &mut Vec<usize>) -> f64 {
match rule {
Neighborhood::Radius(radius) => {
self.nn.within_radius(&self.space, state, radius, out);
radius
}
Neighborhood::Nearest(k) => {
self.nn.k_nearest(&self.space, state, k, out);
if out.len() < k {
f64::INFINITY
} else {
out.last().map_or(f64::INFINITY, |&far| {
self.space.distance(&self.states[far], state)
})
}
}
}
}
pub fn query(
&mut self,
start: &Sp::State,
goal: &GoalRegion<Sp::State>,
) -> Result<Option<Path<Sp::State>>, Error> {
let validity = self.checker.check_state(start);
if !validity.is_valid() {
return Err(Error::InvalidStart(validity));
}
let ends = self.connect_endpoints(start, goal);
loop {
let Some(route) = self.search(&ends, goal) else {
return Ok(None);
};
if self.confirm_lazy_edges(&route) {
return Ok(Some(self.to_path(&route, start, goal)));
}
}
}
fn connect_endpoints(&self, start: &Sp::State, goal: &GoalRegion<Sp::State>) -> Endpoints {
let rule = self.neighborhood(self.states.len().max(1));
let center = goal.center();
let center_valid = self.checker.check_state(center).is_valid();
let mut near = Vec::new();
let reach = self.neighbors(start, rule, &mut near);
let from_start = near
.iter()
.filter(|&&node| self.is_motion_valid(start, &self.states[node]))
.map(|&node| (node, self.space.distance(start, &self.states[node])))
.collect();
let mut to_center = alloc::vec![f64::INFINITY; self.states.len()];
if center_valid {
self.neighbors(center, rule, &mut near);
for &node in &near {
if self.is_motion_valid(&self.states[node], center) {
to_center[node] = self.space.distance(&self.states[node], center);
}
}
}
let direct = self.space.distance(start, center);
let start_to_center =
(center_valid && direct <= reach && self.is_motion_valid(start, center))
.then_some(direct);
Endpoints {
from_start,
to_center,
start_to_center,
start_in_goal: goal.contains(&self.space, start),
}
}
fn is_motion_valid(&self, from: &Sp::State, to: &Sp::State) -> bool {
self.checker.check_motion(&self.space, from, to).is_valid()
}
fn search(&self, ends: &Endpoints, goal: &GoalRegion<Sp::State>) -> Option<Route> {
let n = self.states.len();
let (start, center) = (n, n + 1);
let is_goal = |node: usize| {
node == center
|| (node == start && ends.start_in_goal)
|| (node < n && goal.contains(&self.space, &self.states[node]))
};
let arcs = |node: usize, out: &mut Vec<Arc>| {
out.clear();
if node == start {
out.extend(ends.from_start.iter().map(|&(to, cost)| Arc {
to,
cost,
edge: None,
}));
out.extend(ends.start_to_center.map(|cost| Arc {
to: center,
cost,
edge: None,
}));
} else if node < n {
self.roadmap_arcs(node, out);
if ends.to_center[node].is_finite() {
out.push(Arc {
to: center,
cost: ends.to_center[node],
edge: None,
});
}
}
};
shortest_path(n + 2, start, is_goal, arcs)
}
fn roadmap_arcs(&self, node: usize, out: &mut Vec<Arc>) {
for &id in &self.incident[node] {
let edge = &self.edges[id];
if edge.status != EdgeStatus::Invalid {
let to = if edge.a == node { edge.b } else { edge.a };
out.push(Arc {
to,
cost: edge.cost,
edge: Some(id),
});
}
}
}
fn confirm_lazy_edges(&mut self, route: &Route) -> bool {
for (step, edge) in route.edges.iter().enumerate() {
let Some(id) = *edge else { continue };
if self.edges[id].status != EdgeStatus::Unchecked {
continue;
}
let (from, to) = (route.nodes[step], route.nodes[step + 1]);
let valid = self.is_motion_valid(&self.states[from], &self.states[to])
&& (!self.config.check_both_directions
|| self.is_motion_valid(&self.states[to], &self.states[from]));
self.edges[id].status = if valid {
EdgeStatus::Valid
} else {
EdgeStatus::Invalid
};
if !valid {
return false;
}
}
true
}
fn to_path(
&self,
route: &Route,
start: &Sp::State,
goal: &GoalRegion<Sp::State>,
) -> Path<Sp::State> {
let n = self.states.len();
let states = route
.nodes
.iter()
.map(|&node| match node {
node if node < n => self.states[node].clone(),
node if node == n => start.clone(),
_ => goal.center().clone(),
})
.collect();
Path {
states,
cost: route.cost,
}
}
#[must_use]
pub fn node_count(&self) -> usize {
self.states.len()
}
#[must_use]
pub fn edge_count(&self) -> usize {
self.edges
.iter()
.filter(|edge| edge.status != EdgeStatus::Invalid)
.count()
}
}
struct Endpoints {
from_start: Vec<(usize, f64)>,
to_center: Vec<f64>,
start_to_center: Option<f64>,
start_in_goal: bool,
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{Euclidean, UniformBox, Validity, discretized_motion};
use rand_core::SeedableRng;
struct Wall;
impl ValidityChecker<Euclidean<2>> for Wall {
fn check_state(&self, s: &[f64; 2]) -> Validity {
if (4.0..=6.0).contains(&s[0]) && s[1] < 8.0 {
Validity::Invalid
} else {
Validity::Valid
}
}
fn check_motion(&self, space: &Euclidean<2>, from: &[f64; 2], to: &[f64; 2]) -> Validity {
discretized_motion(space, from, to, 0.02, |s| self.check_state(s))
}
}
fn roadmap(lazy: bool) -> Prm<Euclidean<2>, UniformBox<2>, Wall> {
let gamma = 1.5 * PrmConfig::gamma_lower_bound(2, 100.0);
let config = if lazy {
PrmConfig::star(gamma).lazy()
} else {
PrmConfig::star(gamma)
};
let mut prm = Prm::new(
Euclidean::<2>,
UniformBox::new([0.0; 2], [10.0; 2]),
Wall,
config,
)
.expect("valid config");
prm.grow(400, &mut rand_pcg::Pcg64Mcg::seed_from_u64(3));
prm
}
#[test]
fn lazy_and_eager_roadmaps_agree() {
let (mut eager, mut lazy) = (roadmap(false), roadmap(true));
let goal = GoalRegion::new([9.0, 1.0], 0.3);
let a = eager
.query(&[1.0, 1.0], &goal)
.expect("valid")
.expect("connected");
let b = lazy
.query(&[1.0, 1.0], &goal)
.expect("valid")
.expect("connected");
assert!((a.cost - b.cost).abs() < 1e-9, "{} vs {}", a.cost, b.cost);
assert!(
lazy.edge_count() > eager.edge_count(),
"lazy keeps unchecked edges"
);
for pair in b.states.windows(2) {
assert_eq!(
Wall.check_motion(&Euclidean::<2>, &pair[0], &pair[1]),
Validity::Valid
);
}
}
struct OneWay;
impl ValidityChecker<Euclidean<1>> for OneWay {
fn check_state(&self, _: &[f64; 1]) -> Validity {
Validity::Valid
}
fn check_motion(&self, _: &Euclidean<1>, from: &[f64; 1], to: &[f64; 1]) -> Validity {
if (from[0] < 5.0) != (to[0] < 5.0) && to[0] < from[0] {
Validity::Invalid
} else {
Validity::Valid
}
}
}
fn leftward(config: PrmConfig) -> Option<Path<[f64; 1]>> {
let sampler = UniformBox::new([0.0], [10.0]);
let mut prm = Prm::new(Euclidean::<1>, sampler, OneWay, config).expect("valid");
prm.grow(1000, &mut rand_pcg::Pcg64Mcg::seed_from_u64(5));
prm.query(&[9.0], &GoalRegion::new([1.0], 0.1))
.expect("valid start")
}
#[test]
fn two_way_checks_keep_directional_checkers_sound() {
let both = |config: PrmConfig| PrmConfig {
check_both_directions: true,
..config
};
assert_eq!(leftward(both(PrmConfig::fixed(0.5))), None);
assert_eq!(leftward(both(PrmConfig::fixed(0.5).lazy())), None);
let unsound = leftward(PrmConfig::fixed(0.5)).expect("one-way checks find a path");
let crossing = unsound.states.windows(2).any(|pair| {
OneWay.check_motion(&Euclidean::<1>, &pair[0], &pair[1]) == Validity::Invalid
});
assert!(crossing);
}
#[test]
fn rejects_bad_radius_and_invalid_start() {
let make = |config| {
Prm::new(
Euclidean::<2>,
UniformBox::new([0.0; 2], [1.0; 2]),
Wall,
config,
)
};
assert_eq!(
make(PrmConfig::fixed(0.0)).err(),
Some(Error::InvalidRadius)
);
assert_eq!(
make(PrmConfig::star(f64::NAN)).err(),
Some(Error::InvalidRadius)
);
assert_eq!(
roadmap(false).query(&[5.0, 1.0], &GoalRegion::new([9.0, 1.0], 0.3)),
Err(Error::InvalidStart(Validity::Invalid))
);
}
}