sampling_planning/informed/ait_star.rs
1//! AIT*: adaptively informed trees (Strub and Gammell 2020).
2
3mod forward;
4mod reverse;
5#[cfg(test)]
6mod tests;
7
8use alloc::{collections::BinaryHeap, vec::Vec};
9
10use rand_core::Rng;
11
12use super::batch::{Informed, Neighborhood};
13use super::queues::{EdgeEntry, VertexEntry};
14use super::{BitStarConfig, Error};
15#[cfg(doc)]
16use crate::trees::INFORMED_ATTEMPTS;
17use crate::{GoalRegion, LinearScan, NearestNeighbors, Path, Sampler, StateSpace, ValidityChecker};
18
19/// Settings for [`AitStar`]: the same batch size, radius constant, k-nearest constant and
20/// edge cap as BIT*, with the same meaning, ranges and lower bounds
21/// ([`BitStarConfig::gamma_lower_bound`], [`BitStarConfig::k_constant_lower_bound`]).
22pub type AitStarConfig = BitStarConfig;
23
24/// What a stored state currently is.
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26enum Kind {
27 /// A forward-tree vertex.
28 Vertex,
29 /// A sample not connected to the forward tree.
30 Sample,
31 /// Pruned for good: it cannot improve the solution.
32 Pruned,
33}
34
35/// One stored state: a forward-tree vertex or a sample, with its reverse-search values.
36#[derive(Debug, Clone)]
37struct Node<S> {
38 /// The state.
39 state: S,
40 /// What the state currently is.
41 kind: Kind,
42 /// The cost-to-come through the forward tree, `g_F`; infinite for samples.
43 g: f64,
44 /// The admissible cost-to-come `g_hat = d(start, x)`, also the reverse search's heuristic.
45 g_hat: f64,
46 /// The geometric cost-to-go `max(0, d(x, goal center) - tolerance)`, used for pruning and
47 /// to recognize goal states (zero inside the goal region).
48 h_hat: f64,
49 /// The forward-tree parent; `None` for the root and samples.
50 parent: Option<usize>,
51 /// The forward-tree children.
52 children: Vec<usize>,
53 /// The reverse search's cost-to-go when last connected, `h_con` (LPA*'s `rhs`); the
54 /// forward search's heuristic. Infinite until the reverse search reaches the state.
55 h_con: f64,
56 /// The reverse search's cost-to-go when last expanded, `h_exp` (LPA*'s `g`).
57 h_exp: f64,
58 /// The key of this state's live entry in the reverse queue, or `None` if not queued.
59 reverse_key: Option<[f64; 2]>,
60 /// The forward-queue edges into this state: each source vertex with the key of its live
61 /// entry. Edges leave this list when popped.
62 incoming: Vec<(usize, [f64; 3])>,
63 /// The neighbors in this batch's graph: the RGG neighbors, symmetrized, plus the forward
64 /// tree edges at the start of the batch. Sorted ascending, no duplicates.
65 adjacent: Vec<usize>,
66 /// The targets of motions from this state that checked as not valid, `E_invalid`; kept
67 /// across batches.
68 invalid: Vec<usize>,
69}
70
71impl<S> Node<S> {
72 /// The admissible solution cost through this state, `f_hat = g_hat + h_hat`.
73 fn f_hat(&self) -> f64 {
74 self.g_hat + self.h_hat
75 }
76
77 /// Whether the state lies in the goal region: a root of the reverse search.
78 fn in_goal(&self) -> bool {
79 self.h_hat <= 0.0
80 }
81}
82
83/// AIT*: adaptively informed trees (Strub and Gammell 2020).
84///
85/// AIT* is [BIT*](super::BitStar) with a problem-specific heuristic. Each batch of samples is
86/// an implicit random geometric graph (RGG). An asymmetric bidirectional search runs on it: a
87/// lazy reverse search from the goal states, Lifelong Planning A* (LPA*) without collision
88/// checks, computes the cost-to-go `h_con` of every state over the RGG; the forward search
89/// grows a tree from the start like BIT*, ordered by `g_F(v) + c_hat(v, x) + h_con(x)`, and
90/// checks the edges that come out on top. Every edge it finds invalid is removed from the
91/// reverse search's graph, and LPA* repairs the heuristic incrementally, so that the forward
92/// search stops being drawn into obstacles.
93///
94/// ```mermaid
95/// graph LR
96/// Batch["new batch: prune, sample, restart reverse search"] --> Reverse
97/// Reverse["reverse search (LPA*) until the best edge is settled"] --> Edge["pop best edge"]
98/// Edge -->|invalid| Repair["remove edge, update_state of its source"]
99/// Repair --> Reverse
100/// Edge -->|improves| Connect["add or rewire, expand"]
101/// Connect --> Reverse
102/// Edge -->|cannot improve| Batch
103/// ```
104///
105/// This follows Algorithms 2 to 6 of the ICRA 2020 paper (arXiv 2002.06599), with these
106/// choices:
107///
108/// - The heuristics are `g_hat(x) = d(start, x)` and `c_hat = d`. The goal center is the first
109/// sample when it is valid; every state in the goal region is a goal of the reverse search,
110/// and any forward-tree vertex in it is a solution.
111/// - The reverse search runs on a fixed graph per batch: the RGG neighbors of every state
112/// (radius, or k-nearest made symmetric) plus the forward-tree edges kept from earlier
113/// batches, minus the invalid edges. `h_con[x]` uses the motion from `x` to its neighbor
114/// (travel direction), and invalid edges are stored directed, so directional checkers stay
115/// sound; the paper and OMPL blacklist both directions.
116/// - Algorithm 6, line 1 reads "`x ≠ x_init`" in the paper; the states whose `h_con` must not
117/// be recomputed are the reverse roots, so this checks "`x ∉ X_goal`", as OMPL's
118/// `updateReverseSearchVertex` does.
119/// - Algorithm 5's stopping rule (lines 10 to 12, including the printed "<" on line 11) is
120/// replaced by OMPL's edge-based rule: the reverse search pauses when the child of the best
121/// forward edge is consistent (`h_con == h_exp`) and that edge's first key is below the
122/// reverse queue's first key. This is sound because `g_hat` is consistent: by the triangle
123/// inequality an edge's first key is at least its child's first LPA* key, so the child is
124/// settled and every edge with an unsettled child has a larger true key.
125/// - The forward queue keys are `(g_F(v) + c_hat + h_con(x), g_F(v) + c_hat, g_F(v))` as in
126/// the paper; OMPL uses `c_hat + h_con(x)` as the second key. Keys follow `h_con` as the
127/// reverse search changes it, and are re-sorted after a rewiring lowered tree costs.
128/// - A new batch prunes like BIT* (with the geometric `h_hat`, not `h_con`, which is not
129/// admissible beyond the current graph), samples through [`Sampler::sample_informed`] with a
130/// rejection fallback, and restarts the reverse search from the goals, as OMPL does. Batches
131/// can come out smaller than `batch_size` when [`INFORMED_ATTEMPTS`] draws per sample do not
132/// find a useful one.
133/// - An invalid edge triggers the paper's LPA* repair (`update_state` of its source); OMPL
134/// instead resets the whole reverse branch below it.
135/// - Edges are checked in travel direction, from tree parent to child.
136///
137/// The cost of [`AitStar::best_path`] never increases. Pruned states stay in memory until the
138/// planner is dropped.
139///
140/// # Examples
141///
142/// ```
143/// use rand_core::SeedableRng;
144/// use sampling_planning::{
145/// Euclidean, GoalRegion, UniformBox, Validity, ValidityChecker,
146/// informed::{AitStar, AitStarConfig},
147/// };
148///
149/// /// Free space everywhere.
150/// struct Free;
151///
152/// impl ValidityChecker<Euclidean<2>> for Free {
153/// fn check_state(&self, _: &[f64; 2]) -> Validity {
154/// Validity::Valid
155/// }
156///
157/// fn check_motion(&self, _: &Euclidean<2>, _: &[f64; 2], _: &[f64; 2]) -> Validity {
158/// Validity::Valid
159/// }
160/// }
161///
162/// let sampler = UniformBox::new([0.0, 0.0], [10.0, 10.0]);
163/// let config = AitStarConfig::new(1.5 * AitStarConfig::gamma_lower_bound(2, 100.0));
164/// let goal = GoalRegion::new([9.0, 9.0], 0.5);
165/// let mut ait = AitStar::new(Euclidean::<2>, sampler, Free, [1.0, 1.0], goal, config)
166/// .expect("valid");
167/// ait.run(50, &mut rand_pcg::Pcg64Mcg::seed_from_u64(1));
168///
169/// assert!(ait.best_path().expect("free space").cost < 11.0);
170/// ```
171#[derive(Debug, Clone)]
172pub struct AitStar<Sp: StateSpace, Sa, C, N = LinearScan<<Sp as StateSpace>::State>> {
173 /// The configuration space.
174 space: Sp,
175 /// Draws the batches.
176 sampler: Sa,
177 /// Decides which states and motions are allowed.
178 checker: C,
179 /// The start state; node `0`.
180 start: Sp::State,
181 /// Where the path has to end.
182 goal: GoalRegion<Sp::State>,
183 /// The validated settings.
184 config: AitStarConfig,
185 /// All stored states, by node id; node `0` is the start.
186 nodes: Vec<Node<Sp::State>>,
187 /// An empty index, cloned for every batch.
188 prototype: N,
189 /// Index over the vertices and samples of the current batch.
190 nn: N,
191 /// The forward queue `Q_F`; an entry is live while its target lists it in
192 /// [`Node::incoming`] with the same key.
193 forward_queue: BinaryHeap<EdgeEntry>,
194 /// The reverse queue `Q_R`, keyed `(min(h_con, h_exp) + g_hat, min(h_con, h_exp))`; an
195 /// entry is live while its state's [`Node::reverse_key`] equals its key.
196 reverse_queue: BinaryHeap<VertexEntry>,
197 /// Whether a rewiring lowered tree costs since the forward queue was keyed.
198 stale_keys: bool,
199 /// The forward-tree vertices inside the goal region.
200 solutions: Vec<usize>,
201 /// The cost of the best solution, `c_current`; infinite until one is found.
202 best_cost: f64,
203 /// The connection radius of the current batch, or the neighbor count for k-nearest.
204 neighborhood: Neighborhood,
205 /// The number of batches started.
206 batches: usize,
207}
208
209/// The node id of the start state.
210const START: usize = 0;
211
212impl<Sp, Sa, C> AitStar<Sp, Sa, C>
213where
214 Sp: StateSpace,
215 Sa: Sampler<Sp::State>,
216 C: ValidityChecker<Sp>,
217{
218 /// Creates a planner with a [`LinearScan`] nearest-neighbor index.
219 ///
220 /// # Errors
221 ///
222 /// The same as [`AitStar::with_nearest_neighbors`].
223 pub fn new(
224 space: Sp,
225 sampler: Sa,
226 checker: C,
227 start: Sp::State,
228 goal: GoalRegion<Sp::State>,
229 config: AitStarConfig,
230 ) -> Result<Self, Error> {
231 Self::with_nearest_neighbors(
232 space,
233 sampler,
234 checker,
235 start,
236 goal,
237 config,
238 LinearScan::default(),
239 )
240 }
241}
242
243impl<Sp, Sa, C, N> AitStar<Sp, Sa, C, N>
244where
245 Sp: StateSpace,
246 Sa: Sampler<Sp::State>,
247 C: ValidityChecker<Sp>,
248 N: NearestNeighbors<Sp> + Clone,
249{
250 /// Creates a planner; every batch indexes its states in a clone of the given empty index.
251 ///
252 /// # Errors
253 ///
254 /// - [`Error::InvalidStart`] if `start` is not valid.
255 /// - [`Error::EmptyBatch`] if the batch size is zero.
256 /// - [`Error::InvalidRadius`] if `gamma`, the k-nearest constant or `max_radius` is out of
257 /// range.
258 pub fn with_nearest_neighbors(
259 space: Sp,
260 sampler: Sa,
261 checker: C,
262 start: Sp::State,
263 goal: GoalRegion<Sp::State>,
264 config: AitStarConfig,
265 nn: N,
266 ) -> Result<Self, Error> {
267 config.validate()?;
268
269 let validity = checker.check_state(&start);
270 if !validity.is_valid() {
271 return Err(Error::InvalidStart(validity));
272 }
273
274 let mut planner = Self {
275 space,
276 sampler,
277 checker,
278 start: start.clone(),
279 goal,
280 config,
281 nodes: Vec::new(),
282 nn: nn.clone(),
283 prototype: nn,
284 forward_queue: BinaryHeap::new(),
285 reverse_queue: BinaryHeap::new(),
286 stale_keys: false,
287 solutions: Vec::new(),
288 best_cost: f64::INFINITY,
289 neighborhood: Neighborhood::Radius(0.0),
290 batches: 0,
291 };
292 planner.plant_root(start);
293
294 Ok(planner)
295 }
296
297 /// Stores the start as vertex `0` and the goal center as the first sample, if it is valid.
298 fn plant_root(&mut self, start: Sp::State) {
299 let root = self.push_node(start, Kind::Vertex);
300 self.nodes[root].g = 0.0;
301
302 if self.nodes[root].in_goal() {
303 self.solutions.push(root);
304 self.best_cost = 0.0;
305 }
306
307 let center = self.goal.center().clone();
308 if self.checker.check_state(¢er).is_valid() {
309 self.push_node(center, Kind::Sample);
310 }
311 }
312
313 /// Stores a new state of the given kind with its heuristics and returns its id.
314 fn push_node(&mut self, state: Sp::State, kind: Kind) -> usize {
315 let id = self.nodes.len();
316 let center_distance = self.space.distance(&state, self.goal.center());
317
318 self.nodes.push(Node {
319 g_hat: self.space.distance(&self.start, &state),
320 h_hat: (center_distance - self.goal.tolerance()).max(0.0),
321 g: f64::INFINITY,
322 state,
323 kind,
324 parent: None,
325 children: Vec::new(),
326 h_con: f64::INFINITY,
327 h_exp: f64::INFINITY,
328 reverse_key: None,
329 incoming: Vec::new(),
330 adjacent: Vec::new(),
331 invalid: Vec::new(),
332 });
333
334 id
335 }
336
337 /// Runs one iteration of Algorithm 2: starts a new batch if the forward queue is empty,
338 /// advances the reverse search as far as the best edge needs, then processes that edge.
339 /// Returns whether the forward tree changed.
340 ///
341 /// A batch ends at the first popped edge whose estimate cannot beat the current solution.
342 /// When the batch's graph holds no better path than the incumbent (or none at all), that
343 /// is the first edge, so every step starts a new batch: it adds up to `batch_size` states
344 /// and runs one neighbor query per stored state, which is quadratic with the
345 /// [`LinearScan`] default of [`AitStar::new`]. Use a [`KdTree`](crate::KdTree) and budget
346 /// by [`AitStar::batch_count`] as well. In free space a near-optimal run can reach 100
347 /// batches in a few hundred steps.
348 pub fn step<R: Rng + ?Sized>(&mut self, rng: &mut R) -> bool {
349 self.resort_if_stale();
350
351 if self.peek_edge().is_none() {
352 self.start_batch(rng);
353 }
354
355 self.advance_reverse_search();
356
357 match self.pop_edge() {
358 Some(edge) => self.process_edge(edge),
359 None => false,
360 }
361 }
362
363 /// Runs `iterations` iterations.
364 pub fn run<R: Rng + ?Sized>(&mut self, iterations: usize, rng: &mut R) {
365 for _ in 0..iterations {
366 self.step(rng);
367 }
368 }
369
370 /// Prunes, samples a batch, rebuilds the graph, restarts the reverse search and expands
371 /// the start (Algorithm 2, lines 2, 3 and 23 to 25).
372 fn start_batch<R: Rng + ?Sized>(&mut self, rng: &mut R) {
373 self.batches += 1;
374 self.clear_forward_queue();
375
376 if self.best_cost.is_finite() {
377 self.prune();
378 }
379
380 let sampled = self.sample_batch(rng);
381 self.reindex(sampled);
382 self.build_graph();
383 self.restart_reverse_search();
384 self.expand(START);
385 }
386
387 /// Removes the samples and vertices that cannot improve the solution, as BIT* does
388 /// (Gammell et al. 2020, Algorithm 3); vertices that still could are kept as samples.
389 fn prune(&mut self) {
390 let c = self.best_cost;
391
392 for node in &mut self.nodes {
393 if node.kind == Kind::Sample && node.f_hat() >= c {
394 node.kind = Kind::Pruned;
395 }
396 }
397
398 let mut vertices: Vec<usize> = (0..self.nodes.len())
399 .filter(|&id| self.nodes[id].kind == Kind::Vertex)
400 .collect();
401 vertices.sort_by(|&a, &b| self.nodes[a].g.total_cmp(&self.nodes[b].g).then(a.cmp(&b)));
402
403 for v in vertices {
404 let node = &self.nodes[v];
405 if node.kind == Kind::Vertex && (node.f_hat() > c || node.g + node.h_hat > c) {
406 self.disconnect(v);
407 }
408 }
409
410 // Children of a pruned vertex cost more than the solution too, so the sweep above
411 // removed them as well; this keeps the tree whole should rounding disagree.
412 for v in 1..self.nodes.len() {
413 if self.nodes[v].kind == Kind::Vertex && self.nodes[v].parent.is_none() {
414 self.disconnect(v);
415 }
416 }
417
418 self.solutions
419 .retain(|&id| self.nodes[id].kind == Kind::Vertex);
420 }
421
422 /// Removes vertex `v` from the tree; it becomes a sample if it could still improve the
423 /// solution and is pruned otherwise. Its children are handled by the caller's loop.
424 fn disconnect(&mut self, v: usize) {
425 if let Some(parent) = self.nodes[v].parent.take() {
426 self.nodes[parent].children.retain(|&child| child != v);
427 }
428
429 let recycle = self.nodes[v].f_hat() < self.best_cost;
430 let node = &mut self.nodes[v];
431 node.kind = if recycle { Kind::Sample } else { Kind::Pruned };
432 node.g = f64::INFINITY;
433
434 for child in core::mem::take(&mut node.children) {
435 self.nodes[child].parent = None;
436 }
437 }
438
439 /// Draws up to `batch_size` valid samples that can improve the solution and returns how
440 /// many were added.
441 fn sample_batch<R: Rng + ?Sized>(&mut self, rng: &mut R) -> usize {
442 let mut added = 0;
443
444 for _ in 0..self.config.batch_size {
445 let informed = Informed {
446 space: &self.space,
447 checker: &self.checker,
448 start: &self.start,
449 goal: &self.goal,
450 best_cost: self.best_cost,
451 };
452
453 if let Some(state) = informed.draw(&mut self.sampler, rng) {
454 self.push_node(state, Kind::Sample);
455 added += 1;
456 }
457 }
458
459 added
460 }
461
462 /// Rebuilds the index over all vertices and samples and fixes this batch's neighbor rule
463 /// from `q = |V| + |X_unconn| - m`, as BIT* does.
464 fn reindex(&mut self, sampled: usize) {
465 self.nn = self.prototype.clone();
466 let mut live: usize = 0;
467
468 for (id, node) in self.nodes.iter().enumerate() {
469 if node.kind != Kind::Pruned {
470 self.nn.insert(id, node.state.clone());
471 live += 1;
472 }
473 }
474
475 let q = live.saturating_sub(sampled).max(2);
476 self.neighborhood = Neighborhood::for_batch(&self.config, q, self.space.dimension());
477 }
478
479 /// Fixes this batch's graph: every state's RGG neighbors, symmetrized, plus the forward
480 /// tree edges, which may be longer than this batch's radius.
481 fn build_graph(&mut self) {
482 let mut near = Vec::new();
483
484 for node in &mut self.nodes {
485 node.adjacent.clear();
486 }
487
488 for id in 0..self.nodes.len() {
489 if self.nodes[id].kind == Kind::Pruned {
490 continue;
491 }
492
493 let cap = self.config.max_radius;
494 let keep = |x| x != id && (cap.is_infinite() || self.cost_estimate(id, x) <= cap);
495 self.neighborhood.query(
496 &self.space,
497 &self.nn,
498 &self.nodes[id].state,
499 keep,
500 &mut near,
501 );
502 self.link_all(id, &near);
503
504 if let Some(parent) = self.nodes[id].parent {
505 self.link_all(id, &[parent]);
506 }
507 }
508
509 for node in &mut self.nodes {
510 node.adjacent.sort_unstable();
511 node.adjacent.dedup();
512 }
513 }
514
515 /// Adds the undirected graph edges between `id` and each of `others`.
516 fn link_all(&mut self, id: usize, others: &[usize]) {
517 for &other in others {
518 self.nodes[id].adjacent.push(other);
519 self.nodes[other].adjacent.push(id);
520 }
521 }
522
523 /// The admissible edge cost estimate `c_hat(from, to) = d(from, to)`, in travel direction.
524 fn cost_estimate(&self, from: usize, to: usize) -> f64 {
525 self.space
526 .distance(&self.nodes[from].state, &self.nodes[to].state)
527 }
528
529 /// Whether the motion from `from` to `to` is known to be invalid.
530 fn is_invalid(&self, from: usize, to: usize) -> bool {
531 self.nodes[from].invalid.contains(&to)
532 }
533
534 /// The cheapest path found so far, or `None` if no vertex reached the goal yet. Its cost
535 /// never increases as iterations run.
536 #[must_use]
537 pub fn best_path(&self) -> Option<Path<Sp::State>> {
538 let best = self
539 .solutions
540 .iter()
541 .copied()
542 .min_by(|&a, &b| self.nodes[a].g.total_cmp(&self.nodes[b].g).then(a.cmp(&b)))?;
543 let mut states = Vec::new();
544 let mut current = Some(best);
545
546 while let Some(id) = current {
547 states.push(self.nodes[id].state.clone());
548 current = self.nodes[id].parent;
549 }
550
551 states.reverse();
552
553 Some(Path {
554 states,
555 cost: self.nodes[best].g,
556 })
557 }
558
559 /// The number of forward-tree vertices, including the start.
560 #[must_use]
561 pub fn vertex_count(&self) -> usize {
562 self.count(Kind::Vertex)
563 }
564
565 /// The number of samples not connected to the forward tree.
566 #[must_use]
567 pub fn sample_count(&self) -> usize {
568 self.count(Kind::Sample)
569 }
570
571 /// The number of batches started so far.
572 #[must_use]
573 pub const fn batch_count(&self) -> usize {
574 self.batches
575 }
576
577 /// The number of stored states of `kind`.
578 fn count(&self, kind: Kind) -> usize {
579 self.nodes.iter().filter(|node| node.kind == kind).count()
580 }
581}