Skip to main content

robust_planning/
robust_rrt_star.rs

1//! Robust RRT*: an RRT* whose nodes carry the reachable set they are reached with.
2//!
3//! Each iteration extends the tree like [`RobustRrt`](crate::RobustRrt), then improves it
4//! like RRT* (Karaman and Frazzoli 2011):
5//!
6//! - **Choose parent.** Among the nodes within the connection radius of the new node, the
7//!   cheapest one whose edge to the new node is proven safe becomes its parent. Candidates
8//!   are tried in order of cost, so only edges that would lower the cost are checked.
9//! - **Rewire.** Each neighbor that would be cheaper through the new node is moved under it,
10//!   but only as a transaction. A new parent gives the neighbor a new reachable set, so the
11//!   whole subtree below it is re-propagated from there and every edge in it re-proven with
12//!   [`check_edge`]. The rewire commits only if every edge stays proven
13//!   [`SafetyVerdict::Safe`] and every node of the subtree that reached the goal still does.
14//!   Otherwise the tree stays exactly as it was.
15//!
16//! A choose-parent or rewire edge must arrive *exactly* at the node's nominal state, because
17//! the stored controls of its descendants start there. A model whose steering stops short of
18//! the target therefore only rewires within its reach; keep [`Config::max_radius`] at or
19//! below the model's steering range.
20//!
21//! ```mermaid
22//! graph LR
23//!     Extend["extend nearest toward sample"] -->|safe| Choose["choose cheapest safe parent"]
24//!     Choose --> Insert["insert node"]
25//!     Insert --> Cand{"neighbor cheaper via new node?"}
26//!     Cand -->|yes, within budget| Prove["re-propagate and re-prove subtree"]
27//!     Prove -->|all safe, goal kept| Commit["commit rewire"]
28//!     Prove -->|otherwise| Keep["keep old tree"]
29//! ```
30//!
31//! # Optimality
32//!
33//! The cost is [`Config::cost`]: the nominal path length by default, as in
34//! [`RobustRrt`](crate::RobustRrt). The cost of
35//! [`RobustRrtStar::path`] never increases: new nodes only add goal candidates, a commit
36//! only lowers the costs of a subtree, and no commit drops a node from the goal.
37//!
38//! No convergence to an optimum is claimed. RRT*'s asymptotic optimality argument assumes
39//! every cheaper rewire is taken; here a rewire can be rejected because the new branch makes
40//! a set wider, skipped because of [`Config::rewire_budget`], or impossible because the
41//! steering does not reach the node exactly.
42//!
43//! The argument carries over when all of these hold (see `docs/design.md` for the
44//! statement): the budget is unbounded ([`Config::unbounded`]); steering reaches every
45//! target within [`Config::max_radius`] exactly; whether an edge is proven safe depends on
46//! its end points only, and the set it ends in on its end point alone (for example a model
47//! whose sets are a fixed tube around the nominal); `gamma` is above the RRT* bound; and
48//! the cost is [`Cost::Length`]. Then no rewire
49//! is ever skipped or rejected for a reason other than its own edge, and the tree is RRT*
50//! on the graph of proven-safe edges. The optimum it approaches is the cheapest path made of
51//! such edges, with some clearance in that graph; it is not the nominal optimum.
52//!
53//! # Examples
54//!
55//! ```
56//! use rand_pcg::Pcg64Mcg;
57//! use robust_planning::polyzonotope::{
58//!     Interval, IntervalBox, Polytope, SparsePolyZonotope, Zonotope,
59//! };
60//! use robust_planning::robust_rrt::Problem;
61//! use robust_planning::robust_rrt_star::{Config, RobustRrtStar};
62//! use robust_planning::sampling_planning::{StraightLine, UniformBox, rand_core::SeedableRng};
63//! use robust_planning::{Obstacles, PolytopeGoal, Reach, WithSteering};
64//!
65//! /// Jumps to the setpoint along a straight line, ending within 0.1 of it.
66//! struct Snap;
67//!
68//! impl Reach<2> for Snap {
69//!     type Control = [f64; 2];
70//!
71//!     fn propagate(
72//!         &self,
73//!         initial: &SparsePolyZonotope,
74//!         end: &[f64; 2],
75//!         cover: &mut Vec<SparsePolyZonotope>,
76//!     ) -> Option<SparsePolyZonotope> {
77//!         let from = initial.interval_hull();
78//!         let hull = (0..2).map(|i| {
79//!             Interval::new(from.0[i].lo.min(end[i] - 0.1), from.0[i].hi.max(end[i] + 0.1))
80//!         });
81//!         let end_box = (0..2).map(|i| Interval::new(end[i] - 0.1, end[i] + 0.1));
82//!         let set = |b: IntervalBox| SparsePolyZonotope::from_zonotope(&Zonotope::from_box(&b));
83//!
84//!         cover.push(set(IntervalBox(hull.collect())));
85//!         Some(set(IntervalBox(end_box.collect())))
86//!     }
87//! }
88//!
89//! let square = |x: f64, y: f64, r: f64| {
90//!     IntervalBox(vec![Interval::new(x - r, x + r), Interval::new(y - r, y + r)])
91//! };
92//! let problem = Problem {
93//!     reach: WithSteering::new(Snap, StraightLine::new(1.0)),
94//!     obstacles: Obstacles::new(vec![Polytope::from_box(&square(2.0, 2.0, 0.5))], 4),
95//!     sampler: UniformBox::new([0.0, 0.0], [4.0, 4.0]),
96//!     start: [0.5, 0.5],
97//!     start_set: SparsePolyZonotope::from_zonotope(&Zonotope::from_box(&square(0.5, 0.5, 0.1))),
98//!     goal: PolytopeGoal::from_box(&square(3.5, 3.5, 0.3), 4),
99//! };
100//! let mut planner = RobustRrtStar::new(problem, Config::new(4.0, 1.0)).expect("valid");
101//! let mut rng = Pcg64Mcg::seed_from_u64(1);
102//!
103//! planner.run(200, &mut rng);
104//! let first = planner.path().expect("a path around the block").cost;
105//! planner.run(800, &mut rng);
106//! let later = planner.path().expect("still solved").cost;
107//!
108//! assert!(later <= first, "the cost never increases");
109//! assert!(later < 4.6, "close to the shortest detour: {later}");
110//! ```
111
112#[cfg(test)]
113mod tests;
114
115use core::fmt;
116
117use polyzonotope::{Containment, SparsePolyZonotope};
118use sampling_planning::{
119    Euclidean, LinearScan, NearestNeighbors, Path, Sampler, StateSpace, rand_core::Rng, unit_f64,
120};
121
122pub use crate::robust_rrt::Problem;
123use crate::{Cost, Goal, Node, PolytopeGoal, Reach, SafetyVerdict, Steer, check_edge, node};
124
125/// Settings for [`RobustRrtStar`].
126#[derive(Debug, Clone, Copy, PartialEq)]
127pub struct Config {
128    /// Probability in `[0, 1]` of extending toward the goal's [`Goal::center`] instead of
129    /// a random sample.
130    pub goal_bias: f64,
131    /// The connection radius constant: with `n` nodes in `N` dimensions, nodes within
132    /// `gamma * (ln n / n)^(1/N)` of a new node are candidate parents and rewiring targets.
133    ///
134    /// RRT* needs `gamma` above
135    /// [`RrtStarConfig::gamma_lower_bound`](sampling_planning::trees::RrtStarConfig::gamma_lower_bound)
136    /// for asymptotic optimality. Positive and finite.
137    pub gamma: f64,
138    /// Upper bound on the connection radius. Positive; may be infinite.
139    ///
140    /// Keep it at or below the distance the model's steering reaches in one edge: a
141    /// candidate the steering does not reach exactly is skipped without a check.
142    pub max_radius: f64,
143    /// The most edge checks spent on rewiring in one iteration.
144    ///
145    /// A rewire costs one check per node of the moved subtree. A rewire whose subtree does
146    /// not fit in what is left of the budget is skipped, so one iteration never runs more
147    /// than this many rewiring checks. `0` disables rewiring.
148    pub rewire_budget: usize,
149    /// How an edge is priced. [`Cost::Length`] by default.
150    ///
151    /// With [`Cost::WidthWeighted`], moving a subtree changes the edge costs inside it, so
152    /// a rewire is also rejected if any node of the subtree would get more expensive.
153    pub cost: Cost,
154}
155
156impl Config {
157    /// A config with the given radius constant and radius cap, a goal bias of 10 % and a
158    /// rewiring budget of 64 edge checks per iteration.
159    #[must_use]
160    pub const fn new(gamma: f64, max_radius: f64) -> Self {
161        Self {
162            goal_bias: 0.1,
163            gamma,
164            max_radius,
165            rewire_budget: 64,
166            cost: Cost::Length,
167        }
168    }
169
170    /// A config like [`Config::new`] but with an unbounded rewiring budget
171    /// ([`usize::MAX`] edge checks per iteration), so no cheaper rewire is ever skipped.
172    ///
173    /// This is the mode in which the RRT* optimality argument can carry over; see the
174    /// [module docs](self#optimality) for the remaining conditions. An iteration can then
175    /// re-prove the whole tree.
176    #[must_use]
177    pub const fn unbounded(gamma: f64, max_radius: f64) -> Self {
178        Self {
179            rewire_budget: usize::MAX,
180            ..Self::new(gamma, max_radius)
181        }
182    }
183}
184
185/// Why a [`RobustRrtStar`] could not be created.
186#[derive(Debug, Clone, PartialEq)]
187pub enum Error {
188    /// The start set is not proven safe; carries the verdict.
189    StartNotSafe(SafetyVerdict),
190    /// [`Config::goal_bias`] is not in `[0, 1]`.
191    GoalBiasOutOfRange,
192    /// [`Config::gamma`] is not positive and finite.
193    InvalidGamma,
194    /// [`Config::max_radius`] is not positive.
195    InvalidMaxRadius,
196    /// The weight of [`Config::cost`] is negative or not finite.
197    InvalidCostWeight,
198}
199
200impl fmt::Display for Error {
201    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
202        match self {
203            Self::StartNotSafe(verdict) => write!(f, "start set is not proven safe ({verdict:?})"),
204            Self::GoalBiasOutOfRange => f.write_str("goal bias must be in [0, 1]"),
205            Self::InvalidGamma => f.write_str("gamma must be positive and finite"),
206            Self::InvalidMaxRadius => f.write_str("max radius must be positive"),
207            Self::InvalidCostWeight => f.write_str("cost weight must be finite and non-negative"),
208        }
209    }
210}
211
212impl core::error::Error for Error {}
213
214/// Counts of rewiring outcomes since the planner was created.
215#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
216pub struct Stats {
217    /// Rewires that were proven and committed.
218    pub rewires: usize,
219    /// Rewires that were tried and rejected: the edge to the new parent or an edge in the
220    /// subtree was not proven safe, a goal node would have lost the goal, the steering
221    /// did not reach the node exactly, or (with [`Cost::WidthWeighted`]) the new sets made
222    /// the node not cheaper or a descendant more expensive.
223    pub rejected_rewires: usize,
224    /// Rewires skipped because their subtree did not fit in the remaining
225    /// [`Config::rewire_budget`].
226    pub skipped_rewires: usize,
227}
228
229/// Why a rewire was not committed. The tree is unchanged in every case.
230#[derive(Debug, Clone, Copy, PartialEq, Eq)]
231enum Rejection {
232    /// The subtree has more nodes than the remaining budget allows checks.
233    OverBudget,
234    /// The new parent lies in the subtree of the node, so the rewire would close a cycle.
235    Cycle,
236    /// Steering from the new parent does not end exactly at the node's nominal state.
237    NotReached,
238    /// The edge from the new parent to the node is not proven safe.
239    EdgeUnproven,
240    /// An edge below the node is not proven safe from its re-propagated parent set.
241    DescendantUnproven,
242    /// A node of the subtree that reached the goal would no longer be proven inside it.
243    GoalLost,
244    /// With its new set the node is not cheaper after all (only with
245    /// [`Cost::WidthWeighted`]).
246    NotCheaper,
247    /// A node below the moved one would get more expensive (only with
248    /// [`Cost::WidthWeighted`]).
249    CostIncreased,
250}
251
252/// A proven edge into a node that is not in the tree yet.
253struct Edge<C> {
254    /// The parent node id.
255    parent: usize,
256    /// The control from the parent.
257    control: C,
258    /// The end set, which becomes the new node's set.
259    set: SparsePolyZonotope,
260    /// The cost of the new node through this edge.
261    cost: f64,
262}
263
264/// The proven outcome of a rewire, by subtree entry.
265struct Proven {
266    /// The re-propagated set of every node.
267    sets: Vec<SparsePolyZonotope>,
268    /// The new cost of every node.
269    costs: Vec<f64>,
270    /// Whether every node's new set is proven inside the goal.
271    in_goal: Vec<bool>,
272}
273
274/// The Robust RRT* planner.
275///
276/// Every edge in the tree is proven safe over its whole duration, from the reachable set
277/// its parent has *now*: rewires re-prove the subtrees they move. Runs are reproducible:
278/// all randomness comes from the caller's RNG.
279pub struct RobustRrtStar<R: Reach<N>, Sa, const N: usize, G = PolytopeGoal<N>> {
280    /// The problem being solved.
281    problem: Problem<R, Sa, N, G>,
282    /// Settings; validated by [`RobustRrtStar::new`].
283    config: Config,
284    /// Tree nodes by id; node `0` is the root. Ids never change.
285    nodes: Vec<Node<R::Control, N>>,
286    /// Cost from the root to each node, summed from the root down; see [`Config::cost`].
287    costs: Vec<f64>,
288    /// Child ids of each node, in no particular order.
289    children: Vec<Vec<usize>>,
290    /// Whether each node's set is proven inside the goal.
291    in_goal: Vec<bool>,
292    /// Index over the nominal states of all nodes, using node ids.
293    nn: LinearScan<[f64; N]>,
294    /// Rewiring outcomes so far.
295    stats: Stats,
296    /// Scratch buffer for the cover sets of the edge being checked.
297    cover: Vec<SparsePolyZonotope>,
298    /// Scratch buffer for neighbor queries.
299    near: Vec<usize>,
300}
301
302impl<R, Sa, const N: usize, G> RobustRrtStar<R, Sa, N, G>
303where
304    R: Reach<N> + Steer<N, R::Control>,
305    Sa: Sampler<[f64; N]>,
306    G: Goal<N>,
307{
308    /// Checks the config and the start set and plants the root.
309    ///
310    /// # Errors
311    ///
312    /// - [`Error::GoalBiasOutOfRange`] if the goal bias is not in `[0, 1]`.
313    /// - [`Error::InvalidGamma`] if `gamma` is not positive and finite.
314    /// - [`Error::InvalidMaxRadius`] if `max_radius` is not positive.
315    /// - [`Error::StartNotSafe`] if the start set is not proven disjoint from every obstacle.
316    pub fn new(problem: Problem<R, Sa, N, G>, config: Config) -> Result<Self, Error> {
317        validate(&config)?;
318        let verdict = problem.obstacles.check_set(&problem.start_set);
319
320        if !verdict.is_safe() {
321            return Err(Error::StartNotSafe(verdict));
322        }
323
324        let root = Node {
325            nominal: problem.start,
326            set: problem.start_set.clone(),
327            parent: None,
328            control: None,
329        };
330        let mut planner = Self {
331            problem,
332            config,
333            nodes: Vec::new(),
334            costs: Vec::new(),
335            children: Vec::new(),
336            in_goal: Vec::new(),
337            nn: LinearScan::default(),
338            stats: Stats::default(),
339            cover: Vec::new(),
340            near: Vec::new(),
341        };
342        planner.push(root, 0.0);
343
344        Ok(planner)
345    }
346
347    /// Runs one iteration: extend, choose a parent, insert, rewire. Returns whether a node
348    /// was added.
349    ///
350    /// # Panics
351    ///
352    /// Panics if the model's sets do not have the obstacles' dimension.
353    pub fn step<Rg: Rng + ?Sized>(&mut self, rng: &mut Rg) -> bool {
354        let target = self.draw(rng);
355        let Some((fallback, nominal)) = self.extend(&target) else {
356            return false;
357        };
358
359        let mut near = core::mem::take(&mut self.near);
360        self.nn
361            .within_radius(&Euclidean::<N>, &nominal, self.radius(), &mut near);
362        let edge = self.choose_parent(fallback, &nominal, &near);
363        let id = self.insert(edge, nominal);
364        self.rewire_neighbors(id, &near);
365        self.near = near;
366
367        true
368    }
369
370    /// Runs `iterations` iterations.
371    ///
372    /// Unlike [`RobustRrt::solve`](crate::RobustRrt::solve), it does not stop at the first
373    /// goal node: later iterations keep lowering the cost.
374    ///
375    /// # Panics
376    ///
377    /// Panics if the model's sets do not have the obstacles' dimension.
378    pub fn run<Rg: Rng + ?Sized>(&mut self, iterations: usize, rng: &mut Rg) {
379        for _ in 0..iterations {
380            self.step(rng);
381        }
382    }
383
384    /// All tree nodes by id; node `0` is the root.
385    #[must_use]
386    pub fn nodes(&self) -> &[Node<R::Control, N>] {
387        &self.nodes
388    }
389
390    /// The cost from the root to `node`: the nominal path length with [`Cost::Length`].
391    ///
392    /// # Panics
393    ///
394    /// Panics if `node` is not a node id.
395    #[must_use]
396    pub fn cost(&self, node: usize) -> f64 {
397        self.costs[node]
398    }
399
400    /// The cheapest node whose set is proven inside the goal region, if any. Ties go to the
401    /// oldest node.
402    #[must_use]
403    pub fn goal_node(&self) -> Option<usize> {
404        (0..self.nodes.len())
405            .filter(|&id| self.in_goal[id])
406            .min_by(|&a, &b| self.costs[a].total_cmp(&self.costs[b]))
407    }
408
409    /// Rewiring outcomes since the planner was created.
410    #[must_use]
411    pub const fn stats(&self) -> Stats {
412        self.stats
413    }
414
415    /// The problem being solved.
416    #[must_use]
417    pub const fn problem(&self) -> &Problem<R, Sa, N, G> {
418        &self.problem
419    }
420
421    /// The node ids from the root to `node`, inclusive.
422    ///
423    /// # Panics
424    ///
425    /// Panics if `node` is not a node id.
426    #[must_use]
427    pub fn branch(&self, node: usize) -> Vec<usize> {
428        node::branch(&self.nodes, node)
429    }
430
431    /// The nominal path to [`RobustRrtStar::goal_node`], or `None` if the goal was not
432    /// reached yet.
433    ///
434    /// The cost is [`RobustRrtStar::cost`] of the goal node. With [`Cost::Length`] that is
435    /// the Euclidean length of the nominal path, bit for bit.
436    #[must_use]
437    pub fn path(&self) -> Option<Path<[f64; N]>> {
438        let goal = self.goal_node()?;
439        let states = node::nominal_path(&self.nodes, goal).states;
440
441        Some(Path {
442            states,
443            cost: self.costs[goal],
444        })
445    }
446
447    /// Draws the goal center with the configured probability, otherwise a sampler state.
448    fn draw<Rg: Rng + ?Sized>(&mut self, rng: &mut Rg) -> [f64; N] {
449        if unit_f64(rng) < self.config.goal_bias {
450            self.problem.goal.center()
451        } else {
452            self.problem.sampler.sample(rng)
453        }
454    }
455
456    /// Steers the nearest node toward `target`. Returns the edge and its nominal end state if
457    /// the edge moves and is proven safe.
458    ///
459    /// A zero-length edge is skipped, as in [`ReachSearch`](crate::ReachSearch): once a node
460    /// sits at the goal center, every goal-biased draw would otherwise add a duplicate there.
461    fn extend(&mut self, target: &[f64; N]) -> Option<(Edge<R::Control>, [f64; N])> {
462        let parent = self
463            .nn
464            .nearest(&Euclidean::<N>, target)
465            .expect("the tree always holds the root");
466        let (control, nominal) = self
467            .problem
468            .reach
469            .steer(&self.nodes[parent].nominal, target);
470        let length = Euclidean::<N>.distance(&self.nodes[parent].nominal, &nominal);
471
472        if length.is_nan() || length <= 0.0 {
473            return None;
474        }
475
476        let set = prove(
477            &self.problem,
478            &mut self.cover,
479            &self.nodes[parent].set,
480            &control,
481        )?;
482        let cost = self.costs[parent] + self.config.cost.edge(length, &set);
483
484        Some((
485            Edge {
486                parent,
487                control,
488                set,
489                cost,
490            },
491            nominal,
492        ))
493    }
494
495    /// The connection radius for the next node: `min(gamma * (ln n / n)^(1/N), max_radius)`,
496    /// with `n` counting the new node.
497    fn radius(&self) -> f64 {
498        let n = count_to_f64(self.nodes.len() + 1);
499        let d = count_to_f64(N.max(1));
500
501        (self.config.gamma * (n.ln() / n).powf(1.0 / d)).min(self.config.max_radius)
502    }
503
504    /// The cheapest parent for a node at `nominal` among `fallback.parent` and `near`.
505    ///
506    /// `fallback` is already proven. Other candidates are tried in order of their lower
507    /// bound `cost + length` (which is their cost with [`Cost::Length`]), and only while that
508    /// bound is below the best proven cost so far.
509    fn choose_parent(
510        &mut self,
511        fallback: Edge<R::Control>,
512        nominal: &[f64; N],
513        near: &[usize],
514    ) -> Edge<R::Control> {
515        let mut candidates: Vec<(f64, usize)> = near
516            .iter()
517            .map(|&id| (self.length_bound(id, nominal), id))
518            .filter(|&(bound, id)| bound < fallback.cost && id != fallback.parent)
519            .collect();
520        candidates.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1)));
521        let mut best = fallback;
522
523        for (bound, id) in candidates {
524            if bound >= best.cost {
525                break;
526            }
527
528            if let Some(edge) = self.connect(id, nominal)
529                && edge.cost < best.cost
530            {
531                best = edge;
532            }
533        }
534
535        best
536    }
537
538    /// Tries to move every node in `near` under the new node `id` when that is cheaper,
539    /// within the iteration's rewiring budget.
540    fn rewire_neighbors(&mut self, id: usize, near: &[usize]) {
541        let mut budget = self.config.rewire_budget;
542
543        for &node in near {
544            if self.length_bound(id, &self.nodes[node].nominal) >= self.costs[node] {
545                continue;
546            }
547
548            match self.try_rewire(node, id, &mut budget) {
549                Ok(()) => self.stats.rewires += 1,
550                Err(Rejection::OverBudget) => self.stats.skipped_rewires += 1,
551                Err(_) => self.stats.rejected_rewires += 1,
552            }
553        }
554    }
555
556    /// Moves `node` and its subtree under `parent` if every edge stays proven safe and no
557    /// goal node loses the goal; otherwise leaves the tree unchanged.
558    ///
559    /// Charges one unit of `budget` per edge checked.
560    fn try_rewire(
561        &mut self,
562        node: usize,
563        parent: usize,
564        budget: &mut usize,
565    ) -> Result<(), Rejection> {
566        let subtree = self.subtree(node, *budget).ok_or(Rejection::OverBudget)?;
567
568        if subtree.iter().any(|&(id, _)| id == parent) {
569            return Err(Rejection::Cycle);
570        }
571
572        let control = self
573            .exact_control(parent, &self.nodes[node].nominal)
574            .ok_or(Rejection::NotReached)?;
575        let sets = self.prove_subtree(parent, &control, &subtree, budget)?;
576        let costs = self.subtree_costs(parent, &subtree, &sets)?;
577        let in_goal = self.goal_flags(&subtree, &sets)?;
578        self.commit(
579            parent,
580            control,
581            &subtree,
582            Proven {
583                sets,
584                costs,
585                in_goal,
586            },
587        );
588
589        Ok(())
590    }
591
592    /// The subtree of `node` in breadth-first order, each entry with the index of its
593    /// parent's entry (`0` for the node itself), or `None` if it has more than `limit`
594    /// nodes.
595    fn subtree(&self, node: usize, limit: usize) -> Option<Vec<(usize, usize)>> {
596        let mut entries = vec![(node, 0)];
597        let mut next = 0;
598
599        while next < entries.len() {
600            let id = entries[next].0;
601            entries.extend(self.children[id].iter().map(|&child| (child, next)));
602
603            if entries.len() > limit {
604                return None;
605            }
606
607            next += 1;
608        }
609
610        Some(entries)
611    }
612
613    /// The new set of every node in `subtree`, propagated from `parent` with `control` for
614    /// the subtree root and the stored controls below it, if every edge is proven safe.
615    fn prove_subtree(
616        &mut self,
617        parent: usize,
618        control: &R::Control,
619        subtree: &[(usize, usize)],
620        budget: &mut usize,
621    ) -> Result<Vec<SparsePolyZonotope>, Rejection> {
622        let mut sets: Vec<SparsePolyZonotope> = Vec::with_capacity(subtree.len());
623        let root_set = prove(
624            &self.problem,
625            &mut self.cover,
626            &self.nodes[parent].set,
627            control,
628        );
629        *budget = budget.saturating_sub(1);
630        sets.push(root_set.ok_or(Rejection::EdgeUnproven)?);
631
632        for &(id, parent_entry) in &subtree[1..] {
633            let control = self.nodes[id]
634                .control
635                .as_ref()
636                .expect("non-root nodes have one");
637            let set = prove(&self.problem, &mut self.cover, &sets[parent_entry], control);
638            *budget = budget.saturating_sub(1);
639            sets.push(set.ok_or(Rejection::DescendantUnproven)?);
640        }
641
642        Ok(sets)
643    }
644
645    /// The cost of every node in `subtree` with the new `sets`, the subtree root under
646    /// `parent`, or a rejection if the root is not cheaper or a node below it gets more
647    /// expensive.
648    fn subtree_costs(
649        &self,
650        parent: usize,
651        subtree: &[(usize, usize)],
652        sets: &[SparsePolyZonotope],
653    ) -> Result<Vec<f64>, Rejection> {
654        let mut costs: Vec<f64> = Vec::with_capacity(subtree.len());
655
656        for (entry, (&(id, parent_entry), set)) in subtree.iter().zip(sets).enumerate() {
657            let (from, base) = if entry == 0 {
658                (parent, self.costs[parent])
659            } else {
660                (subtree[parent_entry].0, costs[parent_entry])
661            };
662            let length =
663                Euclidean::<N>.distance(&self.nodes[from].nominal, &self.nodes[id].nominal);
664            let cost = base + self.config.cost.edge(length, set);
665
666            if entry == 0 && cost >= self.costs[id] {
667                return Err(Rejection::NotCheaper);
668            }
669
670            if cost > self.costs[id] {
671                return Err(Rejection::CostIncreased);
672            }
673
674            costs.push(cost);
675        }
676
677        Ok(costs)
678    }
679
680    /// Whether each node of `subtree` is proven inside the goal with its new set, or
681    /// [`Rejection::GoalLost`] if a node that reached the goal no longer does.
682    fn goal_flags(
683        &self,
684        subtree: &[(usize, usize)],
685        sets: &[SparsePolyZonotope],
686    ) -> Result<Vec<bool>, Rejection> {
687        subtree
688            .iter()
689            .zip(sets)
690            .map(|(&(id, _), set)| {
691                let inside = self.reaches_goal(set);
692
693                if self.in_goal[id] && !inside {
694                    Err(Rejection::GoalLost)
695                } else {
696                    Ok(inside)
697                }
698            })
699            .collect()
700    }
701
702    /// Moves the root of `subtree` under `parent` and stores the proven sets, costs and goal
703    /// flags of the whole subtree.
704    fn commit(
705        &mut self,
706        parent: usize,
707        control: R::Control,
708        subtree: &[(usize, usize)],
709        proven: Proven,
710    ) {
711        let node = subtree[0].0;
712        let old = self.nodes[node].parent.expect("the root is never rewired");
713        self.children[old].retain(|&child| child != node);
714        self.children[parent].push(node);
715        self.nodes[node].parent = Some(parent);
716        self.nodes[node].control = Some(control);
717
718        let entries = proven
719            .sets
720            .into_iter()
721            .zip(proven.costs)
722            .zip(proven.in_goal);
723
724        for (&(id, _), ((set, cost), inside)) in subtree.iter().zip(entries) {
725            self.costs[id] = cost;
726            self.nodes[id].set = set;
727            self.in_goal[id] = inside;
728        }
729    }
730
731    /// A proven edge from node `from` that ends exactly at `nominal`, if there is one.
732    fn connect(&mut self, from: usize, nominal: &[f64; N]) -> Option<Edge<R::Control>> {
733        let control = self.exact_control(from, nominal)?;
734        let set = prove(
735            &self.problem,
736            &mut self.cover,
737            &self.nodes[from].set,
738            &control,
739        )?;
740        let length = Euclidean::<N>.distance(&self.nodes[from].nominal, nominal);
741        let cost = self.costs[from] + self.config.cost.edge(length, &set);
742
743        Some(Edge {
744            parent: from,
745            control,
746            set,
747            cost,
748        })
749    }
750
751    /// The control that steers node `from` exactly to `nominal`, or `None` if steering
752    /// ends anywhere else.
753    fn exact_control(&self, from: usize, nominal: &[f64; N]) -> Option<R::Control> {
754        let (control, end) = self.problem.reach.steer(&self.nodes[from].nominal, nominal);
755
756        #[expect(
757            clippy::float_cmp,
758            reason = "the stored controls of the node's children start exactly at `nominal`"
759        )]
760        let reached = end == *nominal;
761
762        reached.then_some(control)
763    }
764
765    /// Adds a node at `nominal` with the proven `edge` and returns its id.
766    fn insert(&mut self, edge: Edge<R::Control>, nominal: [f64; N]) -> usize {
767        let cost = edge.cost;
768        let id = self.push(
769            Node {
770                nominal,
771                set: edge.set,
772                parent: Some(edge.parent),
773                control: Some(edge.control),
774            },
775            cost,
776        );
777        self.children[edge.parent].push(id);
778
779        id
780    }
781
782    /// Appends `node` with `cost` to every per-node table and the index; returns its id.
783    fn push(&mut self, node: Node<R::Control, N>, cost: f64) -> usize {
784        let id = self.nodes.len();
785        self.in_goal.push(self.reaches_goal(&node.set));
786        self.costs.push(cost);
787        self.children.push(Vec::new());
788        NearestNeighbors::<Euclidean<N>>::insert(&mut self.nn, id, node.nominal);
789        self.nodes.push(node);
790
791        id
792    }
793
794    /// A lower bound on the cost of reaching `nominal` through node `via`: its cost plus
795    /// the nominal length. Exact for [`Cost::Length`].
796    fn length_bound(&self, via: usize, nominal: &[f64; N]) -> f64 {
797        self.costs[via] + Euclidean::<N>.distance(&self.nodes[via].nominal, nominal)
798    }
799
800    /// Whether `set` is proven inside the goal region.
801    fn reaches_goal(&self, set: &SparsePolyZonotope) -> bool {
802        self.problem.goal.containment(set) == Containment::Inside
803    }
804}
805
806/// The end set of the edge from `initial` under `control`, if the edge is proven safe.
807///
808/// Takes the problem and the cover buffer apart from the planner, so that `initial` can be
809/// borrowed from its nodes.
810fn prove<R: Reach<N>, Sa, const N: usize, G>(
811    problem: &Problem<R, Sa, N, G>,
812    cover: &mut Vec<SparsePolyZonotope>,
813    initial: &SparsePolyZonotope,
814    control: &R::Control,
815) -> Option<SparsePolyZonotope> {
816    let (verdict, end) = check_edge(&problem.reach, &problem.obstacles, initial, control, cover);
817
818    end.filter(|_| verdict.is_safe())
819}
820
821/// Checks the ranges of every [`Config`] field.
822fn validate(config: &Config) -> Result<(), Error> {
823    if !(0.0..=1.0).contains(&config.goal_bias) {
824        return Err(Error::GoalBiasOutOfRange);
825    }
826
827    if !(config.gamma.is_finite() && config.gamma > 0.0) {
828        return Err(Error::InvalidGamma);
829    }
830
831    if config.max_radius.is_nan() || config.max_radius <= 0.0 {
832        return Err(Error::InvalidMaxRadius);
833    }
834
835    if !config.cost.is_valid() {
836        return Err(Error::InvalidCostWeight);
837    }
838
839    Ok(())
840}
841
842/// Converts a count to `f64`, saturating at `u32::MAX` (far beyond any tree size).
843fn count_to_f64(count: usize) -> f64 {
844    f64::from(u32::try_from(count).unwrap_or(u32::MAX))
845}