use alloc::vec::Vec;
use rand_core::Rng;
use super::BitStarConfig;
use crate::radius::{dimension_f64, k_nearest_count, shrinking_radius};
use crate::trees::INFORMED_ATTEMPTS;
use crate::{GoalRegion, NearestNeighbors, Sampler, StateSpace, ValidityChecker};
#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) enum Neighborhood {
Radius(f64),
Nearest(usize),
}
impl Neighborhood {
pub(super) fn for_batch(config: &BitStarConfig, q: usize, dimension: usize) -> Self {
match config.k_nearest {
Some(k_constant) => Self::Nearest(k_nearest_count(k_constant, q)),
None => Self::Radius(
shrinking_radius(config.gamma, q, dimension_f64(dimension)).min(config.max_radius),
),
}
}
pub(super) fn query<Sp: StateSpace, N: NearestNeighbors<Sp>>(
self,
space: &Sp,
nn: &N,
state: &Sp::State,
keep: impl Fn(usize) -> bool,
out: &mut Vec<usize>,
) {
match self {
Self::Radius(radius) => nn.within_radius(space, state, radius, out),
Self::Nearest(k) => nn.k_nearest(space, state, k + 1, out),
}
out.retain(|&x| keep(x));
}
}
pub(super) struct Informed<'a, Sp: StateSpace, C> {
pub(super) space: &'a Sp,
pub(super) checker: &'a C,
pub(super) start: &'a Sp::State,
pub(super) goal: &'a GoalRegion<Sp::State>,
pub(super) best_cost: f64,
}
impl<Sp: StateSpace, C: ValidityChecker<Sp>> Informed<'_, Sp, C> {
pub(super) fn draw<Sa, R>(&self, sampler: &mut Sa, rng: &mut R) -> Option<Sp::State>
where
Sa: Sampler<Sp::State>,
R: Rng + ?Sized,
{
let bound = self.best_cost + self.goal.tolerance();
for _ in 0..INFORMED_ATTEMPTS {
let direct = if bound.is_finite() {
let center = self.goal.center();
sampler.sample_informed(self.space, rng, self.start, center, bound)
} else {
None
};
let state = direct.unwrap_or_else(|| sampler.sample(rng));
if self.is_useful(&state) {
return Some(state);
}
}
None
}
fn is_useful(&self, state: &Sp::State) -> bool {
let g_hat = self.space.distance(self.start, state);
let h_hat =
(self.space.distance(state, self.goal.center()) - self.goal.tolerance()).max(0.0);
g_hat + h_hat < self.best_cost && self.checker.check_state(state).is_valid()
}
}