sampling_planning/informed/bit_star.rs
1//! BIT*: batch informed trees (Gammell, Barfoot and Srinivasa 2020).
2
3use alloc::{collections::BinaryHeap, vec::Vec};
4
5use rand_core::Rng;
6
7use super::Error;
8use super::batch::{Informed, Neighborhood};
9use super::queues::{EdgeEntry, VertexEntry};
10use crate::radius::k_constant_lower_bound;
11#[cfg(doc)]
12use crate::trees::INFORMED_ATTEMPTS;
13use crate::trees::RrtStarConfig;
14use crate::{GoalRegion, LinearScan, NearestNeighbors, Path, Sampler, StateSpace, ValidityChecker};
15
16/// Settings for [`BitStar`].
17#[derive(Debug, Clone, Copy, PartialEq)]
18pub struct BitStarConfig {
19 /// The number of samples per batch, `m` in the paper. At least one.
20 pub batch_size: usize,
21 /// The connection radius constant: with `q` states in the graph (vertices plus unconnected
22 /// samples, minus the newest batch), states within `gamma * (ln q / q)^(1/d)` are
23 /// neighbors. Asymptotic optimality needs `gamma` above
24 /// [`BitStarConfig::gamma_lower_bound`]. Positive and finite. Unused when
25 /// [`BitStarConfig::k_nearest`] is set.
26 pub gamma: f64,
27 /// When `Some(k_constant)`, the neighbors are the `ceil(k_constant * ln q)` nearest states
28 /// instead (eq. 2 of the paper); asymptotic optimality needs `k_constant` above
29 /// [`BitStarConfig::k_constant_lower_bound`]. Positive and finite.
30 pub k_nearest: Option<f64>,
31 /// Upper bound on the connection radius and on every edge, `r_max` in the paper. Positive;
32 /// may be infinite.
33 pub max_radius: f64,
34}
35
36impl BitStarConfig {
37 /// A radius-based config with 100 samples per batch and no edge-length cap.
38 #[must_use]
39 pub const fn new(gamma: f64) -> Self {
40 Self {
41 batch_size: 100,
42 gamma,
43 k_nearest: None,
44 max_radius: f64::INFINITY,
45 }
46 }
47
48 /// The smallest `gamma` for which BIT* is asymptotically optimal (Gammell et al. 2020,
49 /// eq. 1): `(2 (1 + 1/d) free_volume / zeta_d)^(1/d)`, the RRT* bound.
50 ///
51 /// The paper uses the smaller of the free volume and the informed-set volume, which
52 /// shrinks the radius once a solution exists; using the free volume throughout keeps the
53 /// bound admissible at the price of larger neighborhoods.
54 #[must_use]
55 pub fn gamma_lower_bound(dimension: usize, free_volume: f64) -> f64 {
56 RrtStarConfig::gamma_lower_bound(dimension, free_volume)
57 }
58
59 /// The smallest k-nearest constant for which BIT* is asymptotically optimal (Gammell et
60 /// al. 2020, eq. 2): `e (1 + 1/d)`.
61 #[must_use]
62 pub fn k_constant_lower_bound(dimension: usize) -> f64 {
63 k_constant_lower_bound(dimension)
64 }
65
66 /// Checks every field against its documented range.
67 pub(super) fn validate(&self) -> Result<(), Error> {
68 let constant = self.k_nearest.unwrap_or(self.gamma);
69
70 if self.batch_size == 0 {
71 return Err(Error::EmptyBatch);
72 }
73
74 if !(constant.is_finite() && constant > 0.0)
75 || self.max_radius.is_nan()
76 || self.max_radius <= 0.0
77 {
78 return Err(Error::InvalidRadius);
79 }
80
81 Ok(())
82 }
83}
84
85/// What a stored state currently is.
86#[derive(Debug, Clone, Copy, PartialEq, Eq)]
87enum Kind {
88 /// A tree vertex.
89 Vertex,
90 /// A sample not connected to the tree (`X_unconn`).
91 Sample,
92 /// Pruned for good: it cannot improve the solution.
93 Pruned,
94}
95
96/// One stored state: a vertex or a sample.
97#[derive(Debug, Clone)]
98struct Node<S> {
99 /// The state.
100 state: S,
101 /// What the state currently is.
102 kind: Kind,
103 /// The cost-to-come through the tree, `g_T`; infinite for samples.
104 g: f64,
105 /// The admissible cost-to-come `g_hat = d(start, x)`.
106 g_hat: f64,
107 /// The admissible cost-to-go `h_hat = max(0, d(x, goal center) - tolerance)`.
108 h_hat: f64,
109 /// The tree parent; `None` for the root and samples.
110 parent: Option<usize>,
111 /// The tree children.
112 children: Vec<usize>,
113 /// A vertex that has not been expanded yet (`V_unexpnd`).
114 unexpanded: bool,
115 /// A sample added in the current batch, sampled or recycled (`X_new`).
116 fresh: bool,
117 /// Whether the vertex is waiting in the vertex queue.
118 queued: bool,
119}
120
121impl<S> Node<S> {
122 /// The admissible solution cost through this state, `f_hat = g_hat + h_hat`.
123 fn f_hat(&self) -> f64 {
124 self.g_hat + self.h_hat
125 }
126
127 /// Whether the state lies in the goal region, where the cost-to-go estimate is zero.
128 fn in_goal(&self) -> bool {
129 self.h_hat <= 0.0
130 }
131}
132
133/// BIT*: batch informed trees (Gammell, Srinivasa and Barfoot 2015; Gammell, Barfoot and
134/// Srinivasa 2020).
135///
136/// BIT* treats each batch of samples as an implicit random geometric graph and builds a tree
137/// over it in order of the estimated solution cost through each edge,
138/// `g_T(v) + c_hat(v, x) + h_hat(x)`, with an edge queue fed by expanding vertices. Edges are
139/// motion-checked only when they come out on top and could still improve the tree and the
140/// solution. When the best edge cannot improve the current solution, the batch is over: the
141/// planner prunes every state that cannot improve it (Algorithm 3), samples a new batch from
142/// the informed set and starts again. With one batch of infinitely many samples it would be
143/// Lifelong-Planning A* on the RGG; with batches of one sample it behaves like RRT*.
144///
145/// This follows Algorithms 1 to 3 of the 2020 paper, with these choices:
146///
147/// - The heuristics are `g_hat(x) = d(start, x)`, `h_hat(x) = max(0, d(x, goal center) -
148/// tolerance)` and `c_hat = d`. The goal center is the first sample when it is valid; any
149/// vertex inside the goal region is a solution.
150/// - Batches are drawn through [`Sampler::sample_informed`] with foci start and goal center
151/// and bound `c_best + tolerance`, falling back to rejection, and then filtered to valid
152/// states with `f_hat < c_best`; a batch can come out smaller than `batch_size` when
153/// [`INFORMED_ATTEMPTS`] draws per sample do not find one.
154/// - Queue keys go stale when a rewiring lowers the costs of a subtree; both queues are then
155/// re-sorted before the next pop, as OMPL does.
156/// - Edges are checked in travel direction, from tree parent to child.
157///
158/// The cost of [`BitStar::best_path`] never increases. Pruned states stay in memory until the
159/// planner is dropped.
160///
161/// # Examples
162///
163/// ```
164/// use rand_core::SeedableRng;
165/// use sampling_planning::{
166/// Euclidean, GoalRegion, UniformBox, Validity, ValidityChecker,
167/// informed::{BitStar, BitStarConfig},
168/// };
169///
170/// /// Free space everywhere.
171/// struct Free;
172///
173/// impl ValidityChecker<Euclidean<2>> for Free {
174/// fn check_state(&self, _: &[f64; 2]) -> Validity {
175/// Validity::Valid
176/// }
177///
178/// fn check_motion(&self, _: &Euclidean<2>, _: &[f64; 2], _: &[f64; 2]) -> Validity {
179/// Validity::Valid
180/// }
181/// }
182///
183/// let sampler = UniformBox::new([0.0, 0.0], [10.0, 10.0]);
184/// let config = BitStarConfig::new(1.5 * BitStarConfig::gamma_lower_bound(2, 100.0));
185/// let goal = GoalRegion::new([9.0, 9.0], 0.5);
186/// let mut bit = BitStar::new(Euclidean::<2>, sampler, Free, [1.0, 1.0], goal, config)
187/// .expect("valid");
188/// bit.run(2000, &mut rand_pcg::Pcg64Mcg::seed_from_u64(1));
189///
190/// assert!(bit.best_path().expect("free space").cost < 11.0);
191/// ```
192#[derive(Debug, Clone)]
193pub struct BitStar<Sp: StateSpace, Sa, C, N = LinearScan<<Sp as StateSpace>::State>> {
194 /// The configuration space.
195 space: Sp,
196 /// Draws the batches.
197 sampler: Sa,
198 /// Decides which states and motions are allowed.
199 checker: C,
200 /// The start state; node `0`.
201 start: Sp::State,
202 /// Where the path has to end.
203 goal: GoalRegion<Sp::State>,
204 /// The validated settings.
205 config: BitStarConfig,
206 /// All stored states, by node id; node `0` is the start.
207 nodes: Vec<Node<Sp::State>>,
208 /// An empty index, cloned for every batch.
209 prototype: N,
210 /// Index over the vertices and samples of the current batch.
211 nn: N,
212 /// The vertex queue `Q_V`.
213 vertex_queue: BinaryHeap<VertexEntry>,
214 /// The edge queue `Q_E`.
215 edge_queue: BinaryHeap<EdgeEntry>,
216 /// Whether a rewiring changed costs since the queues were keyed.
217 stale_keys: bool,
218 /// The vertices inside the goal region (`V_sol'n`).
219 solutions: Vec<usize>,
220 /// The cost of the best solution, `c_i`; infinite until one is found.
221 best_cost: f64,
222 /// The connection radius of the current batch, or the neighbor count for k-nearest.
223 neighborhood: Neighborhood,
224 /// The number of batches started.
225 batches: usize,
226 /// Reused buffer for neighbor queries.
227 near: Vec<usize>,
228}
229
230impl<Sp, Sa, C> BitStar<Sp, Sa, C>
231where
232 Sp: StateSpace,
233 Sa: Sampler<Sp::State>,
234 C: ValidityChecker<Sp>,
235{
236 /// Creates a planner with a [`LinearScan`] nearest-neighbor index.
237 ///
238 /// # Errors
239 ///
240 /// The same as [`BitStar::with_nearest_neighbors`].
241 pub fn new(
242 space: Sp,
243 sampler: Sa,
244 checker: C,
245 start: Sp::State,
246 goal: GoalRegion<Sp::State>,
247 config: BitStarConfig,
248 ) -> Result<Self, Error> {
249 Self::with_nearest_neighbors(
250 space,
251 sampler,
252 checker,
253 start,
254 goal,
255 config,
256 LinearScan::default(),
257 )
258 }
259}
260
261impl<Sp, Sa, C, N> BitStar<Sp, Sa, C, N>
262where
263 Sp: StateSpace,
264 Sa: Sampler<Sp::State>,
265 C: ValidityChecker<Sp>,
266 N: NearestNeighbors<Sp> + Clone,
267{
268 /// Creates a planner; every batch indexes its states in a clone of the given empty index.
269 ///
270 /// # Errors
271 ///
272 /// - [`Error::InvalidStart`] if `start` is not valid.
273 /// - [`Error::EmptyBatch`] if the batch size is zero.
274 /// - [`Error::InvalidRadius`] if `gamma`, the k-nearest constant or `max_radius` is out of
275 /// range.
276 pub fn with_nearest_neighbors(
277 space: Sp,
278 sampler: Sa,
279 checker: C,
280 start: Sp::State,
281 goal: GoalRegion<Sp::State>,
282 config: BitStarConfig,
283 nn: N,
284 ) -> Result<Self, Error> {
285 config.validate()?;
286
287 let validity = checker.check_state(&start);
288 if !validity.is_valid() {
289 return Err(Error::InvalidStart(validity));
290 }
291
292 let mut planner = Self {
293 space,
294 sampler,
295 checker,
296 start: start.clone(),
297 goal,
298 config,
299 nodes: Vec::new(),
300 nn: nn.clone(),
301 prototype: nn,
302 vertex_queue: BinaryHeap::new(),
303 edge_queue: BinaryHeap::new(),
304 stale_keys: false,
305 solutions: Vec::new(),
306 best_cost: f64::INFINITY,
307 neighborhood: Neighborhood::Radius(0.0),
308 batches: 0,
309 near: Vec::new(),
310 };
311 planner.plant_root(start);
312
313 Ok(planner)
314 }
315
316 /// Stores the start as vertex `0` and the goal center as the first sample, if it is valid.
317 fn plant_root(&mut self, start: Sp::State) {
318 let root = self.push_node(start, Kind::Vertex);
319 self.nodes[root].g = 0.0;
320 self.nodes[root].unexpanded = true;
321
322 if self.nodes[root].in_goal() {
323 self.solutions.push(root);
324 self.best_cost = 0.0;
325 }
326
327 let center = self.goal.center().clone();
328 if self.checker.check_state(¢er).is_valid() {
329 self.push_node(center, Kind::Sample);
330 }
331 }
332
333 /// Stores a new state of the given kind with its heuristics and returns its id.
334 fn push_node(&mut self, state: Sp::State, kind: Kind) -> usize {
335 let id = self.nodes.len();
336 let center_distance = self.space.distance(&state, self.goal.center());
337
338 self.nodes.push(Node {
339 g_hat: self.space.distance(&self.start, &state),
340 h_hat: (center_distance - self.goal.tolerance()).max(0.0),
341 g: f64::INFINITY,
342 state,
343 kind,
344 parent: None,
345 children: Vec::new(),
346 unexpanded: false,
347 fresh: true,
348 queued: false,
349 });
350
351 id
352 }
353
354 /// Runs one iteration: starts a new batch if both queues are empty, expands vertices while
355 /// the vertex queue is ahead, then processes the best edge. Returns whether the tree
356 /// changed.
357 pub fn step<R: Rng + ?Sized>(&mut self, rng: &mut R) -> bool {
358 if self.vertex_queue.is_empty() && self.edge_queue.is_empty() {
359 self.start_batch(rng);
360 }
361
362 self.resort_if_stale();
363
364 while self.best_vertex_value() <= self.best_edge_value() {
365 if !self.expand_next_vertex() {
366 break;
367 }
368 }
369
370 match self.edge_queue.pop() {
371 Some(edge) => self.process_edge(edge),
372 None => false,
373 }
374 }
375
376 /// Runs `iterations` iterations.
377 pub fn run<R: Rng + ?Sized>(&mut self, iterations: usize, rng: &mut R) {
378 for _ in 0..iterations {
379 self.step(rng);
380 }
381 }
382
383 /// Prunes, samples a batch, re-indexes and queues every vertex (Algorithm 1, lines 7-12).
384 fn start_batch<R: Rng + ?Sized>(&mut self, rng: &mut R) {
385 self.batches += 1;
386
387 for node in &mut self.nodes {
388 node.fresh = false;
389 }
390
391 if self.best_cost.is_finite() {
392 self.prune();
393 }
394
395 let sampled = self.sample_batch(rng);
396 self.reindex(sampled);
397
398 for id in 0..self.nodes.len() {
399 if self.nodes[id].kind == Kind::Vertex {
400 self.queue_vertex(id);
401 }
402 }
403 }
404
405 /// Removes the samples and vertices that cannot improve the solution; vertices that still
406 /// could as samples are recycled into the new batch (Algorithm 3).
407 fn prune(&mut self) {
408 let c = self.best_cost;
409
410 for node in &mut self.nodes {
411 if node.kind == Kind::Sample && node.f_hat() >= c {
412 node.kind = Kind::Pruned;
413 }
414 }
415
416 let mut vertices: Vec<usize> = (0..self.nodes.len())
417 .filter(|&id| self.nodes[id].kind == Kind::Vertex)
418 .collect();
419 vertices.sort_by(|&a, &b| self.nodes[a].g.total_cmp(&self.nodes[b].g).then(a.cmp(&b)));
420
421 for v in vertices {
422 let node = &self.nodes[v];
423 if node.kind == Kind::Vertex && (node.f_hat() > c || node.g + node.h_hat > c) {
424 self.disconnect(v);
425 }
426 }
427
428 // Children of a pruned vertex cost more than the solution too, so the sweep above
429 // removed them as well; this keeps the tree whole should rounding disagree.
430 for v in 1..self.nodes.len() {
431 if self.nodes[v].kind == Kind::Vertex && self.nodes[v].parent.is_none() {
432 self.disconnect(v);
433 }
434 }
435
436 self.solutions
437 .retain(|&id| self.nodes[id].kind == Kind::Vertex);
438 }
439
440 /// Removes vertex `v` from the tree; it becomes a fresh sample if it could still improve
441 /// the solution and is pruned otherwise. Its children are pruned by the caller's loop,
442 /// since their costs exceed the solution cost too.
443 fn disconnect(&mut self, v: usize) {
444 if let Some(parent) = self.nodes[v].parent.take() {
445 self.nodes[parent].children.retain(|&child| child != v);
446 }
447
448 let recycle = self.nodes[v].f_hat() < self.best_cost;
449 let node = &mut self.nodes[v];
450 node.kind = if recycle { Kind::Sample } else { Kind::Pruned };
451 node.g = f64::INFINITY;
452 node.fresh = recycle;
453 node.unexpanded = false;
454
455 for child in core::mem::take(&mut node.children) {
456 self.nodes[child].parent = None;
457 }
458 }
459
460 /// Draws up to `batch_size` valid samples that can improve the solution and returns how
461 /// many were added.
462 fn sample_batch<R: Rng + ?Sized>(&mut self, rng: &mut R) -> usize {
463 let mut added = 0;
464
465 for _ in 0..self.config.batch_size {
466 let informed = Informed {
467 space: &self.space,
468 checker: &self.checker,
469 start: &self.start,
470 goal: &self.goal,
471 best_cost: self.best_cost,
472 };
473
474 if let Some(state) = informed.draw(&mut self.sampler, rng) {
475 self.push_node(state, Kind::Sample);
476 added += 1;
477 }
478 }
479
480 added
481 }
482
483 /// Rebuilds the index over all vertices and samples and fixes this batch's neighbor rule
484 /// from `q = |V| + |X_unconn| - m` (eqs. 1 and 2).
485 fn reindex(&mut self, sampled: usize) {
486 self.nn = self.prototype.clone();
487 let mut live: usize = 0;
488
489 for (id, node) in self.nodes.iter().enumerate() {
490 if node.kind != Kind::Pruned {
491 self.nn.insert(id, node.state.clone());
492 live += 1;
493 }
494 }
495
496 let q = live.saturating_sub(sampled).max(2);
497 self.neighborhood = Neighborhood::for_batch(&self.config, q, self.space.dimension());
498 }
499
500 /// Queues vertex `v` for expansion.
501 fn queue_vertex(&mut self, v: usize) {
502 let node = &mut self.nodes[v];
503 node.queued = true;
504 self.vertex_queue.push(VertexEntry {
505 key: node.g + node.h_hat,
506 cost: node.g,
507 vertex: v,
508 });
509 }
510
511 /// Re-keys both queues after a rewiring lowered the costs of a subtree.
512 fn resort_if_stale(&mut self) {
513 if !self.stale_keys {
514 return;
515 }
516
517 self.stale_keys = false;
518
519 let vertices: Vec<usize> = self
520 .vertex_queue
521 .drain()
522 .map(|entry| entry.vertex)
523 .collect();
524 for v in vertices {
525 if self.nodes[v].queued && self.nodes[v].kind == Kind::Vertex {
526 self.nodes[v].queued = false;
527 self.queue_vertex(v);
528 }
529 }
530
531 let edges: Vec<EdgeEntry> = self.edge_queue.drain().collect();
532 for edge in edges {
533 self.queue_edge(edge.from, edge.to);
534 }
535 }
536
537 /// The best vertex-queue value `g_T(v) + h_hat(v)`, or infinity, dropping stale entries.
538 fn best_vertex_value(&mut self) -> f64 {
539 while let Some(entry) = self.vertex_queue.peek() {
540 let node = &self.nodes[entry.vertex];
541
542 if node.queued && node.kind == Kind::Vertex {
543 return entry.key;
544 }
545
546 self.vertex_queue.pop();
547 }
548
549 f64::INFINITY
550 }
551
552 /// The best edge-queue value `g_T(v) + c_hat(v, x) + h_hat(x)`, or infinity.
553 fn best_edge_value(&self) -> f64 {
554 self.edge_queue
555 .peek()
556 .map_or(f64::INFINITY, |edge| edge.key[0])
557 }
558
559 /// Pops the best vertex and queues its promising edges (Algorithm 2). Returns `false` when
560 /// the vertex queue is empty.
561 fn expand_next_vertex(&mut self) -> bool {
562 let Some(entry) = self.vertex_queue.pop() else {
563 return false;
564 };
565
566 let v = entry.vertex;
567 if !self.nodes[v].queued || self.nodes[v].kind != Kind::Vertex {
568 return true;
569 }
570
571 self.nodes[v].queued = false;
572
573 let mut near = core::mem::take(&mut self.near);
574 self.neighbors(v, &mut near);
575
576 let unexpanded = self.nodes[v].unexpanded;
577 for &x in &near {
578 if self.is_sample_edge_candidate(v, x, unexpanded)
579 || self.is_rewire_candidate(v, x, unexpanded)
580 {
581 self.queue_edge(v, x);
582 }
583 }
584
585 self.nodes[v].unexpanded = false;
586 self.near = near;
587
588 true
589 }
590
591 /// Whether the edge from vertex `v` to `x` is a candidate edge to an unconnected sample:
592 /// a fresh one, or any if `v` was never expanded, whose estimated solution cost beats the
593 /// current one.
594 fn is_sample_edge_candidate(&self, v: usize, x: usize, unexpanded: bool) -> bool {
595 let target = &self.nodes[x];
596
597 target.kind == Kind::Sample
598 && (unexpanded || target.fresh)
599 && self.nodes[v].g_hat + self.edge_estimate(v, x) + target.h_hat < self.best_cost
600 }
601
602 /// Whether the edge from the never-expanded vertex `v` to vertex `w` is a rewiring
603 /// candidate: not a tree edge, and it could improve both `w` and the solution.
604 fn is_rewire_candidate(&self, v: usize, w: usize, unexpanded: bool) -> bool {
605 let target = &self.nodes[w];
606 let through = self.nodes[v].g_hat + self.edge_estimate(v, w);
607
608 unexpanded
609 && target.kind == Kind::Vertex
610 && w != v
611 && target.parent != Some(v)
612 && through + target.h_hat < self.best_cost
613 && through < target.g
614 }
615
616 /// Replaces `out` with the vertices and samples near node `v` under this batch's rule,
617 /// excluding `v`.
618 fn neighbors(&self, v: usize, out: &mut Vec<usize>) {
619 let cap = self.config.max_radius;
620 let keep = |x| x != v && (cap.is_infinite() || self.edge_estimate(v, x) <= cap);
621
622 self.neighborhood
623 .query(&self.space, &self.nn, &self.nodes[v].state, keep, out);
624 }
625
626 /// The admissible edge cost estimate `c_hat(v, x) = d(v, x)`.
627 fn edge_estimate(&self, v: usize, x: usize) -> f64 {
628 self.space
629 .distance(&self.nodes[v].state, &self.nodes[x].state)
630 }
631
632 /// Queues the edge from vertex `v` to `x` with its current keys.
633 fn queue_edge(&mut self, v: usize, x: usize) {
634 let g = self.nodes[v].g;
635 let through = g + self.edge_estimate(v, x);
636
637 self.edge_queue.push(EdgeEntry {
638 key: [through + self.nodes[x].h_hat, through, g],
639 from: v,
640 to: x,
641 });
642 }
643
644 /// Processes the best edge (Algorithm 1, lines 15-34): adds or rewires its target when
645 /// the checked edge improves both the target and the solution, or ends the batch when even
646 /// the estimate cannot improve the solution. Returns whether the tree changed.
647 fn process_edge(&mut self, edge: EdgeEntry) -> bool {
648 let (v, x) = (edge.from, edge.to);
649
650 if self.nodes[v].kind != Kind::Vertex || self.nodes[x].kind == Kind::Pruned {
651 return false;
652 }
653
654 let g_v = self.nodes[v].g;
655 let estimate = g_v + self.edge_estimate(v, x);
656
657 if estimate + self.nodes[x].h_hat >= self.best_cost {
658 self.vertex_queue.clear();
659 self.edge_queue.clear();
660 return false;
661 }
662
663 if estimate >= self.nodes[x].g || !self.is_motion_valid(v, x) {
664 return false;
665 }
666
667 // With c = c_hat for a valid edge, the checked conditions equal the estimated ones.
668 self.connect(v, x, estimate);
669
670 true
671 }
672
673 /// Whether the motion from node `from` to node `to` checks as valid.
674 fn is_motion_valid(&self, from: usize, to: usize) -> bool {
675 self.checker
676 .check_motion(&self.space, &self.nodes[from].state, &self.nodes[to].state)
677 .is_valid()
678 }
679
680 /// Makes `v` the parent of `x` with cost `g`: adds the sample `x` to the tree, or rewires
681 /// the vertex `x` and lowers the costs of its subtree. Updates the solution.
682 fn connect(&mut self, v: usize, x: usize, g: f64) {
683 if let Some(old) = self.nodes[x].parent {
684 self.nodes[old].children.retain(|&child| child != x);
685 self.stale_keys = true;
686 }
687
688 let was_sample = self.nodes[x].kind == Kind::Sample;
689 let node = &mut self.nodes[x];
690 node.parent = Some(v);
691 node.g = g;
692 self.nodes[v].children.push(x);
693
694 if was_sample {
695 let node = &mut self.nodes[x];
696 node.kind = Kind::Vertex;
697 node.unexpanded = true;
698 self.queue_vertex(x);
699
700 if self.nodes[x].in_goal() {
701 self.solutions.push(x);
702 }
703 } else {
704 self.propagate_costs(x);
705 }
706
707 self.update_best_cost();
708 }
709
710 /// Recomputes the costs of all descendants of `x` from their parents' costs.
711 fn propagate_costs(&mut self, x: usize) {
712 let mut stack = self.nodes[x].children.clone();
713
714 while let Some(child) = stack.pop() {
715 let parent = self.nodes[child].parent.expect("a child has a parent");
716 self.nodes[child].g = self.nodes[parent].g + self.edge_estimate(parent, child);
717 stack.extend_from_slice(&self.nodes[child].children);
718 }
719 }
720
721 /// Sets `c_best` to the cost of the cheapest solution vertex.
722 fn update_best_cost(&mut self) {
723 self.best_cost = self
724 .solutions
725 .iter()
726 .map(|&id| self.nodes[id].g)
727 .fold(f64::INFINITY, f64::min);
728 }
729
730 /// The cheapest path found so far, or `None` if no vertex reached the goal yet. Its cost
731 /// never increases as iterations run.
732 #[must_use]
733 pub fn best_path(&self) -> Option<Path<Sp::State>> {
734 let best = self
735 .solutions
736 .iter()
737 .copied()
738 .min_by(|&a, &b| self.nodes[a].g.total_cmp(&self.nodes[b].g).then(a.cmp(&b)))?;
739 let mut states = Vec::new();
740 let mut current = Some(best);
741
742 while let Some(id) = current {
743 states.push(self.nodes[id].state.clone());
744 current = self.nodes[id].parent;
745 }
746
747 states.reverse();
748
749 Some(Path {
750 states,
751 cost: self.nodes[best].g,
752 })
753 }
754
755 /// The number of tree vertices, including the start.
756 #[must_use]
757 pub fn vertex_count(&self) -> usize {
758 self.count(Kind::Vertex)
759 }
760
761 /// The number of samples not connected to the tree.
762 #[must_use]
763 pub fn sample_count(&self) -> usize {
764 self.count(Kind::Sample)
765 }
766
767 /// The number of batches started so far.
768 #[must_use]
769 pub const fn batch_count(&self) -> usize {
770 self.batches
771 }
772
773 /// The number of stored states of `kind`.
774 fn count(&self, kind: Kind) -> usize {
775 self.nodes.iter().filter(|node| node.kind == kind).count()
776 }
777}