sampling_planning/kinodynamic/kpiece.rs
1//! KPIECE: kinodynamic planning by interior-exterior cell exploration (Sucan and Kavraki).
2
3mod grid;
4
5use alloc::vec::Vec;
6
7use rand_core::Rng;
8
9use super::{Error, KinodynamicProblem, Propagator, Trajectory, sst::random_step_count};
10use crate::radius::count_to_f64;
11use crate::{StateSpace, ValidityChecker, unit_f64};
12use grid::Grid;
13
14/// Maps a state to a point in a low-dimensional projection space, where KPIECE lays its grid.
15///
16/// A good projection keeps the coordinates that tell progress apart (the position of a robot,
17/// not its velocity). Any `Fn(&S) -> [f64; K]` closure is a projection.
18pub trait Projection<S, const K: usize> {
19 /// The projection of `state`.
20 fn project(&self, state: &S) -> [f64; K];
21}
22
23impl<S, const K: usize, F: Fn(&S) -> [f64; K]> Projection<S, K> for F {
24 fn project(&self, state: &S) -> [f64; K] {
25 self(state)
26 }
27}
28
29/// Settings for [`Kpiece`]. The defaults follow OMPL's `control::KPIECE1`.
30#[derive(Debug, Clone, Copy, PartialEq)]
31pub struct KpieceConfig<const K: usize> {
32 /// The edge lengths of a grid cell in projection space. Positive and finite.
33 pub cell_size: [f64; K],
34 /// The integration step: every propagation is a sequence of steps of this duration, each
35 /// checked with [`ValidityChecker::check_motion`]. Positive and finite.
36 pub step_size: f64,
37 /// The most integration steps per propagation; the step count is uniform in
38 /// `1..=max_steps`. At least `min_steps`.
39 pub max_steps: usize,
40 /// The fewest valid steps for a propagation to count; shorter ones are discarded and
41 /// penalize their cell. At least one.
42 pub min_steps: usize,
43 /// Probability in `[0, 1]` of expanding one of the motions closest to the goal instead of
44 /// a grid selection. 5 % by default.
45 pub goal_bias: f64,
46 /// The least probability of selecting an exterior cell; the share of exterior cells is used
47 /// when it is higher. In `[0, 1]`; 0.8 by default (the paper suggests 0.7 to 0.8).
48 pub exterior_bias: f64,
49 /// The factor applied to a cell's score after a successful expansion. In `(0, 1]`; 0.9 by
50 /// default.
51 pub good_score_factor: f64,
52 /// The factor applied after a failed expansion. In `(0, 1]`; 0.45 by default.
53 pub bad_score_factor: f64,
54 /// How many motions closest to the goal the goal bias chooses from. 30 by default.
55 pub close_samples: usize,
56}
57
58impl<const K: usize> KpieceConfig<K> {
59 /// A config with the given cell size, integration step and step range `1..=max_steps`, and
60 /// OMPL's defaults for the rest.
61 #[must_use]
62 pub const fn new(cell_size: [f64; K], step_size: f64, max_steps: usize) -> Self {
63 Self {
64 cell_size,
65 step_size,
66 max_steps,
67 min_steps: 1,
68 goal_bias: 0.05,
69 exterior_bias: 0.8,
70 good_score_factor: 0.9,
71 bad_score_factor: 0.45,
72 close_samples: 30,
73 }
74 }
75
76 /// Checks every field against its documented range.
77 fn validate(&self) -> Result<(), Error> {
78 let positive = |value: f64| value.is_finite() && value > 0.0;
79 let factor = |value: f64| value > 0.0 && value <= 1.0;
80 let probability = |value: f64| (0.0..=1.0).contains(&value);
81
82 if !probability(self.goal_bias) {
83 return Err(Error::GoalBiasOutOfRange);
84 }
85
86 if !self.cell_size.iter().all(|&size| positive(size)) {
87 return Err(Error::InvalidRadius);
88 }
89
90 if !positive(self.step_size) || self.min_steps == 0 || self.max_steps < self.min_steps {
91 return Err(Error::InvalidPropagation);
92 }
93
94 let scores = factor(self.good_score_factor) && factor(self.bad_score_factor);
95 if !(scores && probability(self.exterior_bias)) {
96 return Err(Error::InvalidSchedule);
97 }
98
99 Ok(())
100 }
101}
102
103/// One tree edge: a constant control applied for a number of steps, ending in one cell.
104#[derive(Debug, Clone)]
105struct Motion<S, U> {
106 /// The state reached at the end of the motion.
107 state: S,
108 /// The motion this one continues; `None` only for the start.
109 parent: Option<usize>,
110 /// The control and its duration; `None` only for the start.
111 control: Option<(U, f64)>,
112 /// The total duration from the start.
113 cost: f64,
114 /// The grid cell of `state`.
115 cell: usize,
116}
117
118/// KPIECE: grows a tree of motions by forward propagation, guided by a grid over a projection
119/// of the state space (Sucan and Kavraki 2008, 2012).
120///
121/// Each motion's end state falls into a grid cell. Cells with all `2K` axis neighbors are
122/// interior, the others exterior, the frontier of exploration. Each iteration:
123///
124/// ```mermaid
125/// graph LR
126/// Select["select cell: exterior with prob. max(bias, share)"] --> Motion["pick motion, newest preferred"]
127/// Motion --> Propagate["random control, random steps, stop at first invalid step"]
128/// Propagate -->|long enough| Split["split at cell changes, add pieces"]
129/// Propagate --> Score["scale cell score by good or bad factor"]
130/// ```
131///
132/// Cells are ranked by importance `score / ((neighbors + 1) coverage selections)`; a new cell
133/// starts with score `(1 + ln i) / (1e-3 + goal distance)`. Within a cell, motions are picked
134/// from a half-normal distribution centered on the newest one. This follows OMPL's
135/// `control::KPIECE1` with a single grid level, which also expands from the end state of the
136/// chosen motion rather than a random state along it. With probability `goal_bias` one of the
137/// `close_samples` motions closest to the goal is expanded instead.
138///
139/// KPIECE is probabilistically complete but not asymptotically optimal: [`Kpiece::solve`]
140/// stops at the first motion that reaches the goal region. It needs no state sampler; the
141/// problem's sampler is not used.
142///
143/// # Examples
144///
145/// ```
146/// use rand_core::{Rng, SeedableRng};
147/// use sampling_planning::{
148/// Euclidean, GoalRegion, UniformBox, Validity, ValidityChecker, unit_f64,
149/// kinodynamic::{KinodynamicProblem, Kpiece, KpieceConfig, Propagator},
150/// };
151///
152/// /// Free space everywhere.
153/// struct Free;
154///
155/// impl ValidityChecker<Euclidean<2>> for Free {
156/// fn check_state(&self, _: &[f64; 2]) -> Validity {
157/// Validity::Valid
158/// }
159///
160/// fn check_motion(&self, _: &Euclidean<2>, _: &[f64; 2], _: &[f64; 2]) -> Validity {
161/// Validity::Valid
162/// }
163/// }
164///
165/// /// A point that moves with a velocity of at most 1 per axis.
166/// struct Velocity;
167///
168/// impl Propagator<Euclidean<2>> for Velocity {
169/// type Control = [f64; 2];
170///
171/// fn control_dimension(&self) -> usize {
172/// 2
173/// }
174///
175/// fn sample_control<R: Rng + ?Sized>(&mut self, rng: &mut R) -> [f64; 2] {
176/// [2.0 * unit_f64(rng) - 1.0, 2.0 * unit_f64(rng) - 1.0]
177/// }
178///
179/// fn propagate(&self, _: &Euclidean<2>, from: &[f64; 2], u: &[f64; 2], dt: f64) -> [f64; 2] {
180/// [from[0] + u[0] * dt, from[1] + u[1] * dt]
181/// }
182/// }
183///
184/// let problem = KinodynamicProblem {
185/// space: Euclidean::<2>,
186/// sampler: UniformBox::new([0.0, 0.0], [10.0, 10.0]),
187/// checker: Free,
188/// propagator: Velocity,
189/// start: [1.0, 1.0],
190/// goal: GoalRegion::new([9.0, 9.0], 0.5),
191/// };
192///
193/// // The identity projection with half-unit cells.
194/// let projection = |state: &[f64; 2]| *state;
195/// let config = KpieceConfig::new([0.5, 0.5], 0.1, 10);
196/// let mut kpiece = Kpiece::new(problem, projection, config).expect("valid");
197///
198/// let trajectory = kpiece
199/// .solve(20_000, &mut rand_pcg::Pcg64Mcg::seed_from_u64(1))
200/// .expect("free space");
201/// assert_eq!(trajectory.controls.len() + 1, trajectory.states.len());
202/// ```
203#[derive(Clone)]
204pub struct Kpiece<Sp, Sa, C, P, Pr, const K: usize>
205where
206 Sp: StateSpace,
207 P: Propagator<Sp>,
208{
209 /// The problem being solved.
210 problem: KinodynamicProblem<Sp, Sa, C, P>,
211 /// Maps states into the grid's space.
212 projection: Pr,
213 /// The validated settings.
214 config: KpieceConfig<K>,
215 /// All motions; motion `0` is the start.
216 motions: Vec<Motion<Sp::State, P::Control>>,
217 /// The grid over the motions' end states.
218 grid: Grid<K>,
219 /// Up to `close_samples` motions closest to the goal as `(goal distance, motion)`, closest
220 /// first.
221 close: Vec<(f64, usize)>,
222 /// The first motion that reached the goal region.
223 solution: Option<usize>,
224 /// The number of iterations run, including the current one.
225 iteration: usize,
226}
227
228impl<Sp, Sa, C, P, Pr, const K: usize> Kpiece<Sp, Sa, C, P, Pr, K>
229where
230 Sp: StateSpace,
231 C: ValidityChecker<Sp>,
232 P: Propagator<Sp>,
233 Pr: Projection<Sp::State, K>,
234{
235 /// Creates a planner whose tree holds only the start.
236 ///
237 /// # Errors
238 ///
239 /// - [`Error::InvalidStart`] if the start state is not valid.
240 /// - [`Error::GoalBiasOutOfRange`] if `goal_bias` is not in `[0, 1]`.
241 /// - [`Error::InvalidRadius`] if a cell size is not positive and finite.
242 /// - [`Error::InvalidPropagation`] if the step size is not positive and finite or the step
243 /// range is empty.
244 /// - [`Error::InvalidSchedule`] if a score factor is not in `(0, 1]` or `exterior_bias` not
245 /// in `[0, 1]`.
246 pub fn new(
247 problem: KinodynamicProblem<Sp, Sa, C, P>,
248 projection: Pr,
249 config: KpieceConfig<K>,
250 ) -> Result<Self, Error> {
251 config.validate()?;
252
253 let validity = problem.checker.check_state(&problem.start);
254 if !validity.is_valid() {
255 return Err(Error::InvalidStart(validity));
256 }
257
258 let mut planner = Self {
259 problem,
260 projection,
261 config,
262 motions: Vec::new(),
263 grid: Grid::new(),
264 close: Vec::new(),
265 solution: None,
266 iteration: 1,
267 };
268 let start = planner.problem.start.clone();
269 planner.add_motion(start, None, None, 0.0, 0);
270
271 Ok(planner)
272 }
273
274 /// Runs iterations until a motion reaches the goal region or `max_iterations` have run, and
275 /// returns the solution, if any.
276 pub fn solve<R: Rng + ?Sized>(
277 &mut self,
278 max_iterations: usize,
279 rng: &mut R,
280 ) -> Option<Trajectory<Sp::State, P::Control>> {
281 for _ in 0..max_iterations {
282 if self.solution.is_some() {
283 break;
284 }
285
286 self.step(rng);
287 }
288
289 self.best_trajectory()
290 }
291
292 /// Runs one iteration. Returns whether motions were added.
293 pub fn step<R: Rng + ?Sized>(&mut self, rng: &mut R) -> bool {
294 self.iteration += 1;
295
296 let (from, cell) = self.choose_motion(rng);
297 let control = self.problem.propagator.sample_control(rng);
298 let steps = random_step_count(self.config.max_steps, rng);
299 let states = self.propagate_while_valid(from, &control, steps);
300 let good = states.len() >= self.config.min_steps;
301
302 let added = good && self.add_if_interesting(from, &control, &states, rng);
303 self.rescore(cell, good);
304
305 added
306 }
307
308 /// Picks the motion to expand and the cell to score: a close-to-goal motion with
309 /// probability `goal_bias`, otherwise a grid selection.
310 fn choose_motion<R: Rng + ?Sized>(&mut self, rng: &mut R) -> (usize, usize) {
311 if !self.close.is_empty() && unit_f64(rng) < self.config.goal_bias {
312 let motion = self.take_close_sample();
313
314 return (motion, self.motions[motion].cell);
315 }
316
317 let exterior = unit_f64(rng) < self.config.exterior_bias.max(self.grid.exterior_fraction());
318 let cell = self
319 .grid
320 .select(exterior)
321 .expect("the start cell always exists");
322
323 if self.grid.cells[cell].score < f64::EPSILON {
324 self.grid.refresh_scores();
325 }
326
327 let entry = &mut self.grid.cells[cell];
328 entry.selections += 1.0;
329 let pick = half_normal_index(entry.motions.len(), rng);
330
331 (entry.motions[pick], cell)
332 }
333
334 /// The closest-to-goal motion; it stays a close sample with its distance inflated to
335 /// `1.1 (best + worst) / 2`, so that other close samples get their turn (as in OMPL).
336 fn take_close_sample(&mut self) -> usize {
337 let (best, motion) = self.close.remove(0);
338 let worst = self.close.last().map_or(best, |&(distance, _)| distance);
339 self.insert_close(0.55 * (best + worst), motion);
340
341 motion
342 }
343
344 /// Applies `control` from the end of motion `from` for up to `steps` integration steps and
345 /// returns the states after each valid step, stopping at the first invalid one.
346 fn propagate_while_valid(
347 &self,
348 from: usize,
349 control: &P::Control,
350 steps: usize,
351 ) -> Vec<Sp::State> {
352 let (space, propagator) = (&self.problem.space, &self.problem.propagator);
353 let mut states: Vec<Sp::State> = Vec::new();
354 let mut state = self.motions[from].state.clone();
355
356 for _ in 0..steps {
357 let next = propagator.propagate(space, &state, control, self.config.step_size);
358
359 if !self
360 .problem
361 .checker
362 .check_motion(space, &state, &next)
363 .is_valid()
364 {
365 break;
366 }
367
368 states.push(next.clone());
369 state = next;
370 }
371
372 states
373 }
374
375 /// Adds the propagated `states` as motions, one per run of consecutive states in the same
376 /// cell, if they are interesting (OMPL's rule): one reaches a new cell or a cell with at
377 /// most two thirds of the average motion count, or a 5 % coin flip says so.
378 fn add_if_interesting<R: Rng + ?Sized>(
379 &mut self,
380 from: usize,
381 control: &P::Control,
382 states: &[Sp::State],
383 rng: &mut R,
384 ) -> bool {
385 let coords: Vec<[i64; K]> = states.iter().map(|state| self.coordinates(state)).collect();
386
387 if !self.is_interesting(&coords) && unit_f64(rng) >= 0.05 {
388 return false;
389 }
390
391 let mut parent = from;
392 let mut start = 0;
393
394 while start < states.len() {
395 let end = run_end(&coords, start);
396 let duration = count_to_f64(end - start) * self.config.step_size;
397 let cost = self.motions[parent].cost + duration;
398 let cell = self.cell_for(coords[start], &states[end - 1]);
399 parent = self.add_motion(
400 states[end - 1].clone(),
401 Some(parent),
402 Some((control.clone(), duration)),
403 cost,
404 cell,
405 );
406 self.grid.cells[cell].coverage += count_to_f64(end - start);
407 start = end;
408 }
409
410 true
411 }
412
413 /// Whether a propagation through cells `coords` adds information: a new cell, or a sparsely
414 /// populated one.
415 fn is_interesting(&self, coords: &[[i64; K]]) -> bool {
416 let threshold = 2 * self.motions.len() / (3 * self.grid.cells.len());
417
418 coords.iter().any(|coord| {
419 self.grid
420 .find(coord)
421 .is_none_or(|cell| self.grid.cells[cell].motions.len() <= threshold)
422 })
423 }
424
425 /// The cell at `coord`, created with a goal-distance score for `state` if needed.
426 fn cell_for(&mut self, coord: [i64; K], state: &Sp::State) -> usize {
427 if let Some(cell) = self.grid.find(&coord) {
428 return cell;
429 }
430
431 let score =
432 (1.0 + libm::log(count_to_f64(self.iteration))) / (1e-3 + self.goal_distance(state));
433
434 self.grid.add(coord, self.iteration, score)
435 }
436
437 /// Stores a motion in its cell, the close samples and, if it reaches the goal first, as the
438 /// solution. `cell` must be the cell of `state`, except for the start, whose cell is
439 /// created here.
440 fn add_motion(
441 &mut self,
442 state: Sp::State,
443 parent: Option<usize>,
444 control: Option<(P::Control, f64)>,
445 cost: f64,
446 cell: usize,
447 ) -> usize {
448 let id = self.motions.len();
449 let distance = self.goal_distance(&state);
450 let cell = if parent.is_none() {
451 let coord = self.coordinates(&state);
452 let cell = self.cell_for(coord, &state);
453 self.grid.cells[cell].coverage = 1.0;
454
455 cell
456 } else {
457 cell
458 };
459
460 if distance <= 0.0 && self.solution.is_none() {
461 self.solution = Some(id);
462 }
463
464 self.grid.cells[cell].motions.push(id);
465 self.insert_close(distance, id);
466 self.motions.push(Motion {
467 state,
468 parent,
469 control,
470 cost,
471 cell,
472 });
473
474 id
475 }
476
477 /// Keeps `motion` among the `close_samples` closest motions if it is close enough.
478 fn insert_close(&mut self, distance: f64, motion: usize) {
479 let at = self.close.partition_point(|&(other, _)| other <= distance);
480
481 if at < self.config.close_samples {
482 self.close.insert(at, (distance, motion));
483 self.close.truncate(self.config.close_samples);
484 }
485 }
486
487 /// Scales the score of `cell` by the good or bad factor.
488 fn rescore(&mut self, cell: usize, good: bool) {
489 self.grid.cells[cell].score *= if good {
490 self.config.good_score_factor
491 } else {
492 self.config.bad_score_factor
493 };
494 }
495
496 /// The grid coordinates of `state`.
497 fn coordinates(&self, state: &Sp::State) -> [i64; K] {
498 let point = self.projection.project(state);
499
500 core::array::from_fn(|axis| cell_index(point[axis] / self.config.cell_size[axis]))
501 }
502
503 /// The distance from `state` to the goal region; zero inside.
504 fn goal_distance(&self, state: &Sp::State) -> f64 {
505 let goal = &self.problem.goal;
506
507 (self.problem.space.distance(state, goal.center()) - goal.tolerance()).max(0.0)
508 }
509
510 /// The first trajectory found into the goal region, or `None` if none was found yet.
511 #[must_use]
512 pub fn best_trajectory(&self) -> Option<Trajectory<Sp::State, P::Control>> {
513 let goal = self.solution?;
514 let mut states = Vec::new();
515 let mut controls = Vec::new();
516 let mut current = Some(goal);
517
518 while let Some(id) = current {
519 let motion = &self.motions[id];
520 states.push(motion.state.clone());
521 controls.extend(motion.control.clone());
522 current = motion.parent;
523 }
524
525 states.reverse();
526 controls.reverse();
527
528 Some(Trajectory {
529 states,
530 controls,
531 cost: self.motions[goal].cost,
532 })
533 }
534
535 /// The number of motions in the tree, including the start.
536 #[must_use]
537 pub fn motion_count(&self) -> usize {
538 self.motions.len()
539 }
540
541 /// The number of instantiated grid cells.
542 #[must_use]
543 pub fn cell_count(&self) -> usize {
544 self.grid.cells.len()
545 }
546}
547
548/// One past the last index of the run of equal coordinates starting at `start`.
549fn run_end<const K: usize>(coords: &[[i64; K]], start: usize) -> usize {
550 coords[start..]
551 .iter()
552 .position(|coord| *coord != coords[start])
553 .map_or(coords.len(), |offset| start + offset)
554}
555
556/// The integer cell index of a scaled coordinate: its floor, saturated; NaN maps to zero.
557#[expect(
558 clippy::cast_possible_truncation,
559 reason = "float-to-int casts saturate, which is the intended clamping"
560)]
561fn cell_index(scaled: f64) -> i64 {
562 libm::floor(scaled) as i64
563}
564
565/// An index into a list of `len >= 1` items from a half-normal distribution peaked at the last
566/// item, the newest motion: OMPL's `halfNormalInt(0, len - 1)` with focus 3.
567fn half_normal_index<R: Rng + ?Sized>(len: usize, rng: &mut R) -> usize {
568 let mean = count_to_f64(len);
569 let mut v = mean + mean / 3.0 * standard_normal(rng);
570
571 if v > mean {
572 v = 2.0 * mean - v;
573 }
574
575 let value = libm::floor(v.max(0.0));
576 let index = if value >= mean {
577 len - 1
578 } else {
579 #[expect(
580 clippy::cast_possible_truncation,
581 clippy::cast_sign_loss,
582 reason = "value is a whole number in [0, len) after the guards above"
583 )]
584 let index = value as usize;
585 index
586 };
587
588 index.min(len - 1)
589}
590
591/// A standard normal value from one Box-Muller transform.
592fn standard_normal<R: Rng + ?Sized>(rng: &mut R) -> f64 {
593 // `1 - u` lies in (0, 1], so the logarithm is finite.
594 let radius = libm::sqrt(-2.0 * libm::log(1.0 - unit_f64(rng)));
595
596 radius * libm::cos(2.0 * core::f64::consts::PI * unit_f64(rng))
597}
598
599#[cfg(test)]
600mod tests {
601 use super::*;
602 use rand_core::SeedableRng;
603
604 #[test]
605 fn half_normal_indices_stay_in_range_and_favor_the_newest() {
606 let mut rng = rand_pcg::Pcg64Mcg::seed_from_u64(1);
607 let mut counts = [0_u32; 10];
608
609 for _ in 0..10_000 {
610 counts[half_normal_index(10, &mut rng)] += 1;
611 }
612
613 assert!(counts[9] > counts[5] && counts[5] > counts[0], "{counts:?}");
614 assert_eq!(half_normal_index(1, &mut rng), 0);
615 }
616
617 #[test]
618 fn runs_split_at_cell_changes() {
619 let coords = [[0], [0], [1], [1], [1], [0]];
620
621 assert_eq!(run_end(&coords, 0), 2);
622 assert_eq!(run_end(&coords, 2), 5);
623 assert_eq!(run_end(&coords, 5), 6);
624 assert_eq!(cell_index(-0.5), -1);
625 assert_eq!(cell_index(f64::NAN), 0);
626 }
627}