use alloc::{collections::BTreeSet, vec::Vec};
use crate::graph::{Arc, shortest_path};
use crate::{GoalRegion, NearestNeighbors, Path, StateSpace, ValidityChecker};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum GuardKind {
Coverage,
Connectivity,
Interface,
Quality,
}
#[derive(Debug, Clone, Default)]
struct UnionFind {
parent: Vec<usize>,
size: Vec<usize>,
}
impl UnionFind {
fn push(&mut self) -> usize {
let id = self.parent.len();
self.parent.push(id);
self.size.push(1);
id
}
fn find(&mut self, mut x: usize) -> usize {
while self.parent[x] != x {
self.parent[x] = self.parent[self.parent[x]];
x = self.parent[x];
}
x
}
fn union(&mut self, a: usize, b: usize) {
let (mut a, mut b) = (self.find(a), self.find(b));
if a == b {
return;
}
if self.size[a] < self.size[b] {
core::mem::swap(&mut a, &mut b);
}
self.parent[b] = a;
self.size[a] += self.size[b];
}
}
#[derive(Debug, Clone)]
pub(super) struct SparseGraph<S, N> {
pub(super) states: Vec<S>,
pub(super) kinds: Vec<GuardKind>,
pub(super) adjacency: Vec<Vec<usize>>,
edges: BTreeSet<(usize, usize)>,
components: UnionFind,
pub(super) nn: N,
}
impl<S: Clone, N> SparseGraph<S, N> {
pub(super) const fn new(nn: N) -> Self {
Self {
states: Vec::new(),
kinds: Vec::new(),
adjacency: Vec::new(),
edges: BTreeSet::new(),
components: UnionFind {
parent: Vec::new(),
size: Vec::new(),
},
nn,
}
}
pub(super) fn len(&self) -> usize {
self.states.len()
}
pub(super) fn edge_count(&self) -> usize {
self.edges.len()
}
pub(super) fn has_edge(&self, a: usize, b: usize) -> bool {
self.edges.contains(&(a.min(b), a.max(b)))
}
pub(super) fn connect(&mut self, a: usize, b: usize) {
if a == b || !self.edges.insert((a.min(b), a.max(b))) {
return;
}
self.adjacency[a].push(b);
self.adjacency[b].push(a);
self.components.union(a, b);
}
pub(super) fn same_component(&mut self, a: usize, b: usize) -> bool {
self.components.find(a) == self.components.find(b)
}
pub(super) fn connectivity_links(&mut self, visible: &[usize]) -> Vec<usize> {
let mut links = Vec::new();
for (i, &a) in visible.iter().enumerate() {
for &b in &visible[i + 1..] {
if !self.same_component(a, b) {
links.extend([a, b]);
}
}
}
links
}
pub(super) fn connect_links(&mut self, guard: usize, links: &[usize]) {
for &link in links {
if !self.has_edge(guard, link) && !self.same_component(link, guard) {
self.connect(guard, link);
}
}
}
pub(super) fn interface_pair(
&self,
near: &[usize],
visible: &[usize],
) -> Option<(usize, usize)> {
let [v1, v2, ..] = *visible else {
return None;
};
(near[..2] == [v1, v2] && !self.has_edge(v1, v2)).then_some((v1, v2))
}
pub(super) fn non_adjacent_neighbors(&self, v: usize, r: usize) -> Vec<usize> {
self.adjacency[v]
.iter()
.copied()
.filter(|&other| other != r && !self.has_edge(other, r))
.collect()
}
pub(super) fn add_guard<Sp>(&mut self, state: S, kind: GuardKind) -> usize
where
Sp: StateSpace<State = S>,
N: NearestNeighbors<Sp>,
{
let id = self.states.len();
self.nn.insert(id, state.clone());
self.states.push(state);
self.kinds.push(kind);
self.adjacency.push(Vec::new());
self.components.push();
id
}
fn near_sorted<Sp>(&self, space: &Sp, state: &S, radius: f64) -> Vec<usize>
where
Sp: StateSpace<State = S>,
N: NearestNeighbors<Sp>,
{
let mut near = Vec::new();
self.nn.within_radius(space, state, radius, &mut near);
let distance = |id: usize| space.distance(state, &self.states[id]);
near.sort_by(|&a, &b| distance(a).total_cmp(&distance(b)).then(a.cmp(&b)));
near
}
pub(super) fn neighborhood<Sp>(
&self,
space: &Sp,
state: &S,
radius: f64,
visible: impl Fn(&S) -> bool,
) -> (Vec<usize>, Vec<usize>)
where
Sp: StateSpace<State = S>,
N: NearestNeighbors<Sp>,
{
let near = self.near_sorted(space, state, radius);
let visible = near
.iter()
.copied()
.filter(|&id| visible(&self.states[id]))
.collect();
(near, visible)
}
pub(super) fn closest_visible<Sp>(
&self,
space: &Sp,
state: &S,
radius: f64,
visible: impl Fn(&S) -> bool,
) -> Option<usize>
where
Sp: StateSpace<State = S>,
N: NearestNeighbors<Sp>,
{
let near = self.near_sorted(space, state, radius);
near.into_iter().find(|&id| visible(&self.states[id]))
}
pub(super) fn query<Sp, C>(
&self,
space: &Sp,
checker: &C,
start: &S,
goal: &GoalRegion<S>,
radius: f64,
) -> Option<Path<S>>
where
Sp: StateSpace<State = S>,
C: ValidityChecker<Sp>,
N: NearestNeighbors<Sp>,
{
let n = self.len();
let (start_id, center_id) = (n, n + 1);
let center = goal.center();
let (_, from_start) = self.neighborhood(space, start, radius, |guard| {
checker.check_motion(space, start, guard).is_valid()
});
let mut to_center = alloc::vec![false; n];
if checker.check_state(center).is_valid() {
let mut near = Vec::new();
self.nn.within_radius(space, center, radius, &mut near);
for guard in near {
to_center[guard] = checker
.check_motion(space, &self.states[guard], center)
.is_valid();
}
}
let direct = space.distance(start, center) <= radius
&& checker.check_state(center).is_valid()
&& checker.check_motion(space, start, center).is_valid();
let state_of = |id: usize| match id {
id if id < n => &self.states[id],
id if id == start_id => start,
_ => center,
};
let arcs = |node: usize, out: &mut Vec<Arc>| {
out.clear();
let targets: Vec<usize> = if node == start_id {
from_start
.iter()
.copied()
.chain(direct.then_some(center_id))
.collect()
} else if node < n {
self.adjacency[node]
.iter()
.copied()
.chain(to_center[node].then_some(center_id))
.collect()
} else {
Vec::new()
};
out.extend(targets.into_iter().map(|to| Arc {
to,
cost: space.distance(state_of(node), state_of(to)),
edge: None,
}));
};
let is_goal = |id: usize| id == center_id || goal.contains(space, state_of(id));
let route = shortest_path(n + 2, start_id, is_goal, arcs)?;
Some(Path {
states: route.nodes.iter().map(|&id| state_of(id).clone()).collect(),
cost: route.cost,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn union_find_merges_components() {
let mut sets = UnionFind::default();
let ids: Vec<usize> = (0..5).map(|_| sets.push()).collect();
sets.union(ids[0], ids[1]);
sets.union(ids[3], ids[4]);
sets.union(ids[1], ids[4]);
assert_eq!(sets.find(ids[0]), sets.find(ids[3]));
assert_ne!(sets.find(ids[2]), sets.find(ids[0]));
}
}