Skip to main content

sampling_planning/kinodynamic/
sst.rs

1//! SST and SST*: stable sparse RRT (Li, Littlefield and Bekris 2016).
2
3mod 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/// The SST* schedule: SST runs in epochs, and after each epoch both radii shrink.
15///
16/// Epoch `0` lasts `first_epoch` iterations, epoch `j >= 1` lasts
17/// `(1 + ln j) * shrink^(-(d + l + 1) j) * first_epoch` iterations, where `d` is the state and
18/// `l` the control dimension. After epoch `j` both radii are multiplied by `shrink` (Li et al.
19/// 2016, Algorithm 9). With the radii shrinking toward zero, SST* is asymptotically optimal.
20#[derive(Debug, Clone, Copy, PartialEq)]
21pub struct SstStarSchedule {
22    /// The radius factor per epoch, `xi` in the paper. In `(0, 1)`.
23    pub shrink: f64,
24    /// The length of the first epoch in iterations, `K_0` in the paper. At least one.
25    pub first_epoch: usize,
26}
27
28/// Settings for [`Sst`].
29#[derive(Debug, Clone, Copy, PartialEq)]
30pub struct SstConfig {
31    /// Probability in `[0, 1]` of growing toward the goal center instead of a random sample.
32    pub goal_bias: f64,
33    /// `delta_BN`: the cheapest active node within this distance of a sample is expanded; the
34    /// nearest active node if there is none. Positive and finite.
35    pub selection_radius: f64,
36    /// `delta_s`: the witness radius. Of all nodes near one witness only the cheapest stays
37    /// active. Positive and finite; usually smaller than `selection_radius`.
38    pub pruning_radius: f64,
39    /// The integration step: every propagation is a sequence of steps of this duration, each
40    /// checked with [`ValidityChecker::check_motion`]. Positive and finite.
41    pub step_size: f64,
42    /// The most integration steps per propagation; the step count is uniform in
43    /// `1..=max_steps`. At least one.
44    pub max_steps: usize,
45    /// Turns SST into SST*; `None` keeps the radii fixed.
46    pub star: Option<SstStarSchedule>,
47}
48
49impl SstConfig {
50    /// Creates an SST config with a goal bias of 5 % and fixed radii.
51    #[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    /// This config with the SST* schedule.
69    #[must_use]
70    pub const fn star(self, schedule: SstStarSchedule) -> Self {
71        Self {
72            star: Some(schedule),
73            ..self
74        }
75    }
76
77    /// Checks every field against its documented range.
78    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/// A witness: a point that keeps only the cheapest node within the pruning radius active.
103#[derive(Debug, Clone)]
104struct Witness<S> {
105    /// The witness point: the state of the node that created it.
106    state: S,
107    /// The node that represents this witness; always active.
108    representative: usize,
109}
110
111/// Where a new node falls relative to the witnesses.
112#[derive(Debug, Clone, Copy, PartialEq, Eq)]
113enum WitnessSlot {
114    /// Within the pruning radius of this existing witness.
115    Existing(usize),
116    /// Farther than the pruning radius from every witness; becomes a new witness.
117    New,
118}
119
120/// Progress through the SST* epochs.
121#[derive(Debug, Clone, Copy)]
122struct Epoch {
123    /// The current epoch index `j`.
124    index: usize,
125    /// The iteration at which the current epoch ends.
126    end: usize,
127}
128
129/// SST: an RRT-like tree grown by random forward propagation, kept sparse by witnesses.
130///
131/// Each iteration picks the cheapest active node near a goal-biased sample, applies a random
132/// control for a random number of integration steps, and keeps the new node only if it is the
133/// cheapest node near its witness; the previous representative then becomes inactive and is
134/// never expanded again (Li, Littlefield and Bekris 2016). SST is asymptotically near-optimal;
135/// with an [`SstStarSchedule`] it becomes SST*, which is asymptotically optimal.
136///
137/// The cost is the total control duration. [`Sst::best_trajectory`] keeps the best solution
138/// found so far, so its cost never increases.
139///
140/// Inactive nodes stay only as long as they are ancestors of other nodes: an inactive leaf is
141/// freed at once, and so is every ancestor that becomes an inactive leaf in turn (Li et al.
142/// 2016, Algorithm 6). Memory therefore tracks the active nodes and their branches, not the
143/// iteration count. Freed node ids are reused. The cheapest goal node is never freed while it is
144/// the best solution, so [`Sst::best_trajectory`] stays available.
145///
146/// # Examples
147///
148/// ```
149/// use rand_core::{Rng, SeedableRng};
150/// use sampling_planning::{
151///     Euclidean, GoalRegion, UniformBox, Validity, ValidityChecker, unit_f64,
152///     kinodynamic::{KinodynamicProblem, Propagator, Sst, SstConfig},
153/// };
154///
155/// /// Free space everywhere.
156/// struct Free;
157///
158/// impl ValidityChecker<Euclidean<2>> for Free {
159///     fn check_state(&self, _: &[f64; 2]) -> Validity {
160///         Validity::Valid
161///     }
162///
163///     fn check_motion(&self, _: &Euclidean<2>, _: &[f64; 2], _: &[f64; 2]) -> Validity {
164///         Validity::Valid
165///     }
166/// }
167///
168/// /// A point that moves with a velocity of at most 1 per axis.
169/// struct Velocity;
170///
171/// impl Propagator<Euclidean<2>> for Velocity {
172///     type Control = [f64; 2];
173///
174///     fn control_dimension(&self) -> usize {
175///         2
176///     }
177///
178///     fn sample_control<R: Rng + ?Sized>(&mut self, rng: &mut R) -> [f64; 2] {
179///         [2.0 * unit_f64(rng) - 1.0, 2.0 * unit_f64(rng) - 1.0]
180///     }
181///
182///     fn propagate(&self, _: &Euclidean<2>, from: &[f64; 2], u: &[f64; 2], dt: f64) -> [f64; 2] {
183///         [from[0] + u[0] * dt, from[1] + u[1] * dt]
184///     }
185/// }
186///
187/// let problem = KinodynamicProblem {
188///     space: Euclidean::<2>,
189///     sampler: UniformBox::new([0.0, 0.0], [10.0, 10.0]),
190///     checker: Free,
191///     propagator: Velocity,
192///     start: [1.0, 1.0],
193///     goal: GoalRegion::new([9.0, 9.0], 0.5),
194/// };
195///
196/// let mut sst = Sst::new(problem, SstConfig::new(1.0, 0.3, 0.1, 10)).expect("valid");
197/// sst.run(5000, &mut rand_pcg::Pcg64Mcg::seed_from_u64(1));
198///
199/// let trajectory = sst.best_trajectory().expect("free space");
200/// assert_eq!(trajectory.controls.len() + 1, trajectory.states.len());
201/// ```
202#[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    /// The problem being solved.
209    problem: KinodynamicProblem<Sp, Sa, C, P>,
210    /// The settings; the radii shrink here under SST*.
211    config: SstConfig,
212    /// The stored nodes, indexed by node id: active nodes and their ancestors. Node `0` is the
213    /// start, which is never freed.
214    nodes: Nodes<Sp::State, P::Control>,
215    /// Index over the active nodes, by node id.
216    active: N,
217    /// All witnesses, indexed by witness id.
218    witnesses: Vec<Witness<Sp::State>>,
219    /// Index over the witness states, by witness id.
220    witness_nn: N,
221    /// The cheapest node in the goal region so far.
222    best_goal: Option<usize>,
223    /// The number of iterations run.
224    iteration: usize,
225    /// SST* epoch progress; unused without a schedule.
226    epoch: Epoch,
227    /// Reused buffer for neighbor queries.
228    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    /// Creates a planner with [`LinearScan`] indices.
239    ///
240    /// # Errors
241    ///
242    /// - [`Error::InvalidStart`] if the start state is not valid.
243    /// - [`Error::GoalBiasOutOfRange`], [`Error::InvalidRadius`],
244    ///   [`Error::InvalidPropagation`] or [`Error::InvalidSchedule`] if a config field is out of
245    ///   its documented range.
246    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    /// Creates a planner; the active-node and witness indices are clones of the given empty
263    /// index.
264    ///
265    /// # Errors
266    ///
267    /// - [`Error::InvalidStart`] if the start state is not valid.
268    /// - [`Error::GoalBiasOutOfRange`], [`Error::InvalidRadius`],
269    ///   [`Error::InvalidPropagation`] or [`Error::InvalidSchedule`] if a config field is out of
270    ///   its documented range.
271    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    /// Runs one iteration. Returns whether a node was added.
317    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    /// Runs `iterations` iterations.
338    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    /// Ends the current SST* epoch when it is over: shrinks both radii and schedules the next.
345    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    /// The length of epoch `j >= 1`: `(1 + ln j) * shrink^(-(d + l + 1) j) * first_epoch`.
364    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    /// Draws the goal center with probability `goal_bias`, otherwise a sampler state.
375    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    /// Best-first selection: the cheapest active node within the selection radius of
384    /// `target`, lowest id on ties, or the nearest active node if there is none.
385    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    /// Applies a random control for a random number of steps from node `from`, checking every
405    /// step. Returns the reached state, the control and the duration, or `None` if a step was
406    /// not valid.
407    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    /// The witness a new node at `state` with `cost` would represent, or `None` if that
438    /// witness already has a node that is at least as cheap.
439    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    /// Adds the node, makes it the representative of its witness, deactivates the previous
458    /// representative and frees the inactive leaves this leaves behind.
459    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    /// Makes the future node `id` at `state` the representative of the witness in `slot`, a new
497    /// witness if needed. Returns the previous representative.
498    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    /// Removes node `id` from the active index and frees it if that leaves an inactive leaf.
517    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    /// Frees node `id` and then its ancestors for as long as each is an inactive leaf.
524    ///
525    /// The start and the current best goal node are never freed.
526    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    /// The cheapest trajectory into the goal region found so far, or `None` if the goal was not
543    /// reached yet. Its cost never increases as iterations run.
544    #[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    /// The number of stored nodes: active nodes, the inactive ancestors they still need, the
569    /// root and the best goal node. Freed inactive leaves are not counted.
570    #[must_use]
571    pub fn node_count(&self) -> usize {
572        self.nodes.len()
573    }
574
575    /// The number of active nodes, which equals the number of witnesses.
576    #[must_use]
577    pub fn active_count(&self) -> usize {
578        self.active.len()
579    }
580
581    /// The current selection and pruning radii; they shrink over time under SST*.
582    #[must_use]
583    pub const fn radii(&self) -> (f64, f64) {
584        (self.config.selection_radius, self.config.pruning_radius)
585    }
586}
587
588/// A step count uniform in `1..=max_steps`.
589pub(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    // shortcut: modulo bias is below max_steps / 2^64, irrelevant for any realistic step count.
594    offset + 1
595}
596
597/// Converts a non-negative float count to `usize`, saturating; NaN becomes zero.
598fn 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    /// Replays a fixed list of values, cycling; used for both samples and controls.
621    struct Replay(Vec<f64>, usize);
622
623    impl Replay {
624        /// The next value.
625        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    /// Free space everywhere.
654    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        // 0 -> 2 (cost 1) and 2 -> 4 (cost 2) are far from every witness: new witnesses.
682        assert!(sst.step(&mut rng));
683        assert!(sst.step(&mut rng));
684        // 2 -> 2.2 (cost 2) is near the witness at 2, whose node costs 1: rejected.
685        assert!(!sst.step(&mut rng));
686        assert_eq!((sst.node_count(), sst.active_count()), (3, 3));
687        // 0 -> 4.1 (cost 1) is near the witness at 4 and beats its node (cost 2), which goes
688        // inactive and, being a leaf, is freed.
689        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        // 0 -> 1 -> 2 reaches the goal at cost 2; then 0 -> 2.4 (cost 1) takes over the witness
713        // at 2 and deactivates the goal node, which must stay stored as the best solution.
714        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}