use alloc::{collections::BTreeMap, vec::Vec};
use rand_core::Rng;
use super::{
Error,
sparse::{GuardKind, SparseGraph},
};
use crate::{
GoalRegion, LinearScan, NearestNeighbors, Path, Sampler, StateSpace, ValidityChecker, unit_f64,
};
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Spars2Config {
pub sparse_delta: f64,
pub dense_delta: f64,
pub stretch: f64,
pub max_failures: usize,
pub near_samples: usize,
pub check_both_directions: bool,
}
impl Spars2Config {
#[must_use]
pub const fn new(sparse_delta: f64, dense_delta: f64) -> Self {
Self {
sparse_delta,
dense_delta,
stretch: 3.0,
max_failures: 5000,
near_samples: 4,
check_both_directions: false,
}
}
fn validate(&self) -> Result<(), Error> {
let positive = |value: f64| value.is_finite() && value > 0.0;
let valid = positive(self.sparse_delta)
&& positive(self.dense_delta)
&& self.dense_delta < self.sparse_delta
&& self.stretch.is_finite()
&& self.stretch > 1.0;
if valid {
Ok(())
} else {
Err(Error::InvalidRadius)
}
}
}
#[derive(Debug, Clone)]
struct InterfaceData<S> {
first: Option<(S, S)>,
second: Option<(S, S)>,
}
impl<S> Default for InterfaceData<S> {
fn default() -> Self {
Self {
first: None,
second: None,
}
}
}
type Interfaces<S> = BTreeMap<(usize, usize), InterfaceData<S>>;
#[derive(Debug, Clone)]
pub struct Spars2<Sp: StateSpace, Sa, C, N = LinearScan<<Sp as StateSpace>::State>> {
space: Sp,
sampler: Sa,
checker: C,
config: Spars2Config,
graph: SparseGraph<Sp::State, N>,
interfaces: Vec<Interfaces<Sp::State>>,
failures: usize,
}
pub const NEAR_ATTEMPTS: usize = 16;
impl<Sp, Sa, C> Spars2<Sp, Sa, C>
where
Sp: StateSpace,
Sa: Sampler<Sp::State>,
C: ValidityChecker<Sp>,
{
pub fn new(space: Sp, sampler: Sa, checker: C, config: Spars2Config) -> Result<Self, Error> {
Self::with_nearest_neighbors(space, sampler, checker, config, LinearScan::default())
}
}
impl<Sp, Sa, C, N> Spars2<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: Spars2Config,
nn: N,
) -> Result<Self, Error> {
config.validate()?;
Ok(Self {
space,
sampler,
checker,
config,
graph: SparseGraph::new(nn),
interfaces: Vec::new(),
failures: 0,
})
}
pub fn construct<R: Rng + ?Sized>(&mut self, max_samples: usize, rng: &mut R) -> usize {
let mut drawn = 0;
while drawn < max_samples && !self.is_complete() {
self.step(rng);
drawn += 1;
}
drawn
}
pub fn step<R: Rng + ?Sized>(&mut self, rng: &mut R) -> bool {
let before = (self.graph.len(), self.graph.edge_count());
let q = self.sampler.sample(rng);
if self.checker.check_state(&q).is_valid() {
self.process(q, rng);
}
let changed = before != (self.graph.len(), self.graph.edge_count());
self.failures = if changed { 0 } else { self.failures + 1 };
changed
}
fn process<R: Rng + ?Sized>(&mut self, q: Sp::State, rng: &mut R) {
let (near, visible) = self.neighborhood(&q);
if visible.is_empty() {
self.add_guard(q, GuardKind::Coverage);
} else if !self.check_connectivity(&q, &visible)
&& !self.check_interface(&q, &near, &visible)
{
self.check_quality(&q, visible[0], rng);
}
}
fn neighborhood(&self, state: &Sp::State) -> (Vec<usize>, Vec<usize>) {
self.graph
.neighborhood(&self.space, state, self.config.sparse_delta, |guard| {
self.is_edge_valid(state, guard)
})
}
fn is_edge_valid(&self, a: &Sp::State, b: &Sp::State) -> bool {
let forward = self.checker.check_motion(&self.space, a, b).is_valid();
forward
&& (!self.config.check_both_directions
|| self.checker.check_motion(&self.space, b, a).is_valid())
}
fn add_guard(&mut self, state: Sp::State, kind: GuardKind) -> usize {
let mut near = Vec::new();
self.graph
.nn
.within_radius(&self.space, &state, self.config.sparse_delta, &mut near);
for guard in near {
self.interfaces[guard].clear();
}
self.interfaces.push(BTreeMap::new());
self.graph.add_guard(state, kind)
}
fn check_connectivity(&mut self, q: &Sp::State, visible: &[usize]) -> bool {
let links = self.graph.connectivity_links(visible);
if links.is_empty() {
return false;
}
let guard = self.add_guard(q.clone(), GuardKind::Connectivity);
self.graph.connect_links(guard, &links);
true
}
fn check_interface(&mut self, q: &Sp::State, near: &[usize], visible: &[usize]) -> bool {
let Some((v1, v2)) = self.graph.interface_pair(near, visible) else {
return false;
};
if self.is_edge_valid(&self.graph.states[v1], &self.graph.states[v2]) {
self.graph.connect(v1, v2);
} else {
let guard = self.add_guard(q.clone(), GuardKind::Interface);
self.graph.connect(guard, v1);
self.graph.connect(guard, v2);
}
true
}
fn check_quality<R: Rng + ?Sized>(&mut self, q: &Sp::State, v: usize, rng: &mut R) {
let Some(representatives) = self.close_representatives(q, v, rng) else {
return;
};
for (r, sigma) in &representatives {
self.update_pair_points(v, q, *r, sigma);
self.update_pair_points(*r, sigma, v, q);
}
self.test_add_path(v);
for (r, _) in &representatives {
self.test_add_path(*r);
}
}
fn close_representatives<R: Rng + ?Sized>(
&mut self,
q: &Sp::State,
v: usize,
rng: &mut R,
) -> Option<Vec<(usize, Sp::State)>> {
let mut found: Vec<(usize, Sp::State)> = Vec::new();
for _ in 0..self.config.near_samples {
let Some(sigma) = self.sample_near(q, rng) else {
continue;
};
let (_, visible) = self.neighborhood(&sigma);
let Some(&representative) = visible.first() else {
self.add_guard(sigma, GuardKind::Coverage);
return None;
};
if representative != v && found.iter().all(|(r, _)| *r != representative) {
found.push((representative, sigma));
}
}
Some(found)
}
fn sample_near<R: Rng + ?Sized>(&mut self, q: &Sp::State, rng: &mut R) -> Option<Sp::State> {
for _ in 0..NEAR_ATTEMPTS {
let toward = self.sampler.sample(rng);
let distance = self.space.distance(q, &toward);
let step = self.config.dense_delta * unit_f64(rng);
if distance <= 0.0 {
continue;
}
let sigma = self
.space
.interpolate(q, &toward, (step / distance).min(1.0));
if self.space.distance(q, &sigma) <= self.config.dense_delta
&& self.checker.check_state(&sigma).is_valid()
&& self.is_edge_valid(q, &sigma)
{
return Some(sigma);
}
}
None
}
fn update_pair_points(&mut self, v: usize, point: &Sp::State, r: usize, sigma: &Sp::State) {
for r_prime in self.graph.non_adjacent_neighbors(v, r) {
self.distance_check(v, point, r, sigma, r_prime);
}
}
fn distance_check(
&mut self,
v: usize,
point: &Sp::State,
r: usize,
sigma: &Sp::State,
r_prime: usize,
) {
let space = &self.space;
let data = self.interfaces[v].entry(pair(r, r_prime)).or_default();
let (mine, other) = if r < r_prime {
(&mut data.first, &data.second)
} else {
(&mut data.second, &data.first)
};
let replace = match (&*mine, other) {
(None, _) => true,
(Some(_), None) => false,
(Some((current, _)), Some((opposite, _))) => {
space.distance(point, opposite) < space.distance(current, opposite)
}
};
if replace {
*mine = Some((point.clone(), sigma.clone()));
}
}
fn interface_distance(&self, v: usize, r: usize, r_prime: usize) -> f64 {
match self.interfaces[v].get(&pair(r, r_prime)) {
Some(InterfaceData {
first: Some((a, _)),
second: Some((b, _)),
}) => self.space.distance(a, b),
_ => f64::INFINITY,
}
}
fn has_point_toward(&self, v: usize, r_pp: usize, x: usize) -> bool {
self.interfaces[v].get(&pair(r_pp, x)).is_some_and(|data| {
if r_pp < x {
data.first.is_some()
} else {
data.second.is_some()
}
})
}
fn test_add_path(&mut self, v: usize) -> bool {
let neighbors = self.graph.adjacency[v].clone();
for r in neighbors {
for r_prime in self.graph.non_adjacent_neighbors(v, r) {
let through_v = self.longest_path_estimate(v, r, r_prime);
if through_v > self.config.stretch * self.interface_distance(v, r, r_prime) {
self.add_shortcut(v, r, r_prime);
return true;
}
}
}
false
}
fn longest_path_estimate(&self, v: usize, r: usize, r_prime: usize) -> f64 {
let states = &self.graph.states;
let to_r = self.space.distance(&states[r], &states[v]);
self.graph.adjacency[r_prime]
.iter()
.copied()
.filter(|&x| {
self.graph.has_edge(x, v)
&& !self.graph.has_edge(x, r)
&& self.has_point_toward(v, r_prime, x)
})
.chain([r_prime])
.map(|x| f64::midpoint(to_r, self.space.distance(&states[v], &states[x])))
.fold(0.0, f64::max)
}
fn add_shortcut(&mut self, v: usize, r: usize, r_prime: usize) {
if self.is_edge_valid(&self.graph.states[r], &self.graph.states[r_prime]) {
self.graph.connect(r, r_prime);
return;
}
let Some(data) = self.interfaces[v].get(&pair(r, r_prime)).cloned() else {
return;
};
let (Some((point_a, sigma_a)), Some((point_b, sigma_b))) = (data.first, data.second) else {
return;
};
let ((point_r, sigma_r), (point_rp, sigma_rp)) = if r < r_prime {
((point_a, sigma_a), (point_b, sigma_b))
} else {
((point_b, sigma_b), (point_a, sigma_a))
};
self.add_chain(r, [sigma_r, point_r], v, [point_rp, sigma_rp], r_prime);
}
fn add_chain(
&mut self,
r: usize,
before: [Sp::State; 2],
v: usize,
after: [Sp::State; 2],
r_prime: usize,
) {
let states = &self.graph.states;
let chain: Vec<&Sp::State> = [&states[r]]
.into_iter()
.chain(&before)
.chain([&states[v]])
.chain(&after)
.chain([&states[r_prime]])
.collect();
if !chain
.windows(2)
.all(|pair| self.is_edge_valid(pair[0], pair[1]))
{
return;
}
let mut prior = r;
for state in before {
let guard = self.add_guard(state, GuardKind::Quality);
self.graph.connect(prior, guard);
prior = guard;
}
self.graph.connect(prior, v);
prior = v;
for state in after {
let guard = self.add_guard(state, GuardKind::Quality);
self.graph.connect(prior, guard);
prior = guard;
}
self.graph.connect(prior, r_prime);
}
pub fn query(
&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));
}
Ok(self.graph.query(
&self.space,
&self.checker,
start,
goal,
self.config.sparse_delta,
))
}
#[must_use]
pub const fn is_complete(&self) -> bool {
self.failures >= self.config.max_failures
}
#[must_use]
pub fn node_count(&self) -> usize {
self.graph.len()
}
#[must_use]
pub fn edge_count(&self) -> usize {
self.graph.edge_count()
}
#[must_use]
pub fn guard_counts(&self) -> [usize; 4] {
let count = |kind| self.graph.kinds.iter().filter(|&&k| k == kind).count();
[
count(GuardKind::Coverage),
count(GuardKind::Connectivity),
count(GuardKind::Interface),
count(GuardKind::Quality),
]
}
}
fn pair(a: usize, b: usize) -> (usize, usize) {
(a.min(b), a.max(b))
}