heuristic_search/cost.rs
1//! Priority arithmetic on costs ([`CostExt`]) and heuristic weights ([`Weight`]).
2//!
3//! The [`Cost`] and [`CostExt`] traits come from `search-core`. [`CostExt`] adds the
4//! subtraction and conversion to `f64` that a few searches need for their priorities, such
5//! as the `(G - g) / h` order of [`ana_star`](crate::ana_star), the `2g + h - h_opposite` key
6//! of [`dibbs`](crate::dibbs) and [`bae_star`](crate::bae_star), and the potential of
7//! [`dps`](crate::dps).
8
9use search_core::Cost;
10pub use search_core::CostExt;
11
12/// A rational heuristic weight `w = numerator / denominator` for Weighted A*.
13///
14/// Rational so that integer costs keep exact arithmetic: Weighted A* orders by
15/// `denominator * g + numerator * h`, which sorts like `g + w * h`.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
17pub struct Weight {
18 /// Numerator of the weight.
19 numerator: u32,
20 /// Denominator of the weight. Never zero.
21 denominator: u32,
22}
23
24impl Weight {
25 /// Weight `1`, which makes Weighted A* behave like A*.
26 pub const ONE: Self = Self {
27 numerator: 1,
28 denominator: 1,
29 };
30
31 /// Creates the weight `numerator / denominator`.
32 ///
33 /// Weights below `1` are allowed; they bias the search towards Dijkstra's order.
34 ///
35 /// # Panics
36 ///
37 /// Panics if `denominator` is zero.
38 #[must_use]
39 pub const fn new(numerator: u32, denominator: u32) -> Self {
40 assert!(denominator != 0, "weight denominator must not be zero");
41
42 Self {
43 numerator,
44 denominator,
45 }
46 }
47
48 /// Creates the integer weight `w`.
49 #[must_use]
50 pub const fn integer(w: u32) -> Self {
51 Self::new(w, 1)
52 }
53
54 /// The numerator of the weight.
55 #[must_use]
56 pub const fn numerator(self) -> u32 {
57 self.numerator
58 }
59
60 /// The denominator of the weight. Never zero.
61 #[must_use]
62 pub const fn denominator(self) -> u32 {
63 self.denominator
64 }
65}
66
67/// A cost or infinity, for bounds and backed-up values that must be able to exceed every
68/// cost.
69///
70/// Ordered with every [`Extended::Finite`] value below [`Extended::Infinite`]. Saturated
71/// costs are no substitute: a saturated sum ties with real costs at the maximum.
72#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
73pub(crate) enum Extended<C> {
74 /// A finite cost.
75 Finite(C),
76 /// Larger than every cost: no bound, or a subtree without any goal.
77 Infinite,
78}
79
80impl<C: Cost> Extended<C> {
81 /// `g + h` for an estimate `h`, where a dead end (`None`) is infinite.
82 pub(crate) fn f(g: C, h: Option<C>) -> Self {
83 h.map_or(Self::Infinite, |h| Self::Finite(g.saturating_add(h)))
84 }
85}
86
87/// Returns `true` if `cost <= weight * bound`, computed as `den * cost <= num * bound`
88/// without division.
89pub(crate) fn within<C: Cost>(cost: C, weight: Weight, bound: C) -> bool {
90 cost.saturating_times(weight.denominator()) <= bound.saturating_times(weight.numerator())
91}