mod grid;
use alloc::vec::Vec;
use rand_core::Rng;
use super::{Error, KinodynamicProblem, Propagator, Trajectory, sst::random_step_count};
use crate::radius::count_to_f64;
use crate::{StateSpace, ValidityChecker, unit_f64};
use grid::Grid;
pub trait Projection<S, const K: usize> {
fn project(&self, state: &S) -> [f64; K];
}
impl<S, const K: usize, F: Fn(&S) -> [f64; K]> Projection<S, K> for F {
fn project(&self, state: &S) -> [f64; K] {
self(state)
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct KpieceConfig<const K: usize> {
pub cell_size: [f64; K],
pub step_size: f64,
pub max_steps: usize,
pub min_steps: usize,
pub goal_bias: f64,
pub exterior_bias: f64,
pub good_score_factor: f64,
pub bad_score_factor: f64,
pub close_samples: usize,
}
impl<const K: usize> KpieceConfig<K> {
#[must_use]
pub const fn new(cell_size: [f64; K], step_size: f64, max_steps: usize) -> Self {
Self {
cell_size,
step_size,
max_steps,
min_steps: 1,
goal_bias: 0.05,
exterior_bias: 0.8,
good_score_factor: 0.9,
bad_score_factor: 0.45,
close_samples: 30,
}
}
fn validate(&self) -> Result<(), Error> {
let positive = |value: f64| value.is_finite() && value > 0.0;
let factor = |value: f64| value > 0.0 && value <= 1.0;
let probability = |value: f64| (0.0..=1.0).contains(&value);
if !probability(self.goal_bias) {
return Err(Error::GoalBiasOutOfRange);
}
if !self.cell_size.iter().all(|&size| positive(size)) {
return Err(Error::InvalidRadius);
}
if !positive(self.step_size) || self.min_steps == 0 || self.max_steps < self.min_steps {
return Err(Error::InvalidPropagation);
}
let scores = factor(self.good_score_factor) && factor(self.bad_score_factor);
if !(scores && probability(self.exterior_bias)) {
return Err(Error::InvalidSchedule);
}
Ok(())
}
}
#[derive(Debug, Clone)]
struct Motion<S, U> {
state: S,
parent: Option<usize>,
control: Option<(U, f64)>,
cost: f64,
cell: usize,
}
#[derive(Clone)]
pub struct Kpiece<Sp, Sa, C, P, Pr, const K: usize>
where
Sp: StateSpace,
P: Propagator<Sp>,
{
problem: KinodynamicProblem<Sp, Sa, C, P>,
projection: Pr,
config: KpieceConfig<K>,
motions: Vec<Motion<Sp::State, P::Control>>,
grid: Grid<K>,
close: Vec<(f64, usize)>,
solution: Option<usize>,
iteration: usize,
}
impl<Sp, Sa, C, P, Pr, const K: usize> Kpiece<Sp, Sa, C, P, Pr, K>
where
Sp: StateSpace,
C: ValidityChecker<Sp>,
P: Propagator<Sp>,
Pr: Projection<Sp::State, K>,
{
pub fn new(
problem: KinodynamicProblem<Sp, Sa, C, P>,
projection: Pr,
config: KpieceConfig<K>,
) -> Result<Self, Error> {
config.validate()?;
let validity = problem.checker.check_state(&problem.start);
if !validity.is_valid() {
return Err(Error::InvalidStart(validity));
}
let mut planner = Self {
problem,
projection,
config,
motions: Vec::new(),
grid: Grid::new(),
close: Vec::new(),
solution: None,
iteration: 1,
};
let start = planner.problem.start.clone();
planner.add_motion(start, None, None, 0.0, 0);
Ok(planner)
}
pub fn solve<R: Rng + ?Sized>(
&mut self,
max_iterations: usize,
rng: &mut R,
) -> Option<Trajectory<Sp::State, P::Control>> {
for _ in 0..max_iterations {
if self.solution.is_some() {
break;
}
self.step(rng);
}
self.best_trajectory()
}
pub fn step<R: Rng + ?Sized>(&mut self, rng: &mut R) -> bool {
self.iteration += 1;
let (from, cell) = self.choose_motion(rng);
let control = self.problem.propagator.sample_control(rng);
let steps = random_step_count(self.config.max_steps, rng);
let states = self.propagate_while_valid(from, &control, steps);
let good = states.len() >= self.config.min_steps;
let added = good && self.add_if_interesting(from, &control, &states, rng);
self.rescore(cell, good);
added
}
fn choose_motion<R: Rng + ?Sized>(&mut self, rng: &mut R) -> (usize, usize) {
if !self.close.is_empty() && unit_f64(rng) < self.config.goal_bias {
let motion = self.take_close_sample();
return (motion, self.motions[motion].cell);
}
let exterior = unit_f64(rng) < self.config.exterior_bias.max(self.grid.exterior_fraction());
let cell = self
.grid
.select(exterior)
.expect("the start cell always exists");
if self.grid.cells[cell].score < f64::EPSILON {
self.grid.refresh_scores();
}
let entry = &mut self.grid.cells[cell];
entry.selections += 1.0;
let pick = half_normal_index(entry.motions.len(), rng);
(entry.motions[pick], cell)
}
fn take_close_sample(&mut self) -> usize {
let (best, motion) = self.close.remove(0);
let worst = self.close.last().map_or(best, |&(distance, _)| distance);
self.insert_close(0.55 * (best + worst), motion);
motion
}
fn propagate_while_valid(
&self,
from: usize,
control: &P::Control,
steps: usize,
) -> Vec<Sp::State> {
let (space, propagator) = (&self.problem.space, &self.problem.propagator);
let mut states: Vec<Sp::State> = Vec::new();
let mut state = self.motions[from].state.clone();
for _ in 0..steps {
let next = propagator.propagate(space, &state, control, self.config.step_size);
if !self
.problem
.checker
.check_motion(space, &state, &next)
.is_valid()
{
break;
}
states.push(next.clone());
state = next;
}
states
}
fn add_if_interesting<R: Rng + ?Sized>(
&mut self,
from: usize,
control: &P::Control,
states: &[Sp::State],
rng: &mut R,
) -> bool {
let coords: Vec<[i64; K]> = states.iter().map(|state| self.coordinates(state)).collect();
if !self.is_interesting(&coords) && unit_f64(rng) >= 0.05 {
return false;
}
let mut parent = from;
let mut start = 0;
while start < states.len() {
let end = run_end(&coords, start);
let duration = count_to_f64(end - start) * self.config.step_size;
let cost = self.motions[parent].cost + duration;
let cell = self.cell_for(coords[start], &states[end - 1]);
parent = self.add_motion(
states[end - 1].clone(),
Some(parent),
Some((control.clone(), duration)),
cost,
cell,
);
self.grid.cells[cell].coverage += count_to_f64(end - start);
start = end;
}
true
}
fn is_interesting(&self, coords: &[[i64; K]]) -> bool {
let threshold = 2 * self.motions.len() / (3 * self.grid.cells.len());
coords.iter().any(|coord| {
self.grid
.find(coord)
.is_none_or(|cell| self.grid.cells[cell].motions.len() <= threshold)
})
}
fn cell_for(&mut self, coord: [i64; K], state: &Sp::State) -> usize {
if let Some(cell) = self.grid.find(&coord) {
return cell;
}
let score =
(1.0 + libm::log(count_to_f64(self.iteration))) / (1e-3 + self.goal_distance(state));
self.grid.add(coord, self.iteration, score)
}
fn add_motion(
&mut self,
state: Sp::State,
parent: Option<usize>,
control: Option<(P::Control, f64)>,
cost: f64,
cell: usize,
) -> usize {
let id = self.motions.len();
let distance = self.goal_distance(&state);
let cell = if parent.is_none() {
let coord = self.coordinates(&state);
let cell = self.cell_for(coord, &state);
self.grid.cells[cell].coverage = 1.0;
cell
} else {
cell
};
if distance <= 0.0 && self.solution.is_none() {
self.solution = Some(id);
}
self.grid.cells[cell].motions.push(id);
self.insert_close(distance, id);
self.motions.push(Motion {
state,
parent,
control,
cost,
cell,
});
id
}
fn insert_close(&mut self, distance: f64, motion: usize) {
let at = self.close.partition_point(|&(other, _)| other <= distance);
if at < self.config.close_samples {
self.close.insert(at, (distance, motion));
self.close.truncate(self.config.close_samples);
}
}
fn rescore(&mut self, cell: usize, good: bool) {
self.grid.cells[cell].score *= if good {
self.config.good_score_factor
} else {
self.config.bad_score_factor
};
}
fn coordinates(&self, state: &Sp::State) -> [i64; K] {
let point = self.projection.project(state);
core::array::from_fn(|axis| cell_index(point[axis] / self.config.cell_size[axis]))
}
fn goal_distance(&self, state: &Sp::State) -> f64 {
let goal = &self.problem.goal;
(self.problem.space.distance(state, goal.center()) - goal.tolerance()).max(0.0)
}
#[must_use]
pub fn best_trajectory(&self) -> Option<Trajectory<Sp::State, P::Control>> {
let goal = self.solution?;
let mut states = Vec::new();
let mut controls = Vec::new();
let mut current = Some(goal);
while let Some(id) = current {
let motion = &self.motions[id];
states.push(motion.state.clone());
controls.extend(motion.control.clone());
current = motion.parent;
}
states.reverse();
controls.reverse();
Some(Trajectory {
states,
controls,
cost: self.motions[goal].cost,
})
}
#[must_use]
pub fn motion_count(&self) -> usize {
self.motions.len()
}
#[must_use]
pub fn cell_count(&self) -> usize {
self.grid.cells.len()
}
}
fn run_end<const K: usize>(coords: &[[i64; K]], start: usize) -> usize {
coords[start..]
.iter()
.position(|coord| *coord != coords[start])
.map_or(coords.len(), |offset| start + offset)
}
#[expect(
clippy::cast_possible_truncation,
reason = "float-to-int casts saturate, which is the intended clamping"
)]
fn cell_index(scaled: f64) -> i64 {
libm::floor(scaled) as i64
}
fn half_normal_index<R: Rng + ?Sized>(len: usize, rng: &mut R) -> usize {
let mean = count_to_f64(len);
let mut v = mean + mean / 3.0 * standard_normal(rng);
if v > mean {
v = 2.0 * mean - v;
}
let value = libm::floor(v.max(0.0));
let index = if value >= mean {
len - 1
} else {
#[expect(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
reason = "value is a whole number in [0, len) after the guards above"
)]
let index = value as usize;
index
};
index.min(len - 1)
}
fn standard_normal<R: Rng + ?Sized>(rng: &mut R) -> f64 {
let radius = libm::sqrt(-2.0 * libm::log(1.0 - unit_f64(rng)));
radius * libm::cos(2.0 * core::f64::consts::PI * unit_f64(rng))
}
#[cfg(test)]
mod tests {
use super::*;
use rand_core::SeedableRng;
#[test]
fn half_normal_indices_stay_in_range_and_favor_the_newest() {
let mut rng = rand_pcg::Pcg64Mcg::seed_from_u64(1);
let mut counts = [0_u32; 10];
for _ in 0..10_000 {
counts[half_normal_index(10, &mut rng)] += 1;
}
assert!(counts[9] > counts[5] && counts[5] > counts[0], "{counts:?}");
assert_eq!(half_normal_index(1, &mut rng), 0);
}
#[test]
fn runs_split_at_cell_changes() {
let coords = [[0], [0], [1], [1], [1], [0]];
assert_eq!(run_end(&coords, 0), 2);
assert_eq!(run_end(&coords, 2), 5);
assert_eq!(run_end(&coords, 5), 6);
assert_eq!(cell_index(-0.5), -1);
assert_eq!(cell_index(f64::NAN), 0);
}
}