1use alloc::{collections::BinaryHeap, vec::Vec};
4
5use rand_core::Rng;
6
7use super::{Error, RrtStarConfig, targets::draw_target};
8use crate::graph::Entry;
9use crate::{
10 LinearScan, NearestNeighbors, Path, Problem, Sampler, StateSpace, Steering, ValidityChecker,
11};
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15enum EdgeStatus {
16 Unchecked,
18 Valid,
20 Invalid,
22}
23
24#[derive(Debug, Clone)]
26struct Edge {
27 to: usize,
29 cost: f64,
31 status: EdgeStatus,
33}
34
35#[derive(Debug, Clone)]
37struct Vertex<S> {
38 state: S,
40 g: f64,
43 lmc: f64,
45 h: f64,
47 parent: Option<usize>,
49 out: Vec<Edge>,
51}
52
53#[derive(Clone)]
114pub struct RrtSharp<Sp: StateSpace, Sa, C, St, N = LinearScan<<Sp as StateSpace>::State>> {
115 problem: Problem<Sp, Sa, C, St>,
117 config: RrtStarConfig,
119 vertices: Vec<Vertex<Sp::State>>,
121 nn: N,
123 queue: BinaryHeap<Entry>,
125 goal_vertices: Vec<usize>,
127 best_goal: Option<usize>,
129 near: Vec<usize>,
131}
132
133impl<Sp, Sa, C, St> RrtSharp<Sp, Sa, C, St>
134where
135 Sp: StateSpace,
136 Sa: Sampler<Sp::State>,
137 C: ValidityChecker<Sp>,
138 St: Steering<Sp>,
139{
140 pub fn new(problem: Problem<Sp, Sa, C, St>, config: RrtStarConfig) -> Result<Self, Error> {
146 Self::with_nearest_neighbors(problem, config, LinearScan::default())
147 }
148}
149
150impl<Sp, Sa, C, St, N> RrtSharp<Sp, Sa, C, St, N>
151where
152 Sp: StateSpace,
153 Sa: Sampler<Sp::State>,
154 C: ValidityChecker<Sp>,
155 St: Steering<Sp>,
156 N: NearestNeighbors<Sp>,
157{
158 pub fn with_nearest_neighbors(
168 problem: Problem<Sp, Sa, C, St>,
169 config: RrtStarConfig,
170 mut nn: N,
171 ) -> Result<Self, Error> {
172 config.validate()?;
173
174 if !(0.0..=1.0).contains(&config.goal_bias) {
175 return Err(Error::GoalBiasOutOfRange);
176 }
177
178 let validity = problem.checker.check_state(&problem.start);
179 if !validity.is_valid() {
180 return Err(Error::InvalidStart(validity));
181 }
182
183 let start = problem.start.clone();
184 let in_goal = problem.goal.contains(&problem.space, &start);
185 nn.insert(0, start.clone());
186
187 Ok(Self {
188 vertices: alloc::vec![Vertex {
189 h: heuristic(&problem, &start),
190 state: start,
191 g: 0.0,
192 lmc: 0.0,
193 parent: None,
194 out: Vec::new(),
195 }],
196 goal_vertices: if in_goal { alloc::vec![0] } else { Vec::new() },
197 best_goal: in_goal.then_some(0),
198 problem,
199 config,
200 nn,
201 queue: BinaryHeap::new(),
202 near: Vec::new(),
203 })
204 }
205
206 pub fn step<R: Rng + ?Sized>(&mut self, rng: &mut R) -> bool {
208 let Some((nearest, new)) = self.extend_target(rng) else {
209 return false;
210 };
211
212 let id = self.add_vertex(new, nearest);
213 self.enqueue_if_promising(id);
214 self.replan();
215
216 true
217 }
218
219 pub fn run<R: Rng + ?Sized>(&mut self, iterations: usize, rng: &mut R) {
221 for _ in 0..iterations {
222 self.step(rng);
223 }
224 }
225
226 fn extend_target<R: Rng + ?Sized>(&mut self, rng: &mut R) -> Option<(usize, Sp::State)> {
229 let bound = self.informed_bound();
230 let target = draw_target(&mut self.problem, self.config.goal_bias, bound, rng);
231 let space = &self.problem.space;
232 let nearest = self
233 .nn
234 .nearest(space, &target)
235 .expect("the graph always holds the start");
236 let from = &self.vertices[nearest].state;
237 let new = self.problem.steering.steer(space, from, &target);
238
239 self.problem
240 .checker
241 .check_motion(space, from, &new)
242 .is_valid()
243 .then_some((nearest, new))
244 }
245
246 fn informed_bound(&self) -> Option<f64> {
249 if !self.config.informed {
250 return None;
251 }
252
253 let best = self.best_goal?;
254
255 Some(self.vertices[best].g + self.problem.goal.tolerance())
256 }
257
258 fn add_vertex(&mut self, state: Sp::State, nearest: usize) -> usize {
262 let id = self.vertices.len();
263 let mut near = core::mem::take(&mut self.near);
264 self.config.neighbors(
265 &self.problem.space,
266 &self.nn,
267 &state,
268 id + 1,
269 |other| &self.vertices[other].state,
270 &mut near,
271 );
272
273 if !near.contains(&nearest) {
274 near.push(nearest);
275 }
276
277 self.vertices.push(Vertex {
278 h: heuristic(&self.problem, &state),
279 state: state.clone(),
280 g: f64::INFINITY,
281 lmc: f64::INFINITY,
282 parent: None,
283 out: Vec::new(),
284 });
285 self.link(id, nearest, &near);
286 self.choose_parent(id);
287
288 if self.problem.goal.contains(&self.problem.space, &state) {
289 self.goal_vertices.push(id);
290 }
291
292 self.nn.insert(id, state);
293 self.near = near;
294
295 id
296 }
297
298 fn link(&mut self, id: usize, nearest: usize, near: &[usize]) {
301 for &other in near {
302 let cost = self
303 .problem
304 .space
305 .distance(&self.vertices[other].state, &self.vertices[id].state);
306 let into = if other == nearest {
307 EdgeStatus::Valid
308 } else {
309 EdgeStatus::Unchecked
310 };
311
312 self.vertices[other].out.push(Edge {
313 to: id,
314 cost,
315 status: into,
316 });
317 let back = self
318 .problem
319 .space
320 .distance(&self.vertices[id].state, &self.vertices[other].state);
321 self.vertices[id].out.push(Edge {
322 to: other,
323 cost: back,
324 status: EdgeStatus::Unchecked,
325 });
326 }
327 }
328
329 fn choose_parent(&mut self, id: usize) {
332 let mut candidates: Vec<(f64, usize, usize)> = self.vertices[id]
333 .out
334 .iter()
335 .map(|edge| edge.to)
336 .filter_map(|from| {
337 let slot = self.vertices[from].out.iter().rposition(|e| e.to == id)?;
338 let cost = self.vertices[from].g + self.vertices[from].out[slot].cost;
339
340 cost.is_finite().then_some((cost, from, slot))
341 })
342 .collect();
343 candidates.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1)));
344
345 for (cost, from, slot) in candidates {
346 if self.is_edge_valid(from, slot) {
347 self.vertices[id].lmc = cost;
348 self.vertices[id].parent = Some(from);
349 return;
350 }
351 }
352 }
353
354 fn is_edge_valid(&mut self, from: usize, slot: usize) -> bool {
356 let edge = &self.vertices[from].out[slot];
357
358 match edge.status {
359 EdgeStatus::Valid => true,
360 EdgeStatus::Invalid => false,
361 EdgeStatus::Unchecked => {
362 let valid = self
363 .problem
364 .checker
365 .check_motion(
366 &self.problem.space,
367 &self.vertices[from].state,
368 &self.vertices[edge.to].state,
369 )
370 .is_valid();
371 self.vertices[from].out[slot].status = if valid {
372 EdgeStatus::Valid
373 } else {
374 EdgeStatus::Invalid
375 };
376
377 valid
378 }
379 }
380 }
381
382 fn enqueue_if_promising(&mut self, id: usize) {
385 let vertex = &self.vertices[id];
386 let key = vertex.lmc + vertex.h;
387
388 if vertex.lmc < vertex.g && key < self.best_cost() {
389 self.queue.push(Entry {
390 cost: key,
391 node: id,
392 });
393 }
394 }
395
396 fn best_cost(&self) -> f64 {
398 self.best_goal
399 .map_or(f64::INFINITY, |id| self.vertices[id].g)
400 }
401
402 fn replan(&mut self) {
405 while let Some(&Entry { cost: key, node }) = self.queue.peek() {
406 if key >= self.best_cost() {
407 return;
408 }
409
410 self.queue.pop();
411 if self.is_stale(key, node) {
412 continue;
413 }
414
415 self.vertices[node].g = self.vertices[node].lmc;
416 self.record_goal(node);
417 self.relax_out_edges(node);
418 }
419 }
420
421 #[expect(
424 clippy::float_cmp,
425 reason = "a current entry carries exactly the key computed from the current lmc"
426 )]
427 fn is_stale(&self, key: f64, node: usize) -> bool {
428 let vertex = &self.vertices[node];
429
430 vertex.g <= vertex.lmc || key != vertex.lmc + vertex.h
431 }
432
433 fn record_goal(&mut self, node: usize) {
435 let in_goal = self
436 .problem
437 .goal
438 .contains(&self.problem.space, &self.vertices[node].state);
439
440 if in_goal && self.vertices[node].g < self.best_cost() {
441 self.best_goal = Some(node);
442 }
443 }
444
445 fn relax_out_edges(&mut self, node: usize) {
448 let g = self.vertices[node].g;
449
450 for slot in 0..self.vertices[node].out.len() {
451 let Edge { to, cost, .. } = self.vertices[node].out[slot];
452 let candidate = g + cost;
453
454 if candidate < self.vertices[to].lmc && self.is_edge_valid(node, slot) {
455 self.vertices[to].lmc = candidate;
456 self.vertices[to].parent = Some(node);
457 self.enqueue_if_promising(to);
458 }
459 }
460 }
461
462 #[must_use]
465 pub fn best_path(&self) -> Option<Path<Sp::State>> {
466 let goal = self.best_goal?;
467 let mut states = Vec::new();
468 let mut cost = 0.0;
469 let mut current = Some(goal);
470
471 while let Some(id) = current {
472 let vertex = &self.vertices[id];
473 states.push(vertex.state.clone());
474
475 if let Some(parent) = vertex.parent {
476 cost += self
477 .problem
478 .space
479 .distance(&self.vertices[parent].state, &vertex.state);
480 }
481
482 current = vertex.parent;
483 }
484
485 states.reverse();
486
487 Some(Path { states, cost })
488 }
489
490 #[must_use]
492 pub fn node_count(&self) -> usize {
493 self.vertices.len()
494 }
495}
496
497fn heuristic<Sp: StateSpace, Sa, C, St>(
499 problem: &Problem<Sp, Sa, C, St>,
500 state: &Sp::State,
501) -> f64 {
502 (problem.space.distance(state, problem.goal.center()) - problem.goal.tolerance()).max(0.0)
503}
504
505#[cfg(test)]
506mod tests {
507 use super::*;
508 use crate::graph::{Arc, shortest_path};
509 use crate::{Euclidean, GoalRegion, StraightLine, UniformBox, Validity, discretized_motion};
510 use rand_core::SeedableRng;
511
512 struct Wall;
514
515 impl ValidityChecker<Euclidean<2>> for Wall {
516 fn check_state(&self, s: &[f64; 2]) -> Validity {
517 if (4.0..=6.0).contains(&s[0]) && s[1] < 8.0 {
518 Validity::Invalid
519 } else {
520 Validity::Valid
521 }
522 }
523
524 fn check_motion(&self, space: &Euclidean<2>, from: &[f64; 2], to: &[f64; 2]) -> Validity {
525 discretized_motion(space, from, to, 0.02, |s| self.check_state(s))
526 }
527 }
528
529 fn planner() -> RrtSharp<Euclidean<2>, UniformBox<2>, Wall, StraightLine> {
531 let problem = Problem {
532 space: Euclidean::<2>,
533 sampler: UniformBox::new([0.0; 2], [10.0; 2]),
534 checker: Wall,
535 steering: StraightLine::new(1.0),
536 start: [1.0, 1.0],
537 goal: GoalRegion::new([9.0, 1.0], 0.5),
538 };
539 let gamma = 1.5 * RrtStarConfig::gamma_lower_bound(2, 100.0);
540
541 RrtSharp::new(problem, RrtStarConfig::new(gamma, 1.0)).expect("valid")
542 }
543
544 fn eager_optimum(planner: &RrtSharp<Euclidean<2>, UniformBox<2>, Wall, StraightLine>) -> f64 {
546 let space = Euclidean::<2>;
547 let vertices = &planner.vertices;
548 let route = shortest_path(
549 vertices.len(),
550 0,
551 |id| planner.goal_vertices.contains(&id),
552 |id, out: &mut Vec<Arc>| {
553 out.clear();
554 out.extend(
555 vertices[id]
556 .out
557 .iter()
558 .filter(|e| {
559 Wall.check_motion(&space, &vertices[id].state, &vertices[e.to].state)
560 .is_valid()
561 })
562 .map(|e| Arc {
563 to: e.to,
564 cost: e.cost,
565 edge: None,
566 }),
567 );
568 },
569 );
570
571 route.map_or(f64::INFINITY, |route| route.cost)
572 }
573
574 #[test]
575 fn replanning_keeps_the_graph_optimum_with_lazy_checks() {
576 let mut planner = planner();
577 let mut rng = rand_pcg::Pcg64Mcg::seed_from_u64(2);
578 let mut checked = 0;
579
580 for _ in 0..8 {
581 planner.run(250, &mut rng);
582
583 let best = planner.best_path().map_or(f64::INFINITY, |path| path.cost);
584 let optimum = eager_optimum(&planner);
585 assert!((best - optimum).abs() < 1e-9, "{best} vs {optimum}");
586 checked += usize::from(best.is_finite());
587 }
588
589 assert!(checked > 4, "solved early enough");
590
591 let unchecked = planner
592 .vertices
593 .iter()
594 .flat_map(|v| &v.out)
595 .filter(|e| e.status == EdgeStatus::Unchecked)
596 .count();
597 assert!(unchecked > 0, "lazy checking skips edges");
598 }
599}