Skip to main content

robust_planning/
search.rs

1//! Reachability-guided search: A* over reachable-set nodes on a lattice of nominal states.
2//!
3//! Each node carries a nominal state and the reachable set the system can be in there. To
4//! expand a node, every motion primitive (an offset from the nominal state) is steered
5//! toward, the node's set is propagated along the edge, and the edge is kept only if every
6//! set covering it is proven disjoint from every obstacle. Nodes are expanded in order of
7//! `f = g + h`: `g` is the path cost (see [`Config::cost`]), `h` a conservative lower bound
8//! on the remaining length (see [`Config::goal_radius`]). Successors whose nominal state
9//! leaves [`Problem::bounds`] are dropped. A node reaches the goal when its whole
10//! set is proven inside the goal region; the first such node popped is returned.
11//!
12//! ```mermaid
13//! graph LR
14//!     Pop["pop lowest f"] --> Goal{"set inside goal?"}
15//!     Goal -->|yes| Done
16//!     Goal -->|no| Prim["for each primitive: steer"]
17//!     Prim --> Check["propagate and check cover"]
18//!     Check -->|indeterminate or unsafe| Prim
19//!     Check -->|safe| Dom{"dominated in its cell?"}
20//!     Dom -->|yes| Prim
21//!     Dom -->|no| Push["push with f = g + h"]
22//!     Push --> Pop
23//! ```
24//!
25//! # Deduplication
26//!
27//! Nominal states are binned into lattice cells of width [`Config::resolution`]. A new node
28//! is dropped when a node already in its cell has a cost at most as high and an interval
29//! hull inside the new node's interval hull. Conversely, a new node supersedes the older
30//! nodes in its cell that it dominates, and they are skipped when popped.
31//!
32//! By default ([`Dedup::Hull`]) this is a heuristic dominance test: the hulls stand in for
33//! the sets. Pruning never affects safety, since every kept edge is still proven, but it can
34//! drop a node whose set is thinner than its hull and so cost completeness in tight
35//! passages. [`Dedup::Proven`] replaces it with a proof that one set lies inside the other
36//! ([`decide_within`]), for zonotopes in up to four dimensions, at the
37//! price of keeping many more nodes.
38//!
39//! # Examples
40//!
41//! ```
42//! use robust_planning::polyzonotope::{
43//!     Interval, IntervalBox, Polytope, SparsePolyZonotope, Zonotope,
44//! };
45//! use robust_planning::sampling_planning::StraightLine;
46//! use robust_planning::search::{Config, GoalRadius, Problem, ReachSearch};
47//! use robust_planning::{Obstacles, PolytopeGoal, Reach, WithSteering};
48//!
49//! /// Jumps to the setpoint along a straight line, ending within 0.1 of it.
50//! struct Snap;
51//!
52//! impl Reach<2> for Snap {
53//!     type Control = [f64; 2];
54//!
55//!     fn propagate(
56//!         &self,
57//!         initial: &SparsePolyZonotope,
58//!         end: &[f64; 2],
59//!         cover: &mut Vec<SparsePolyZonotope>,
60//!     ) -> Option<SparsePolyZonotope> {
61//!         let from = initial.interval_hull();
62//!         let hull = (0..2).map(|i| {
63//!             Interval::new(from.0[i].lo.min(end[i] - 0.1), from.0[i].hi.max(end[i] + 0.1))
64//!         });
65//!         let end_box = (0..2).map(|i| Interval::new(end[i] - 0.1, end[i] + 0.1));
66//!         let set = |b: IntervalBox| SparsePolyZonotope::from_zonotope(&Zonotope::from_box(&b));
67//!
68//!         cover.push(set(IntervalBox(hull.collect())));
69//!         Some(set(IntervalBox(end_box.collect())))
70//!     }
71//! }
72//!
73//! let square = |x: f64, y: f64, r: f64| {
74//!     IntervalBox(vec![Interval::new(x - r, x + r), Interval::new(y - r, y + r)])
75//! };
76//! let primitives = vec![[1.0, 0.0], [-1.0, 0.0], [0.0, 1.0], [0.0, -1.0]];
77//! let problem = Problem {
78//!     reach: WithSteering::new(Snap, StraightLine::new(2.0)),
79//!     // A wall at x in [1.5, 2.5] for y <= 1.5 forces a detour through y = 2.
80//!     obstacles: Obstacles::new(vec![Polytope::from_box(&IntervalBox(vec![
81//!         Interval::new(1.5, 2.5),
82//!         Interval::new(-5.0, 1.5),
83//!     ]))], 4),
84//!     start: [0.0, 0.0],
85//!     start_set: SparsePolyZonotope::from_zonotope(&Zonotope::from_box(&square(0.0, 0.0, 0.1))),
86//!     goal: PolytopeGoal::from_box(&square(4.0, 0.0, 0.3), 4),
87//!     primitives,
88//!     bounds: None,
89//! };
90//! let config = Config { goal_radius: GoalRadius::Fixed(0.0), ..Config::default() };
91//! let mut search = ReachSearch::new(problem, config).expect("valid start and config");
92//! let path = search.solve().expect("the detour is proven safe");
93//!
94//! assert!((path.cost - 8.0).abs() < 1e-9, "up 2, across 4, down 2");
95//! ```
96
97use core::{cmp::Ordering, fmt};
98use std::collections::{BinaryHeap, HashMap};
99
100use polyzonotope::{Containment, Interval, IntervalBox, Polytope, SparsePolyZonotope};
101use sampling_planning::{Euclidean, Path, StateSpace};
102
103use crate::{
104    Cost, Goal, Node, Obstacles, PolytopeGoal, Reach, SafetyVerdict, Steer, check_edge,
105    containment::decide_within, node,
106};
107
108/// Everything [`ReachSearch`] needs to know about the world.
109///
110/// The goal defaults to a [`PolytopeGoal`]; any [`Goal`] works.
111#[derive(Debug, Clone)]
112pub struct Problem<R, const N: usize, G = PolytopeGoal<N>> {
113    /// The dynamics model that steers and propagates.
114    pub reach: R,
115    /// The obstacles and their split budget.
116    pub obstacles: Obstacles,
117    /// The nominal start state, which steering starts from.
118    pub start: [f64; N],
119    /// Every state the system may start in. Must be proven safe.
120    pub start_set: SparsePolyZonotope,
121    /// The goal region. A node reaches it when its set is proven inside.
122    pub goal: G,
123    /// The motion primitives: offsets from a node's nominal state that steering aims at.
124    ///
125    /// Grid vectors that the model reaches exactly (for example the 4- or 8-neighborhood at
126    /// one step length) keep nominal states on a lattice, so deduplication can merge them.
127    pub primitives: Vec<[f64; N]>,
128    /// The workspace: lower and upper corners of the box that every nominal state must lie
129    /// in, or `None` for no bound.
130    ///
131    /// Successors outside it are dropped before their edge is checked, which keeps the
132    /// lattice finite in open worlds without framing walls. It bounds nominal states only;
133    /// to keep whole sets inside, add the outside as obstacles.
134    pub bounds: Option<([f64; N], [f64; N])>,
135}
136
137/// Where the heuristic's goal radius comes from; see [`Config::goal_radius`].
138#[derive(Debug, Clone, Copy, PartialEq, Default)]
139pub enum GoalRadius {
140    /// An infinite radius: `h = 0`, a uniform-cost search. The default.
141    #[default]
142    Infinite,
143    /// This radius. Non-negative and not NaN.
144    Fixed(f64),
145    /// [`Goal::radius`] of the problem's goal, for example the half diagonal of a
146    /// [`PolytopeGoal`] box.
147    ///
148    /// Admissible when each goal node's nominal state lies in its set, so that a set inside
149    /// the goal puts the nominal state inside it as well. That holds for models whose set
150    /// contains the nominal trajectory, like the affine test model.
151    FromGoal,
152}
153
154/// Settings for [`ReachSearch`].
155#[derive(Debug, Clone, Copy, PartialEq)]
156pub struct Config {
157    /// Width of the lattice cells nominal states are binned into for deduplication.
158    /// Positive and finite.
159    pub resolution: f64,
160    /// Distance from [`Goal::center`] within which every goal node's nominal state lies.
161    ///
162    /// The heuristic is `h(x) = max(0, |x - center| - goal_radius)`, which is consistent
163    /// for Euclidean edge costs. It is admissible, and the returned path optimal over the
164    /// nodes deduplication keeps, only if every node whose set is proven inside the goal
165    /// has its nominal state within `goal_radius` of the center. An infinite radius gives
166    /// `h = 0`, a uniform-cost search that is always admissible but expands more nodes.
167    /// The heuristic never affects safety.
168    pub goal_radius: GoalRadius,
169    /// The most nodes [`ReachSearch::solve`] expands before giving up.
170    pub max_expansions: usize,
171    /// How an edge is priced; `g` sums it. [`Cost::Length`] by default. Every option is at
172    /// least the nominal length, so the heuristic stays admissible.
173    pub cost: Cost,
174    /// When a new node supersedes an older one, also skip every descendant the older node
175    /// has generated so far. Off by default.
176    ///
177    /// The superseded node's subtree was grown from a set that a cheaper node with a set
178    /// at most as wide (by the hull test) now covers, so the new node regrows it. Pruning
179    /// only removes nodes from the open list; every kept edge stays proven, so it never
180    /// affects safety. Like deduplication it can cost completeness, since dominance is a
181    /// hull test.
182    ///
183    /// With the shipped heuristic, which is consistent, `f` never decreases along an edge.
184    /// A node that is already expanded is then superseded only by a node of exactly equal
185    /// cost, so this rarely prunes anything; it saves work only on such ties.
186    pub prune_superseded_subtrees: bool,
187    /// How one node's set is shown to lie inside another's for deduplication.
188    /// [`Dedup::Hull`] by default.
189    pub dedup: Dedup,
190    /// Require whole sets, not only nominal states, to stay in [`Problem::bounds`]. Off by
191    /// default; without bounds it has no effect.
192    ///
193    /// When on, the start set and every cover set and end set of an edge must be proven
194    /// inside the bounds box ([`Containment::Inside`] within the obstacles' split budget).
195    /// An edge that is not proven inside is dropped like an unsafe one. The proof is
196    /// rigorous with the `sound` feature.
197    pub bounds_contain_sets: bool,
198}
199
200/// The set-in-set test behind deduplication; see [`Config::dedup`].
201///
202/// Deduplication never affects safety, only which nodes are kept, so both are safe to use.
203/// They differ in what "node A covers node B" means.
204#[derive(Debug, Clone, Copy, PartialEq, Default)]
205pub enum Dedup {
206    /// Interval hulls: A's hull inside B's hull. Cheap and works in every dimension, but a
207    /// heuristic: A's set can stick out of B's set where B is thinner than its hull. The
208    /// default.
209    #[default]
210    Hull,
211    /// A proof that A's set lies inside B's set inflated by `tolerance` along every axis,
212    /// via [`decide_within`]. Where that test does not handle B's shape (not a zonotope,
213    /// more than [`MAX_DIMENSION`](crate::containment::MAX_DIMENSION) dimensions or
214    /// [`MAX_GENERATORS`](crate::containment::MAX_GENERATORS) generators, or a rank it
215    /// cannot prove full), it falls back to the hull test.
216    ///
217    /// With `tolerance` 0, sets that only touch are never merged, which keeps many more
218    /// nodes than [`Dedup::Hull`]. A small positive tolerance (`1e-9` merges rounding
219    /// noise) merges them, and the dominance then holds up to `tolerance`. The hull test,
220    /// widened by `tolerance`, runs first as a cheap filter.
221    Proven {
222        /// How far, along every axis, A may stick out of B. Finite and non-negative.
223        tolerance: f64,
224    },
225}
226
227impl Dedup {
228    /// The tolerance of [`Dedup::proven`]: merges sets that differ by rounding noise.
229    pub const PROVEN_TOLERANCE: f64 = 1e-9;
230
231    /// [`Dedup::Proven`] with the default tolerance [`Dedup::PROVEN_TOLERANCE`] (`1e-9`).
232    ///
233    /// Dominance then holds only up to `1e-9` along every axis: a merged node's set may
234    /// stick out of the covering set by that much. Like all deduplication this affects
235    /// completeness, never safety. Use `Dedup::Proven { tolerance }` for another value,
236    /// `0.0` for exact containment. The overall default stays [`Dedup::Hull`].
237    ///
238    /// # Examples
239    ///
240    /// ```
241    /// use robust_planning::search::Dedup;
242    ///
243    /// assert_eq!(Dedup::proven(), Dedup::Proven { tolerance: 1e-9 });
244    /// assert_eq!(Dedup::default(), Dedup::Hull);
245    /// ```
246    #[must_use]
247    pub const fn proven() -> Self {
248        Self::Proven {
249            tolerance: Self::PROVEN_TOLERANCE,
250        }
251    }
252}
253
254impl Default for Config {
255    /// A resolution of `1e-6` (merging only rounding noise), an infinite goal radius
256    /// (uniform-cost search), at most 10 000 expansions, length costs, no subtree pruning
257    /// and hull deduplication.
258    fn default() -> Self {
259        Self {
260            resolution: 1e-6,
261            goal_radius: GoalRadius::Infinite,
262            max_expansions: 10_000,
263            cost: Cost::Length,
264            prune_superseded_subtrees: false,
265            dedup: Dedup::Hull,
266            bounds_contain_sets: false,
267        }
268    }
269}
270
271/// Why a [`ReachSearch`] could not be created.
272#[derive(Debug, Clone, PartialEq)]
273pub enum Error {
274    /// The start set is not proven safe; carries the verdict.
275    StartNotSafe(SafetyVerdict),
276    /// [`Config::resolution`] is not positive and finite.
277    ResolutionOutOfRange,
278    /// [`Config::goal_radius`] is a negative or NaN [`GoalRadius::Fixed`].
279    GoalRadiusOutOfRange,
280    /// [`Config::goal_radius`] is [`GoalRadius::FromGoal`] but the goal knows no radius.
281    GoalRadiusUnavailable,
282    /// [`Problem::bounds`] has a NaN or inverted bound, or does not contain the start.
283    InvalidBounds,
284    /// The tolerance of [`Dedup::Proven`] is negative or not finite.
285    InvalidDedupTolerance,
286    /// The weight of [`Config::cost`] is negative or not finite.
287    InvalidCostWeight,
288}
289
290impl fmt::Display for Error {
291    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
292        match self {
293            Self::StartNotSafe(verdict) => write!(f, "start set is not proven safe ({verdict:?})"),
294            Self::ResolutionOutOfRange => f.write_str("resolution must be positive and finite"),
295            Self::GoalRadiusOutOfRange => f.write_str("goal radius must be non-negative"),
296            Self::GoalRadiusUnavailable => f.write_str("the goal provides no radius"),
297            Self::InvalidDedupTolerance => {
298                f.write_str("dedup tolerance must be finite and non-negative")
299            }
300            Self::InvalidBounds => {
301                f.write_str("bounds must be ordered, not NaN, and contain the start")
302            }
303            Self::InvalidCostWeight => f.write_str("cost weight must be finite and non-negative"),
304        }
305    }
306}
307
308impl core::error::Error for Error {}
309
310/// An entry of the open list: a node id and its priority `f = g + h`.
311///
312/// Ordered so that [`BinaryHeap`], a max-heap, pops the lowest `f` first, and among equal
313/// `f` the oldest node, which makes runs deterministic.
314#[derive(Debug, Clone, Copy)]
315struct Entry {
316    /// `g + h` of the node. Never NaN.
317    f: f64,
318    /// The node id.
319    id: usize,
320}
321
322impl Ord for Entry {
323    fn cmp(&self, other: &Self) -> Ordering {
324        other.f.total_cmp(&self.f).then(other.id.cmp(&self.id))
325    }
326}
327
328impl PartialOrd for Entry {
329    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
330        Some(self.cmp(other))
331    }
332}
333
334impl PartialEq for Entry {
335    fn eq(&self, other: &Self) -> bool {
336        self.cmp(other) == Ordering::Equal
337    }
338}
339
340impl Eq for Entry {}
341
342/// A* over reachable-set nodes; see the [module docs](self).
343///
344/// Every edge in the search tree is proven safe over its whole duration, every
345/// intermediate time step included, from the reachable set of its parent.
346pub struct ReachSearch<R: Reach<N>, const N: usize, G = PolytopeGoal<N>> {
347    /// The problem being solved.
348    problem: Problem<R, N, G>,
349    /// Settings.
350    config: Config,
351    /// Search-tree nodes by id; node `0` is the root.
352    nodes: Vec<Node<R::Control, N>>,
353    /// Cost from the root by node id; see [`Config::cost`].
354    costs: Vec<f64>,
355    /// Interval hull of each node's set, by node id; used for deduplication.
356    hulls: Vec<IntervalBox>,
357    /// Node ids by lattice cell of their nominal state.
358    cells: HashMap<[i64; N], Vec<usize>>,
359    /// Nodes generated but not expanded yet.
360    open: BinaryHeap<Entry>,
361    /// By node id: whether a later node in the same cell dominates it, so popping it is
362    /// skipped.
363    superseded: Vec<bool>,
364    /// Nodes expanded so far.
365    expansions: usize,
366    /// The resolved [`Config::goal_radius`]; non-negative, may be infinite.
367    goal_radius: f64,
368    /// The bounds box that whole sets must stay in, if [`Config::bounds_contain_sets`] is
369    /// on and there are bounds.
370    workspace: Option<Polytope>,
371    /// Child ids by node id; kept for [`Config::prune_superseded_subtrees`].
372    children: Vec<Vec<usize>>,
373    /// Descendants skipped by [`Config::prune_superseded_subtrees`] so far.
374    pruned: usize,
375    /// The node whose set was proven inside the goal, once popped.
376    goal_node: Option<usize>,
377    /// Scratch buffer for the cover sets of the edge being checked.
378    cover: Vec<SparsePolyZonotope>,
379}
380
381impl<R, const N: usize, G> ReachSearch<R, N, G>
382where
383    R: Reach<N> + Steer<N, R::Control>,
384    G: Goal<N>,
385{
386    /// Checks the start set and the settings and pushes the root.
387    ///
388    /// # Errors
389    ///
390    /// - [`Error::ResolutionOutOfRange`] if the resolution is not positive and finite.
391    /// - [`Error::GoalRadiusOutOfRange`] if a fixed goal radius is negative or NaN.
392    /// - [`Error::GoalRadiusUnavailable`] if the radius should come from a goal that has
393    ///   none.
394    /// - [`Error::InvalidCostWeight`] if the cost weight is negative or not finite.
395    /// - [`Error::InvalidBounds`] if the bounds are NaN, inverted or exclude the start, or,
396    ///   with [`Config::bounds_contain_sets`], do not provably contain the start set.
397    /// - [`Error::InvalidDedupTolerance`] if the proven-dedup tolerance is negative or not
398    ///   finite.
399    /// - [`Error::StartNotSafe`] if the start set is not proven disjoint from every obstacle.
400    pub fn new(problem: Problem<R, N, G>, config: Config) -> Result<Self, Error> {
401        let goal_radius = validate(&problem, &config)?;
402        let workspace = workspace(&problem, &config);
403
404        if workspace
405            .as_ref()
406            .is_some_and(|box_| !is_inside(&problem.start_set, box_, &problem.obstacles))
407        {
408            return Err(Error::InvalidBounds);
409        }
410
411        let verdict = problem.obstacles.check_set(&problem.start_set);
412
413        if !verdict.is_safe() {
414            return Err(Error::StartNotSafe(verdict));
415        }
416
417        let root = Node {
418            nominal: problem.start,
419            set: problem.start_set.clone(),
420            parent: None,
421            control: None,
422        };
423
424        let mut search = Self {
425            problem,
426            config,
427            nodes: Vec::new(),
428            costs: Vec::new(),
429            hulls: Vec::new(),
430            cells: HashMap::new(),
431            open: BinaryHeap::new(),
432            superseded: Vec::new(),
433            expansions: 0,
434            goal_radius,
435            workspace,
436            children: Vec::new(),
437            pruned: 0,
438            goal_node: None,
439            cover: Vec::new(),
440        };
441        let hull = root.set.interval_hull();
442        search.push(root, 0.0, hull);
443
444        Ok(search)
445    }
446
447    /// Searches until a goal node is popped, the open list runs empty or
448    /// [`Config::max_expansions`] nodes are expanded.
449    ///
450    /// Returns the nominal path to the goal, or `None` if none was found. Calling it again
451    /// after a budget stop continues with a fresh budget.
452    ///
453    /// # Panics
454    ///
455    /// Panics if the model's sets do not have the obstacles' dimension.
456    pub fn solve(&mut self) -> Option<Path<[f64; N]>> {
457        let budget = self.expansions + self.config.max_expansions;
458
459        while self.goal_node.is_none() && self.expansions < budget {
460            let Some(Entry { id, .. }) = self.open.pop() else {
461                break;
462            };
463
464            if self.superseded[id] {
465                continue;
466            }
467
468            if self.reaches_goal(id) {
469                self.goal_node = Some(id);
470            } else {
471                self.expand(id);
472            }
473        }
474
475        self.path()
476    }
477
478    /// All search-tree nodes by id; node `0` is the root.
479    #[must_use]
480    pub fn nodes(&self) -> &[Node<R::Control, N>] {
481        &self.nodes
482    }
483
484    /// The cost from the root to `node`: the nominal path length with [`Cost::Length`].
485    ///
486    /// # Panics
487    ///
488    /// Panics if `node` is not a node id.
489    #[must_use]
490    pub fn cost(&self, node: usize) -> f64 {
491        self.costs[node]
492    }
493
494    /// The node whose set was proven inside the goal, if one was popped.
495    #[must_use]
496    pub const fn goal_node(&self) -> Option<usize> {
497        self.goal_node
498    }
499
500    /// The number of descendants skipped by [`Config::prune_superseded_subtrees`] so far.
501    #[must_use]
502    pub const fn pruned(&self) -> usize {
503        self.pruned
504    }
505
506    /// The number of nodes expanded so far.
507    #[must_use]
508    pub const fn expansions(&self) -> usize {
509        self.expansions
510    }
511
512    /// Whether every generated node has been expanded, popped as the goal or superseded
513    /// by a dominating node.
514    #[must_use]
515    pub fn is_exhausted(&self) -> bool {
516        self.open.iter().all(|entry| self.superseded[entry.id])
517    }
518
519    /// The problem being solved.
520    #[must_use]
521    pub const fn problem(&self) -> &Problem<R, N, G> {
522        &self.problem
523    }
524
525    /// The node ids from the root to `node`, inclusive.
526    ///
527    /// # Panics
528    ///
529    /// Panics if `node` is not a node id.
530    #[must_use]
531    pub fn branch(&self, node: usize) -> Vec<usize> {
532        node::branch(&self.nodes, node)
533    }
534
535    /// The nominal path to the goal node, or `None` if the goal was not reached yet.
536    ///
537    /// The cost is [`ReachSearch::cost`] of the goal node. With [`Cost::Length`] that is the
538    /// Euclidean length of the nominal path, bit for bit.
539    #[must_use]
540    pub fn path(&self) -> Option<Path<[f64; N]>> {
541        let goal = self.goal_node?;
542        let states = node::nominal_path(&self.nodes, goal).states;
543
544        Some(Path {
545            states,
546            cost: self.costs[goal],
547        })
548    }
549
550    /// Generates every proven-safe, non-dominated successor of node `id`.
551    fn expand(&mut self, id: usize) {
552        self.expansions += 1;
553
554        for k in 0..self.problem.primitives.len() {
555            if let Some((child, cost, hull)) = self.successor(id, k) {
556                self.push(child, cost, hull);
557            }
558        }
559    }
560
561    /// The successor of node `id` along primitive `k` with its cost and interval hull, if
562    /// the edge moves, is proven safe and its end node is not dominated.
563    fn successor(
564        &mut self,
565        id: usize,
566        k: usize,
567    ) -> Option<(Node<R::Control, N>, f64, IntervalBox)> {
568        let parent = &self.nodes[id];
569        let offset = &self.problem.primitives[k];
570        let target = core::array::from_fn(|i| parent.nominal[i] + offset[i]);
571        let (control, nominal) = self.problem.reach.steer(&parent.nominal, &target);
572        let length = Euclidean::<N>.distance(&parent.nominal, &nominal);
573
574        // A zero-length edge could repeat forever at no cost.
575        if length.is_nan() || length <= 0.0 || !self.in_bounds(&nominal) {
576            return None;
577        }
578
579        let (verdict, end) = check_edge(
580            &self.problem.reach,
581            &self.problem.obstacles,
582            &parent.set,
583            &control,
584            &mut self.cover,
585        );
586        let set = end.filter(|_| verdict.is_safe())?;
587
588        if !self.sets_in_workspace(&set) {
589            return None;
590        }
591
592        let cost = self.costs[id] + self.config.cost.edge(length, &set);
593        let hull = set.interval_hull();
594
595        if self.is_dominated(&nominal, &set, &hull, cost) {
596            return None;
597        }
598
599        let child = Node {
600            nominal,
601            set,
602            parent: Some(id),
603            control: Some(control),
604        };
605
606        Some((child, cost, hull))
607    }
608
609    /// Whether a node in the cell of `nominal` costs at most `cost` and covers the set
610    /// `set` with interval hull `hull`, by [`Config::dedup`].
611    fn is_dominated(
612        &self,
613        nominal: &[f64; N],
614        set: &SparsePolyZonotope,
615        hull: &IntervalBox,
616        cost: f64,
617    ) -> bool {
618        self.cells.get(&self.cell(nominal)).is_some_and(|ids| {
619            // Skip superseded nodes: one superseded by dominance is covered by its superseder,
620            // which is checked in its place, and a pruned descendant must not drop the node
621            // that regrows it.
622            ids.iter().any(|&e| {
623                !self.superseded[e]
624                    && self.costs[e] <= cost
625                    && self.covers((&self.nodes[e].set, &self.hulls[e]), (set, hull))
626            })
627        })
628    }
629
630    /// The nodes in the cell of `nominal` that a node with cost `cost`, set `set` and hull
631    /// `hull` dominates.
632    fn dominated_by(
633        &self,
634        nominal: &[f64; N],
635        set: &SparsePolyZonotope,
636        hull: &IntervalBox,
637        cost: f64,
638    ) -> Vec<usize> {
639        self.cells
640            .get(&self.cell(nominal))
641            .map(|ids| {
642                ids.iter()
643                    .copied()
644                    .filter(|&e| {
645                        cost <= self.costs[e]
646                            && self.covers((set, hull), (&self.nodes[e].set, &self.hulls[e]))
647                    })
648                    .collect()
649            })
650            .unwrap_or_default()
651    }
652
653    /// Whether the set `inner` with its hull lies inside `outer`, by [`Config::dedup`].
654    fn covers(
655        &self,
656        inner: (&SparsePolyZonotope, &IntervalBox),
657        outer: (&SparsePolyZonotope, &IntervalBox),
658    ) -> bool {
659        match self.config.dedup {
660            Dedup::Hull => box_within(inner.1, outer.1, 0.0),
661            Dedup::Proven { tolerance } => {
662                let splits = self.problem.obstacles.max_splits();
663
664                box_within(inner.1, outer.1, tolerance)
665                    && decide_within(inner.0, outer.0, tolerance, splits)
666                        .unwrap_or_else(|| box_within(inner.1, outer.1, 0.0))
667            }
668        }
669    }
670
671    /// Adds `node` with path cost `cost` and interval hull `hull` to the tree, its cell and
672    /// the open list, and supersedes the nodes in its cell that it dominates.
673    fn push(&mut self, node: Node<R::Control, N>, cost: f64, hull: IntervalBox) {
674        let id = self.nodes.len();
675        let f = cost + self.heuristic(&node.nominal);
676        let dominated = self.dominated_by(&node.nominal, &node.set, &hull, cost);
677        self.cells
678            .entry(self.cell(&node.nominal))
679            .or_default()
680            .push(id);
681
682        if let Some(parent) = node.parent {
683            self.children[parent].push(id);
684        }
685
686        self.hulls.push(hull);
687        self.superseded.push(false);
688        self.costs.push(cost);
689        self.children.push(Vec::new());
690        self.nodes.push(node);
691        self.open.push(Entry { f, id });
692
693        for e in dominated {
694            self.supersede(e, id);
695        }
696    }
697
698    /// Marks node `e` superseded by node `by` and, with
699    /// [`Config::prune_superseded_subtrees`], every descendant of `e` as well.
700    ///
701    /// Descendants that are ancestors of `by` are kept, so `by`'s own branch is never
702    /// pruned. With positive edge costs that case cannot arise, since `by` costs at most
703    /// as much as `e`; the guard keeps it sound regardless.
704    fn supersede(&mut self, e: usize, by: usize) {
705        self.superseded[e] = true;
706
707        if !self.config.prune_superseded_subtrees {
708            return;
709        }
710
711        let ancestors = node::branch(&self.nodes, by);
712
713        if ancestors.contains(&e) {
714            return;
715        }
716
717        let mut stack = self.children[e].clone();
718
719        while let Some(id) = stack.pop() {
720            if !self.superseded[id] {
721                self.superseded[id] = true;
722                self.pruned += 1;
723            }
724
725            stack.extend_from_slice(&self.children[id]);
726        }
727    }
728
729    /// Whether `end` and the cover sets of the edge just checked are proven inside the
730    /// workspace box, if whole sets must stay there.
731    fn sets_in_workspace(&self, end: &SparsePolyZonotope) -> bool {
732        self.workspace.as_ref().is_none_or(|box_| {
733            let obstacles = &self.problem.obstacles;
734
735            is_inside(end, box_, obstacles)
736                && self.cover.iter().all(|set| is_inside(set, box_, obstacles))
737        })
738    }
739
740    /// Whether `nominal` lies in [`Problem::bounds`], if there are any.
741    fn in_bounds(&self, nominal: &[f64; N]) -> bool {
742        self.problem.bounds.is_none_or(|(lower, upper)| {
743            (0..N).all(|i| lower[i] <= nominal[i] && nominal[i] <= upper[i])
744        })
745    }
746
747    /// The lower bound `max(0, |x - center| - goal_radius)` on the remaining path length.
748    fn heuristic(&self, nominal: &[f64; N]) -> f64 {
749        let distance = Euclidean::<N>.distance(nominal, &self.problem.goal.center());
750
751        (distance - self.goal_radius).max(0.0)
752    }
753
754    /// The lattice cell of `nominal`.
755    fn cell(&self, nominal: &[f64; N]) -> [i64; N] {
756        #[expect(
757            clippy::cast_possible_truncation,
758            reason = "cells only group nodes for deduplication; a saturated cell is harmless"
759        )]
760        core::array::from_fn(|i| (nominal[i] / self.config.resolution).round() as i64)
761    }
762
763    /// Whether the set of node `id` is proven inside the goal.
764    fn reaches_goal(&self, id: usize) -> bool {
765        self.problem.goal.containment(&self.nodes[id].set) == Containment::Inside
766    }
767}
768
769/// The bounds of `problem` as a polytope, if [`Config::bounds_contain_sets`] is on.
770fn workspace<R, const N: usize, G>(
771    problem: &Problem<R, N, G>,
772    config: &Config,
773) -> Option<Polytope> {
774    let (lower, upper) = problem.bounds.filter(|_| config.bounds_contain_sets)?;
775    let box_ = IntervalBox((0..N).map(|i| Interval::new(lower[i], upper[i])).collect());
776
777    Some(Polytope::from_box(&box_))
778}
779
780/// Whether `set` is proven inside `box_` within the split budget of `obstacles`.
781fn is_inside(set: &SparsePolyZonotope, box_: &Polytope, obstacles: &Obstacles) -> bool {
782    set.containment(box_, obstacles.max_splits()) == Containment::Inside
783}
784
785/// Checks `config` and the bounds of `problem`, and resolves the goal radius.
786fn validate<R, const N: usize, G: Goal<N>>(
787    problem: &Problem<R, N, G>,
788    config: &Config,
789) -> Result<f64, Error> {
790    if !(config.resolution.is_finite() && config.resolution > 0.0) {
791        return Err(Error::ResolutionOutOfRange);
792    }
793
794    if !config.cost.is_valid() {
795        return Err(Error::InvalidCostWeight);
796    }
797
798    if let Dedup::Proven { tolerance } = config.dedup
799        && !(tolerance.is_finite() && tolerance >= 0.0)
800    {
801        return Err(Error::InvalidDedupTolerance);
802    }
803
804    if let Some((lower, upper)) = problem.bounds {
805        let contains_start =
806            (0..N).all(|i| lower[i] <= problem.start[i] && problem.start[i] <= upper[i]);
807
808        if !contains_start {
809            return Err(Error::InvalidBounds);
810        }
811    }
812
813    match config.goal_radius {
814        GoalRadius::Infinite => Ok(f64::INFINITY),
815        GoalRadius::Fixed(radius) if radius.is_nan() || radius < 0.0 => {
816            Err(Error::GoalRadiusOutOfRange)
817        }
818        GoalRadius::Fixed(radius) => Ok(radius),
819        GoalRadius::FromGoal => problem.goal.radius().ok_or(Error::GoalRadiusUnavailable),
820    }
821}
822
823/// Whether box `inner` lies inside box `outer` widened by `tolerance`, bound by bound.
824fn box_within(inner: &IntervalBox, outer: &IntervalBox, tolerance: f64) -> bool {
825    inner.dim() == outer.dim()
826        && inner
827            .0
828            .iter()
829            .zip(&outer.0)
830            .all(|(i, o)| o.lo - tolerance <= i.lo && i.hi <= o.hi + tolerance)
831}
832
833#[cfg(test)]
834mod tests {
835    use polyzonotope::{Interval, Zonotope};
836    use sampling_planning::StraightLine;
837
838    use super::*;
839    use crate::WithSteering;
840
841    /// Jumps to the setpoint; the end set is the box of half width 0.1 around it.
842    struct Snap;
843
844    impl Reach<2> for Snap {
845        type Control = [f64; 2];
846
847        fn propagate(
848            &self,
849            _: &SparsePolyZonotope,
850            end: &[f64; 2],
851            cover: &mut Vec<SparsePolyZonotope>,
852        ) -> Option<SparsePolyZonotope> {
853            cover.push(square(*end, 0.1));
854            Some(square(*end, 0.1))
855        }
856    }
857
858    /// The box `center ± half_width` as a set.
859    fn square(center: [f64; 2], half_width: f64) -> SparsePolyZonotope {
860        let b = IntervalBox(
861            center
862                .iter()
863                .map(|c| Interval::new(c - half_width, c + half_width))
864                .collect(),
865        );
866
867        SparsePolyZonotope::from_zonotope(&Zonotope::from_box(&b))
868    }
869
870    /// A search with no obstacles and no primitives; nodes are pushed by hand.
871    fn empty_search(prune: bool) -> ReachSearch<WithSteering<Snap, StraightLine>, 2> {
872        let problem = Problem {
873            reach: WithSteering::new(Snap, StraightLine::new(1.0)),
874            obstacles: Obstacles::new(Vec::new(), 0),
875            start: [0.0, 0.0],
876            start_set: square([0.0, 0.0], 0.1),
877            goal: PolytopeGoal::from_box(&IntervalBox(vec![Interval::new(8.0, 9.0); 2]), 0),
878            primitives: Vec::new(),
879            bounds: None,
880        };
881        let config = Config {
882            prune_superseded_subtrees: prune,
883            ..Config::default()
884        };
885
886        ReachSearch::new(problem, config).expect("valid")
887    }
888
889    /// Pushes a node at `nominal` under `parent` with `cost` and a set of `half_width`.
890    fn push(
891        search: &mut ReachSearch<WithSteering<Snap, StraightLine>, 2>,
892        parent: usize,
893        nominal: [f64; 2],
894        cost: f64,
895        half_width: f64,
896    ) -> usize {
897        let set = square(nominal, half_width);
898        let hull = set.interval_hull();
899        let node = Node {
900            nominal,
901            set,
902            parent: Some(parent),
903            control: Some(nominal),
904        };
905        search.push(node, cost, hull);
906
907        search.nodes.len() - 1
908    }
909
910    #[test]
911    fn superseding_prunes_the_old_subtree_only_when_asked() {
912        for prune in [false, true] {
913            let mut search = empty_search(prune);
914            let a = push(&mut search, 0, [1.0, 0.0], 1.0, 0.3);
915            let b = push(&mut search, a, [2.0, 0.0], 2.0, 0.3);
916            let c = push(&mut search, b, [3.0, 0.0], 3.0, 0.3);
917            let other = push(&mut search, 0, [0.0, 1.0], 1.0, 0.3);
918            let d = push(&mut search, 0, [1.0, 0.0], 0.5, 0.1);
919
920            assert!(search.superseded[a], "d is cheaper and narrower than a");
921            assert_eq!(search.superseded[b], prune);
922            assert_eq!(search.superseded[c], prune);
923            assert!(!search.superseded[other] && !search.superseded[d]);
924            assert_eq!(search.pruned(), if prune { 2 } else { 0 });
925        }
926    }
927
928    #[test]
929    fn proven_dedup_keeps_a_node_the_hull_test_wrongly_drops() {
930        // A box of half width 0.6 is not inside the diamond |x| + |y| <= 1, although its
931        // hull is inside the diamond's hull [-1, 1]².
932        let diamond = SparsePolyZonotope::from_zonotope(&Zonotope::new(
933            nalgebra::DVector::from_column_slice(&[1.0, 0.0]),
934            nalgebra::DMatrix::from_column_slice(2, 2, &[0.5, 0.5, 0.5, -0.5]),
935        ));
936        let diamond_hull = diamond.interval_hull();
937
938        for (dedup, dropped) in [
939            (Dedup::Hull, true),
940            (Dedup::Proven { tolerance: 0.0 }, false),
941        ] {
942            let mut search = empty_search(false);
943            search.config.dedup = dedup;
944            push(&mut search, 0, [1.0, 0.0], 1.0, 0.6);
945
946            assert_eq!(
947                search.is_dominated(&[1.0, 0.0], &diamond, &diamond_hull, 2.0),
948                dropped,
949                "{dedup:?}"
950            );
951        }
952
953        let mut search = empty_search(false);
954        search.config.dedup = Dedup::Proven { tolerance: 0.0 };
955        push(&mut search, 0, [1.0, 0.0], 1.0, 0.3);
956        assert!(
957            search.is_dominated(&[1.0, 0.0], &diamond, &diamond_hull, 2.0),
958            "a box of half width 0.3 is proven inside"
959        );
960    }
961
962    #[test]
963    fn pruning_never_touches_the_branch_of_the_superseding_node() {
964        let mut search = empty_search(true);
965        let a = push(&mut search, 0, [1.0, 0.0], 1.0, 0.3);
966        let b = push(&mut search, a, [2.0, 0.0], 1.0, 0.3);
967        // A zero-cost loop back into a's cell, which positive edge costs rule out; the guard
968        // keeps a's subtree, which holds the new node's own branch.
969        let d = push(&mut search, b, [1.0, 0.0], 1.0, 0.1);
970
971        assert!(search.superseded[a]);
972        assert!(!search.superseded[b] && !search.superseded[d]);
973        assert_eq!(search.pruned(), 0);
974    }
975
976    #[test]
977    fn open_list_pops_lowest_f_then_oldest() {
978        let mut open = BinaryHeap::new();
979
980        for (f, id) in [(2.0, 0), (1.0, 1), (1.0, 2), (3.0, 3)] {
981            open.push(Entry { f, id });
982        }
983
984        let order: Vec<usize> = core::iter::from_fn(|| open.pop().map(|e| e.id)).collect();
985        assert_eq!(order, [1, 2, 0, 3]);
986    }
987
988    #[test]
989    fn box_within_compares_every_bound() {
990        let b = |lo: f64, hi: f64| IntervalBox(vec![Interval::new(lo, hi); 2]);
991        let box_within_exact =
992            |inner: &IntervalBox, outer: &IntervalBox| box_within(inner, outer, 0.0);
993
994        assert!(box_within_exact(&b(1.0, 2.0), &b(0.0, 3.0)));
995        assert!(box_within_exact(&b(1.0, 2.0), &b(1.0, 2.0)));
996        assert!(!box_within_exact(&b(0.0, 3.0), &b(1.0, 2.0)));
997        assert!(!box_within_exact(&b(0.5, 3.5), &b(0.0, 3.0)));
998        assert!(box_within(&b(0.5, 3.5), &b(0.0, 3.0), 0.5));
999    }
1000}