1mod nodes;
4
5use alloc::vec::Vec;
6
7use rand_core::Rng;
8
9use super::{Error, KinodynamicProblem, Propagator, Trajectory};
10use crate::radius::count_to_f64;
11use crate::{LinearScan, RemovableNeighbors, Sampler, StateSpace, ValidityChecker, unit_f64};
12use nodes::{Node, Nodes};
13
14#[derive(Debug, Clone, Copy, PartialEq)]
21pub struct SstStarSchedule {
22 pub shrink: f64,
24 pub first_epoch: usize,
26}
27
28#[derive(Debug, Clone, Copy, PartialEq)]
30pub struct SstConfig {
31 pub goal_bias: f64,
33 pub selection_radius: f64,
36 pub pruning_radius: f64,
39 pub step_size: f64,
42 pub max_steps: usize,
45 pub star: Option<SstStarSchedule>,
47}
48
49impl SstConfig {
50 #[must_use]
52 pub const fn new(
53 selection_radius: f64,
54 pruning_radius: f64,
55 step_size: f64,
56 max_steps: usize,
57 ) -> Self {
58 Self {
59 goal_bias: 0.05,
60 selection_radius,
61 pruning_radius,
62 step_size,
63 max_steps,
64 star: None,
65 }
66 }
67
68 #[must_use]
70 pub const fn star(self, schedule: SstStarSchedule) -> Self {
71 Self {
72 star: Some(schedule),
73 ..self
74 }
75 }
76
77 fn validate(&self) -> Result<(), Error> {
79 let positive = |value: f64| value.is_finite() && value > 0.0;
80
81 if !(0.0..=1.0).contains(&self.goal_bias) {
82 return Err(Error::GoalBiasOutOfRange);
83 }
84
85 if !(positive(self.selection_radius) && positive(self.pruning_radius)) {
86 return Err(Error::InvalidRadius);
87 }
88
89 if !positive(self.step_size) || self.max_steps == 0 {
90 return Err(Error::InvalidPropagation);
91 }
92
93 match self.star {
94 Some(s) if !(s.shrink > 0.0 && s.shrink < 1.0) || s.first_epoch == 0 => {
95 Err(Error::InvalidSchedule)
96 }
97 _ => Ok(()),
98 }
99 }
100}
101
102#[derive(Debug, Clone)]
104struct Witness<S> {
105 state: S,
107 representative: usize,
109}
110
111#[derive(Debug, Clone, Copy, PartialEq, Eq)]
113enum WitnessSlot {
114 Existing(usize),
116 New,
118}
119
120#[derive(Debug, Clone, Copy)]
122struct Epoch {
123 index: usize,
125 end: usize,
127}
128
129#[derive(Clone)]
203pub struct Sst<Sp, Sa, C, P, N = LinearScan<<Sp as StateSpace>::State>>
204where
205 Sp: StateSpace,
206 P: Propagator<Sp>,
207{
208 problem: KinodynamicProblem<Sp, Sa, C, P>,
210 config: SstConfig,
212 nodes: Nodes<Sp::State, P::Control>,
215 active: N,
217 witnesses: Vec<Witness<Sp::State>>,
219 witness_nn: N,
221 best_goal: Option<usize>,
223 iteration: usize,
225 epoch: Epoch,
227 near: Vec<usize>,
229}
230
231impl<Sp, Sa, C, P> Sst<Sp, Sa, C, P>
232where
233 Sp: StateSpace,
234 Sa: Sampler<Sp::State>,
235 C: ValidityChecker<Sp>,
236 P: Propagator<Sp>,
237{
238 pub fn new(
247 problem: KinodynamicProblem<Sp, Sa, C, P>,
248 config: SstConfig,
249 ) -> Result<Self, Error> {
250 Self::with_nearest_neighbors(problem, config, LinearScan::default())
251 }
252}
253
254impl<Sp, Sa, C, P, N> Sst<Sp, Sa, C, P, N>
255where
256 Sp: StateSpace,
257 Sa: Sampler<Sp::State>,
258 C: ValidityChecker<Sp>,
259 P: Propagator<Sp>,
260 N: RemovableNeighbors<Sp> + Clone,
261{
262 pub fn with_nearest_neighbors(
272 problem: KinodynamicProblem<Sp, Sa, C, P>,
273 config: SstConfig,
274 nn: N,
275 ) -> Result<Self, Error> {
276 config.validate()?;
277
278 let validity = problem.checker.check_state(&problem.start);
279 if !validity.is_valid() {
280 return Err(Error::InvalidStart(validity));
281 }
282
283 let start = problem.start.clone();
284 let mut active = nn.clone();
285 let mut witness_nn = nn;
286 active.insert(0, start.clone());
287 witness_nn.insert(0, start.clone());
288
289 Ok(Self {
290 best_goal: problem.goal.contains(&problem.space, &start).then_some(0),
291 nodes: Nodes::new(Node {
292 state: start.clone(),
293 parent: None,
294 control: None,
295 cost: 0.0,
296 children: 0,
297 active: true,
298 }),
299 problem,
300 active,
301 witnesses: alloc::vec![Witness {
302 state: start.clone(),
303 representative: 0,
304 }],
305 witness_nn,
306 iteration: 0,
307 epoch: Epoch {
308 index: 0,
309 end: config.star.map_or(usize::MAX, |s| s.first_epoch),
310 },
311 config,
312 near: Vec::new(),
313 })
314 }
315
316 pub fn step<R: Rng + ?Sized>(&mut self, rng: &mut R) -> bool {
318 self.advance_schedule();
319 self.iteration += 1;
320
321 let target = self.draw(rng);
322 let parent = self.select(&target);
323 let Some((state, control, duration)) = self.propagate(parent, rng) else {
324 return false;
325 };
326
327 let cost = self.nodes[parent].cost + duration;
328 let Some(slot) = self.witness_slot(&state, cost) else {
329 return false;
330 };
331
332 self.add(state, parent, (control, duration), cost, slot);
333
334 true
335 }
336
337 pub fn run<R: Rng + ?Sized>(&mut self, iterations: usize, rng: &mut R) {
339 for _ in 0..iterations {
340 self.step(rng);
341 }
342 }
343
344 fn advance_schedule(&mut self) {
346 let Some(schedule) = self.config.star else {
347 return;
348 };
349
350 if self.iteration < self.epoch.end {
351 return;
352 }
353
354 self.config.selection_radius *= schedule.shrink;
355 self.config.pruning_radius *= schedule.shrink;
356 self.epoch.index += 1;
357 self.epoch.end = self
358 .epoch
359 .end
360 .saturating_add(self.epoch_length(schedule, self.epoch.index));
361 }
362
363 fn epoch_length(&self, schedule: SstStarSchedule, j: usize) -> usize {
365 let degrees = self.problem.space.dimension() + self.problem.propagator.control_dimension();
366 let exponent = -count_to_f64(degrees + 1) * count_to_f64(j);
367 let length = (1.0 + libm::log(count_to_f64(j)))
368 * libm::pow(schedule.shrink, exponent)
369 * count_to_f64(schedule.first_epoch);
370
371 saturating_count(length)
372 }
373
374 fn draw<R: Rng + ?Sized>(&mut self, rng: &mut R) -> Sp::State {
376 if unit_f64(rng) < self.config.goal_bias {
377 self.problem.goal.center().clone()
378 } else {
379 self.problem.sampler.sample(rng)
380 }
381 }
382
383 fn select(&mut self, target: &Sp::State) -> usize {
386 let space = &self.problem.space;
387 self.active
388 .within_radius(space, target, self.config.selection_radius, &mut self.near);
389
390 let mut best: Option<usize> = None;
391 for &id in &self.near {
392 if best.is_none_or(|b| self.nodes[id].cost < self.nodes[b].cost) {
393 best = Some(id);
394 }
395 }
396
397 best.unwrap_or_else(|| {
398 self.active
399 .nearest(space, target)
400 .expect("every witness keeps one node active")
401 })
402 }
403
404 fn propagate<R: Rng + ?Sized>(
408 &mut self,
409 from: usize,
410 rng: &mut R,
411 ) -> Option<(Sp::State, P::Control, f64)> {
412 let control = self.problem.propagator.sample_control(rng);
413 let steps = random_step_count(self.config.max_steps, rng);
414 let (space, propagator) = (&self.problem.space, &self.problem.propagator);
415 let mut state = self.nodes[from].state.clone();
416
417 for _ in 0..steps {
418 let next = propagator.propagate(space, &state, &control, self.config.step_size);
419
420 if !self
421 .problem
422 .checker
423 .check_motion(space, &state, &next)
424 .is_valid()
425 {
426 return None;
427 }
428
429 state = next;
430 }
431
432 let duration = count_to_f64(steps) * self.config.step_size;
433
434 Some((state, control, duration))
435 }
436
437 fn witness_slot(&self, state: &Sp::State, cost: f64) -> Option<WitnessSlot> {
440 let space = &self.problem.space;
441 let witness = self
442 .witness_nn
443 .nearest(space, state)
444 .expect("the start is always a witness");
445 let Witness {
446 state: point,
447 representative,
448 } = &self.witnesses[witness];
449
450 if space.distance(state, point) > self.config.pruning_radius {
451 return Some(WitnessSlot::New);
452 }
453
454 (cost < self.nodes[*representative].cost).then_some(WitnessSlot::Existing(witness))
455 }
456
457 fn add(
460 &mut self,
461 state: Sp::State,
462 parent: usize,
463 control: (P::Control, f64),
464 cost: f64,
465 slot: WitnessSlot,
466 ) {
467 let id = self.nodes.next_id();
468 let previous = self.claim_witness(slot, id, &state);
469 let reaches_goal = self.problem.goal.contains(&self.problem.space, &state);
470
471 self.active.insert(id, state.clone());
472 self.nodes.push(Node {
473 state,
474 parent: Some(parent),
475 control: Some(control),
476 cost,
477 children: 0,
478 active: true,
479 });
480
481 if let Some(previous) = previous {
482 self.deactivate(previous);
483 }
484
485 if reaches_goal
486 && self
487 .best_goal
488 .is_none_or(|best| cost < self.nodes[best].cost)
489 {
490 if let Some(old) = self.best_goal.replace(id) {
491 self.free_inactive_branch(old);
492 }
493 }
494 }
495
496 fn claim_witness(&mut self, slot: WitnessSlot, id: usize, state: &Sp::State) -> Option<usize> {
499 match slot {
500 WitnessSlot::Existing(witness) => Some(core::mem::replace(
501 &mut self.witnesses[witness].representative,
502 id,
503 )),
504 WitnessSlot::New => {
505 self.witness_nn.insert(self.witnesses.len(), state.clone());
506 self.witnesses.push(Witness {
507 state: state.clone(),
508 representative: id,
509 });
510
511 None
512 }
513 }
514 }
515
516 fn deactivate(&mut self, id: usize) {
518 self.active.remove(id);
519 self.nodes[id].active = false;
520 self.free_inactive_branch(id);
521 }
522
523 fn free_inactive_branch(&mut self, id: usize) {
527 let mut current = Some(id);
528
529 while let Some(node) = current {
530 let entry = &self.nodes[node];
531 let removable =
532 node != 0 && !entry.active && entry.children == 0 && self.best_goal != Some(node);
533
534 if !removable {
535 return;
536 }
537
538 current = self.nodes.free(node);
539 }
540 }
541
542 #[must_use]
545 pub fn best_trajectory(&self) -> Option<Trajectory<Sp::State, P::Control>> {
546 let goal = self.best_goal?;
547 let mut states = Vec::new();
548 let mut controls = Vec::new();
549 let mut current = Some(goal);
550
551 while let Some(id) = current {
552 let node = &self.nodes[id];
553 states.push(node.state.clone());
554 controls.extend(node.control.clone());
555 current = node.parent;
556 }
557
558 states.reverse();
559 controls.reverse();
560
561 Some(Trajectory {
562 states,
563 controls,
564 cost: self.nodes[goal].cost,
565 })
566 }
567
568 #[must_use]
571 pub fn node_count(&self) -> usize {
572 self.nodes.len()
573 }
574
575 #[must_use]
577 pub fn active_count(&self) -> usize {
578 self.active.len()
579 }
580
581 #[must_use]
583 pub const fn radii(&self) -> (f64, f64) {
584 (self.config.selection_radius, self.config.pruning_radius)
585 }
586}
587
588pub(super) fn random_step_count<R: Rng + ?Sized>(max_steps: usize, rng: &mut R) -> usize {
590 let max = u64::try_from(max_steps).unwrap_or(u64::MAX);
591 let offset = usize::try_from(rng.next_u64() % max).expect("below max_steps");
592
593 offset + 1
595}
596
597fn saturating_count(value: f64) -> usize {
599 if value.is_nan() || value < 1.0 {
600 0
601 } else if value >= f64::from(u32::MAX) {
602 usize::try_from(u32::MAX).unwrap_or(usize::MAX)
603 } else {
604 #[expect(
605 clippy::cast_possible_truncation,
606 clippy::cast_sign_loss,
607 reason = "value is in [1, u32::MAX) after the guards above"
608 )]
609 let count = value as u32;
610 usize::try_from(count).unwrap_or(usize::MAX)
611 }
612}
613
614#[cfg(test)]
615mod tests {
616 use super::*;
617 use crate::{Euclidean, GoalRegion, NearestNeighbors, Validity};
618 use rand_core::SeedableRng;
619
620 struct Replay(Vec<f64>, usize);
622
623 impl Replay {
624 fn next(&mut self) -> f64 {
626 self.1 += 1;
627 self.0[(self.1 - 1) % self.0.len()]
628 }
629 }
630
631 impl Sampler<[f64; 1]> for Replay {
632 fn sample<R: Rng + ?Sized>(&mut self, _: &mut R) -> [f64; 1] {
633 [self.next()]
634 }
635 }
636
637 impl Propagator<Euclidean<1>> for Replay {
638 type Control = f64;
639
640 fn control_dimension(&self) -> usize {
641 1
642 }
643
644 fn sample_control<R: Rng + ?Sized>(&mut self, _: &mut R) -> f64 {
645 self.next()
646 }
647
648 fn propagate(&self, _: &Euclidean<1>, from: &[f64; 1], u: &f64, dt: f64) -> [f64; 1] {
649 [from[0] + u * dt]
650 }
651 }
652
653 struct Free;
655
656 impl ValidityChecker<Euclidean<1>> for Free {
657 fn check_state(&self, _: &[f64; 1]) -> Validity {
658 Validity::Valid
659 }
660
661 fn check_motion(&self, _: &Euclidean<1>, _: &[f64; 1], _: &[f64; 1]) -> Validity {
662 Validity::Valid
663 }
664 }
665
666 #[test]
667 fn hand_checked_witness_rules() {
668 let problem = KinodynamicProblem {
669 space: Euclidean::<1>,
670 sampler: Replay(alloc::vec![0.0, 2.0, 2.0, 0.0], 0),
671 checker: Free,
672 propagator: Replay(alloc::vec![2.0, 2.0, 0.2, 4.1], 0),
673 start: [0.0],
674 goal: GoalRegion::new([100.0], 0.1),
675 };
676 let mut config = SstConfig::new(0.1, 0.5, 1.0, 1);
677 config.goal_bias = 0.0;
678 let mut sst = Sst::new(problem, config).expect("valid");
679 let mut rng = rand_pcg::Pcg64Mcg::seed_from_u64(1);
680
681 assert!(sst.step(&mut rng));
683 assert!(sst.step(&mut rng));
684 assert!(!sst.step(&mut rng));
686 assert_eq!((sst.node_count(), sst.active_count()), (3, 3));
687 assert!(sst.step(&mut rng));
690 assert_eq!((sst.node_count(), sst.active_count()), (3, 3));
691 assert_eq!(sst.nodes.next_id(), 2, "the freed id is reused next");
692 assert_eq!(sst.witnesses.len(), 3);
693 assert_eq!(sst.witnesses[2].representative, 3);
694 assert_eq!(sst.active.nearest(&Euclidean::<1>, &[4.0]), Some(3));
695 }
696
697 #[test]
698 fn the_best_goal_node_survives_deactivation() {
699 let problem = KinodynamicProblem {
700 space: Euclidean::<1>,
701 sampler: Replay(alloc::vec![0.0, 1.0, 0.0], 0),
702 checker: Free,
703 propagator: Replay(alloc::vec![1.0, 1.0, 2.4], 0),
704 start: [0.0],
705 goal: GoalRegion::new([2.0], 0.1),
706 };
707 let mut config = SstConfig::new(0.1, 0.5, 1.0, 1);
708 config.goal_bias = 0.0;
709 let mut sst = Sst::new(problem, config).expect("valid");
710 let mut rng = rand_pcg::Pcg64Mcg::seed_from_u64(1);
711
712 assert!(sst.step(&mut rng) && sst.step(&mut rng) && sst.step(&mut rng));
715 assert_eq!((sst.node_count(), sst.active_count()), (4, 3));
716
717 let trajectory = sst.best_trajectory().expect("solved");
718 assert_eq!(trajectory.states, [[0.0], [1.0], [2.0]]);
719 assert!((trajectory.cost - 2.0).abs() < 1e-12);
720 }
721
722 #[test]
723 fn step_counts_cover_the_whole_range() {
724 let mut rng = rand_pcg::Pcg64Mcg::seed_from_u64(1);
725 let mut seen = [false; 5];
726
727 for _ in 0..200 {
728 let steps = random_step_count(5, &mut rng);
729 assert!((1..=5).contains(&steps));
730 seen[steps - 1] = true;
731 }
732
733 assert_eq!(seen, [true; 5]);
734 }
735
736 #[test]
737 fn saturating_count_clamps() {
738 assert_eq!(saturating_count(f64::NAN), 0);
739 assert_eq!(saturating_count(0.5), 0);
740 assert_eq!(saturating_count(7.9), 7);
741 assert_eq!(
742 saturating_count(1e30),
743 usize::try_from(u32::MAX).expect("fits")
744 );
745 }
746}