mod forward;
mod reverse;
#[cfg(test)]
mod tests;
use alloc::{collections::BinaryHeap, vec::Vec};
use rand_core::Rng;
use super::batch::{Informed, Neighborhood};
use super::queues::{EdgeEntry, VertexEntry};
use super::{BitStarConfig, Error};
#[cfg(doc)]
use crate::trees::INFORMED_ATTEMPTS;
use crate::{GoalRegion, LinearScan, NearestNeighbors, Path, Sampler, StateSpace, ValidityChecker};
pub type AitStarConfig = BitStarConfig;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Kind {
Vertex,
Sample,
Pruned,
}
#[derive(Debug, Clone)]
struct Node<S> {
state: S,
kind: Kind,
g: f64,
g_hat: f64,
h_hat: f64,
parent: Option<usize>,
children: Vec<usize>,
h_con: f64,
h_exp: f64,
reverse_key: Option<[f64; 2]>,
incoming: Vec<(usize, [f64; 3])>,
adjacent: Vec<usize>,
invalid: Vec<usize>,
}
impl<S> Node<S> {
fn f_hat(&self) -> f64 {
self.g_hat + self.h_hat
}
fn in_goal(&self) -> bool {
self.h_hat <= 0.0
}
}
#[derive(Debug, Clone)]
pub struct AitStar<Sp: StateSpace, Sa, C, N = LinearScan<<Sp as StateSpace>::State>> {
space: Sp,
sampler: Sa,
checker: C,
start: Sp::State,
goal: GoalRegion<Sp::State>,
config: AitStarConfig,
nodes: Vec<Node<Sp::State>>,
prototype: N,
nn: N,
forward_queue: BinaryHeap<EdgeEntry>,
reverse_queue: BinaryHeap<VertexEntry>,
stale_keys: bool,
solutions: Vec<usize>,
best_cost: f64,
neighborhood: Neighborhood,
batches: usize,
}
const START: usize = 0;
impl<Sp, Sa, C> AitStar<Sp, Sa, C>
where
Sp: StateSpace,
Sa: Sampler<Sp::State>,
C: ValidityChecker<Sp>,
{
pub fn new(
space: Sp,
sampler: Sa,
checker: C,
start: Sp::State,
goal: GoalRegion<Sp::State>,
config: AitStarConfig,
) -> Result<Self, Error> {
Self::with_nearest_neighbors(
space,
sampler,
checker,
start,
goal,
config,
LinearScan::default(),
)
}
}
impl<Sp, Sa, C, N> AitStar<Sp, Sa, C, N>
where
Sp: StateSpace,
Sa: Sampler<Sp::State>,
C: ValidityChecker<Sp>,
N: NearestNeighbors<Sp> + Clone,
{
pub fn with_nearest_neighbors(
space: Sp,
sampler: Sa,
checker: C,
start: Sp::State,
goal: GoalRegion<Sp::State>,
config: AitStarConfig,
nn: N,
) -> Result<Self, Error> {
config.validate()?;
let validity = checker.check_state(&start);
if !validity.is_valid() {
return Err(Error::InvalidStart(validity));
}
let mut planner = Self {
space,
sampler,
checker,
start: start.clone(),
goal,
config,
nodes: Vec::new(),
nn: nn.clone(),
prototype: nn,
forward_queue: BinaryHeap::new(),
reverse_queue: BinaryHeap::new(),
stale_keys: false,
solutions: Vec::new(),
best_cost: f64::INFINITY,
neighborhood: Neighborhood::Radius(0.0),
batches: 0,
};
planner.plant_root(start);
Ok(planner)
}
fn plant_root(&mut self, start: Sp::State) {
let root = self.push_node(start, Kind::Vertex);
self.nodes[root].g = 0.0;
if self.nodes[root].in_goal() {
self.solutions.push(root);
self.best_cost = 0.0;
}
let center = self.goal.center().clone();
if self.checker.check_state(¢er).is_valid() {
self.push_node(center, Kind::Sample);
}
}
fn push_node(&mut self, state: Sp::State, kind: Kind) -> usize {
let id = self.nodes.len();
let center_distance = self.space.distance(&state, self.goal.center());
self.nodes.push(Node {
g_hat: self.space.distance(&self.start, &state),
h_hat: (center_distance - self.goal.tolerance()).max(0.0),
g: f64::INFINITY,
state,
kind,
parent: None,
children: Vec::new(),
h_con: f64::INFINITY,
h_exp: f64::INFINITY,
reverse_key: None,
incoming: Vec::new(),
adjacent: Vec::new(),
invalid: Vec::new(),
});
id
}
pub fn step<R: Rng + ?Sized>(&mut self, rng: &mut R) -> bool {
self.resort_if_stale();
if self.peek_edge().is_none() {
self.start_batch(rng);
}
self.advance_reverse_search();
match self.pop_edge() {
Some(edge) => self.process_edge(edge),
None => false,
}
}
pub fn run<R: Rng + ?Sized>(&mut self, iterations: usize, rng: &mut R) {
for _ in 0..iterations {
self.step(rng);
}
}
fn start_batch<R: Rng + ?Sized>(&mut self, rng: &mut R) {
self.batches += 1;
self.clear_forward_queue();
if self.best_cost.is_finite() {
self.prune();
}
let sampled = self.sample_batch(rng);
self.reindex(sampled);
self.build_graph();
self.restart_reverse_search();
self.expand(START);
}
fn prune(&mut self) {
let c = self.best_cost;
for node in &mut self.nodes {
if node.kind == Kind::Sample && node.f_hat() >= c {
node.kind = Kind::Pruned;
}
}
let mut vertices: Vec<usize> = (0..self.nodes.len())
.filter(|&id| self.nodes[id].kind == Kind::Vertex)
.collect();
vertices.sort_by(|&a, &b| self.nodes[a].g.total_cmp(&self.nodes[b].g).then(a.cmp(&b)));
for v in vertices {
let node = &self.nodes[v];
if node.kind == Kind::Vertex && (node.f_hat() > c || node.g + node.h_hat > c) {
self.disconnect(v);
}
}
for v in 1..self.nodes.len() {
if self.nodes[v].kind == Kind::Vertex && self.nodes[v].parent.is_none() {
self.disconnect(v);
}
}
self.solutions
.retain(|&id| self.nodes[id].kind == Kind::Vertex);
}
fn disconnect(&mut self, v: usize) {
if let Some(parent) = self.nodes[v].parent.take() {
self.nodes[parent].children.retain(|&child| child != v);
}
let recycle = self.nodes[v].f_hat() < self.best_cost;
let node = &mut self.nodes[v];
node.kind = if recycle { Kind::Sample } else { Kind::Pruned };
node.g = f64::INFINITY;
for child in core::mem::take(&mut node.children) {
self.nodes[child].parent = None;
}
}
fn sample_batch<R: Rng + ?Sized>(&mut self, rng: &mut R) -> usize {
let mut added = 0;
for _ in 0..self.config.batch_size {
let informed = Informed {
space: &self.space,
checker: &self.checker,
start: &self.start,
goal: &self.goal,
best_cost: self.best_cost,
};
if let Some(state) = informed.draw(&mut self.sampler, rng) {
self.push_node(state, Kind::Sample);
added += 1;
}
}
added
}
fn reindex(&mut self, sampled: usize) {
self.nn = self.prototype.clone();
let mut live: usize = 0;
for (id, node) in self.nodes.iter().enumerate() {
if node.kind != Kind::Pruned {
self.nn.insert(id, node.state.clone());
live += 1;
}
}
let q = live.saturating_sub(sampled).max(2);
self.neighborhood = Neighborhood::for_batch(&self.config, q, self.space.dimension());
}
fn build_graph(&mut self) {
let mut near = Vec::new();
for node in &mut self.nodes {
node.adjacent.clear();
}
for id in 0..self.nodes.len() {
if self.nodes[id].kind == Kind::Pruned {
continue;
}
let cap = self.config.max_radius;
let keep = |x| x != id && (cap.is_infinite() || self.cost_estimate(id, x) <= cap);
self.neighborhood.query(
&self.space,
&self.nn,
&self.nodes[id].state,
keep,
&mut near,
);
self.link_all(id, &near);
if let Some(parent) = self.nodes[id].parent {
self.link_all(id, &[parent]);
}
}
for node in &mut self.nodes {
node.adjacent.sort_unstable();
node.adjacent.dedup();
}
}
fn link_all(&mut self, id: usize, others: &[usize]) {
for &other in others {
self.nodes[id].adjacent.push(other);
self.nodes[other].adjacent.push(id);
}
}
fn cost_estimate(&self, from: usize, to: usize) -> f64 {
self.space
.distance(&self.nodes[from].state, &self.nodes[to].state)
}
fn is_invalid(&self, from: usize, to: usize) -> bool {
self.nodes[from].invalid.contains(&to)
}
#[must_use]
pub fn best_path(&self) -> Option<Path<Sp::State>> {
let best = self
.solutions
.iter()
.copied()
.min_by(|&a, &b| self.nodes[a].g.total_cmp(&self.nodes[b].g).then(a.cmp(&b)))?;
let mut states = Vec::new();
let mut current = Some(best);
while let Some(id) = current {
states.push(self.nodes[id].state.clone());
current = self.nodes[id].parent;
}
states.reverse();
Some(Path {
states,
cost: self.nodes[best].g,
})
}
#[must_use]
pub fn vertex_count(&self) -> usize {
self.count(Kind::Vertex)
}
#[must_use]
pub fn sample_count(&self) -> usize {
self.count(Kind::Sample)
}
#[must_use]
pub const fn batch_count(&self) -> usize {
self.batches
}
fn count(&self, kind: Kind) -> usize {
self.nodes.iter().filter(|node| node.kind == kind).count()
}
}