use alloc::{collections::BinaryHeap, vec::Vec};
use rand_core::Rng;
use super::Error;
use super::batch::{Informed, Neighborhood};
use super::queues::{EdgeEntry, VertexEntry};
use crate::radius::k_constant_lower_bound;
#[cfg(doc)]
use crate::trees::INFORMED_ATTEMPTS;
use crate::trees::RrtStarConfig;
use crate::{GoalRegion, LinearScan, NearestNeighbors, Path, Sampler, StateSpace, ValidityChecker};
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct BitStarConfig {
pub batch_size: usize,
pub gamma: f64,
pub k_nearest: Option<f64>,
pub max_radius: f64,
}
impl BitStarConfig {
#[must_use]
pub const fn new(gamma: f64) -> Self {
Self {
batch_size: 100,
gamma,
k_nearest: None,
max_radius: f64::INFINITY,
}
}
#[must_use]
pub fn gamma_lower_bound(dimension: usize, free_volume: f64) -> f64 {
RrtStarConfig::gamma_lower_bound(dimension, free_volume)
}
#[must_use]
pub fn k_constant_lower_bound(dimension: usize) -> f64 {
k_constant_lower_bound(dimension)
}
pub(super) fn validate(&self) -> Result<(), Error> {
let constant = self.k_nearest.unwrap_or(self.gamma);
if self.batch_size == 0 {
return Err(Error::EmptyBatch);
}
if !(constant.is_finite() && constant > 0.0)
|| self.max_radius.is_nan()
|| self.max_radius <= 0.0
{
return Err(Error::InvalidRadius);
}
Ok(())
}
}
#[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>,
unexpanded: bool,
fresh: bool,
queued: bool,
}
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 BitStar<Sp: StateSpace, Sa, C, N = LinearScan<<Sp as StateSpace>::State>> {
space: Sp,
sampler: Sa,
checker: C,
start: Sp::State,
goal: GoalRegion<Sp::State>,
config: BitStarConfig,
nodes: Vec<Node<Sp::State>>,
prototype: N,
nn: N,
vertex_queue: BinaryHeap<VertexEntry>,
edge_queue: BinaryHeap<EdgeEntry>,
stale_keys: bool,
solutions: Vec<usize>,
best_cost: f64,
neighborhood: Neighborhood,
batches: usize,
near: Vec<usize>,
}
impl<Sp, Sa, C> BitStar<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: BitStarConfig,
) -> Result<Self, Error> {
Self::with_nearest_neighbors(
space,
sampler,
checker,
start,
goal,
config,
LinearScan::default(),
)
}
}
impl<Sp, Sa, C, N> BitStar<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: BitStarConfig,
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,
vertex_queue: BinaryHeap::new(),
edge_queue: BinaryHeap::new(),
stale_keys: false,
solutions: Vec::new(),
best_cost: f64::INFINITY,
neighborhood: Neighborhood::Radius(0.0),
batches: 0,
near: Vec::new(),
};
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;
self.nodes[root].unexpanded = true;
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(),
unexpanded: false,
fresh: true,
queued: false,
});
id
}
pub fn step<R: Rng + ?Sized>(&mut self, rng: &mut R) -> bool {
if self.vertex_queue.is_empty() && self.edge_queue.is_empty() {
self.start_batch(rng);
}
self.resort_if_stale();
while self.best_vertex_value() <= self.best_edge_value() {
if !self.expand_next_vertex() {
break;
}
}
match self.edge_queue.pop() {
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;
for node in &mut self.nodes {
node.fresh = false;
}
if self.best_cost.is_finite() {
self.prune();
}
let sampled = self.sample_batch(rng);
self.reindex(sampled);
for id in 0..self.nodes.len() {
if self.nodes[id].kind == Kind::Vertex {
self.queue_vertex(id);
}
}
}
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;
node.fresh = recycle;
node.unexpanded = false;
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 queue_vertex(&mut self, v: usize) {
let node = &mut self.nodes[v];
node.queued = true;
self.vertex_queue.push(VertexEntry {
key: node.g + node.h_hat,
cost: node.g,
vertex: v,
});
}
fn resort_if_stale(&mut self) {
if !self.stale_keys {
return;
}
self.stale_keys = false;
let vertices: Vec<usize> = self
.vertex_queue
.drain()
.map(|entry| entry.vertex)
.collect();
for v in vertices {
if self.nodes[v].queued && self.nodes[v].kind == Kind::Vertex {
self.nodes[v].queued = false;
self.queue_vertex(v);
}
}
let edges: Vec<EdgeEntry> = self.edge_queue.drain().collect();
for edge in edges {
self.queue_edge(edge.from, edge.to);
}
}
fn best_vertex_value(&mut self) -> f64 {
while let Some(entry) = self.vertex_queue.peek() {
let node = &self.nodes[entry.vertex];
if node.queued && node.kind == Kind::Vertex {
return entry.key;
}
self.vertex_queue.pop();
}
f64::INFINITY
}
fn best_edge_value(&self) -> f64 {
self.edge_queue
.peek()
.map_or(f64::INFINITY, |edge| edge.key[0])
}
fn expand_next_vertex(&mut self) -> bool {
let Some(entry) = self.vertex_queue.pop() else {
return false;
};
let v = entry.vertex;
if !self.nodes[v].queued || self.nodes[v].kind != Kind::Vertex {
return true;
}
self.nodes[v].queued = false;
let mut near = core::mem::take(&mut self.near);
self.neighbors(v, &mut near);
let unexpanded = self.nodes[v].unexpanded;
for &x in &near {
if self.is_sample_edge_candidate(v, x, unexpanded)
|| self.is_rewire_candidate(v, x, unexpanded)
{
self.queue_edge(v, x);
}
}
self.nodes[v].unexpanded = false;
self.near = near;
true
}
fn is_sample_edge_candidate(&self, v: usize, x: usize, unexpanded: bool) -> bool {
let target = &self.nodes[x];
target.kind == Kind::Sample
&& (unexpanded || target.fresh)
&& self.nodes[v].g_hat + self.edge_estimate(v, x) + target.h_hat < self.best_cost
}
fn is_rewire_candidate(&self, v: usize, w: usize, unexpanded: bool) -> bool {
let target = &self.nodes[w];
let through = self.nodes[v].g_hat + self.edge_estimate(v, w);
unexpanded
&& target.kind == Kind::Vertex
&& w != v
&& target.parent != Some(v)
&& through + target.h_hat < self.best_cost
&& through < target.g
}
fn neighbors(&self, v: usize, out: &mut Vec<usize>) {
let cap = self.config.max_radius;
let keep = |x| x != v && (cap.is_infinite() || self.edge_estimate(v, x) <= cap);
self.neighborhood
.query(&self.space, &self.nn, &self.nodes[v].state, keep, out);
}
fn edge_estimate(&self, v: usize, x: usize) -> f64 {
self.space
.distance(&self.nodes[v].state, &self.nodes[x].state)
}
fn queue_edge(&mut self, v: usize, x: usize) {
let g = self.nodes[v].g;
let through = g + self.edge_estimate(v, x);
self.edge_queue.push(EdgeEntry {
key: [through + self.nodes[x].h_hat, through, g],
from: v,
to: x,
});
}
fn process_edge(&mut self, edge: EdgeEntry) -> bool {
let (v, x) = (edge.from, edge.to);
if self.nodes[v].kind != Kind::Vertex || self.nodes[x].kind == Kind::Pruned {
return false;
}
let g_v = self.nodes[v].g;
let estimate = g_v + self.edge_estimate(v, x);
if estimate + self.nodes[x].h_hat >= self.best_cost {
self.vertex_queue.clear();
self.edge_queue.clear();
return false;
}
if estimate >= self.nodes[x].g || !self.is_motion_valid(v, x) {
return false;
}
self.connect(v, x, estimate);
true
}
fn is_motion_valid(&self, from: usize, to: usize) -> bool {
self.checker
.check_motion(&self.space, &self.nodes[from].state, &self.nodes[to].state)
.is_valid()
}
fn connect(&mut self, v: usize, x: usize, g: f64) {
if let Some(old) = self.nodes[x].parent {
self.nodes[old].children.retain(|&child| child != x);
self.stale_keys = true;
}
let was_sample = self.nodes[x].kind == Kind::Sample;
let node = &mut self.nodes[x];
node.parent = Some(v);
node.g = g;
self.nodes[v].children.push(x);
if was_sample {
let node = &mut self.nodes[x];
node.kind = Kind::Vertex;
node.unexpanded = true;
self.queue_vertex(x);
if self.nodes[x].in_goal() {
self.solutions.push(x);
}
} else {
self.propagate_costs(x);
}
self.update_best_cost();
}
fn propagate_costs(&mut self, x: usize) {
let mut stack = self.nodes[x].children.clone();
while let Some(child) = stack.pop() {
let parent = self.nodes[child].parent.expect("a child has a parent");
self.nodes[child].g = self.nodes[parent].g + self.edge_estimate(parent, child);
stack.extend_from_slice(&self.nodes[child].children);
}
}
fn update_best_cost(&mut self) {
self.best_cost = self
.solutions
.iter()
.map(|&id| self.nodes[id].g)
.fold(f64::INFINITY, f64::min);
}
#[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()
}
}