Skip to main content

multiobjective_search/
constrained.rs

1//! Resource-constrained shortest paths: the cheapest path whose second
2//! cost stays within a budget.
3//!
4//! A classic constrained relative of the bi-objective problem (the
5//! "constrained shortest path" class surveyed by Craveirinha et al.,
6//! Algorithms 17(6):222, 2024); solved here by BOA*'s pruning with the
7//! budget as an extra bound, stopping at the first solution.
8
9use alloc::collections::{BTreeMap, BinaryHeap};
10use alloc::vec::Vec;
11use core::cmp::Reverse;
12
13use search_core::{Cost, Heuristic};
14
15use crate::cost::add;
16use crate::graph::Graph;
17use crate::output::{Solution, Stats};
18
19/// Finds the path from `start` to a state that satisfies `is_goal` with
20/// the smallest first cost among those whose second cost is at most
21/// `budget`, the smallest second cost breaking ties; `None` if no path
22/// fits the budget.
23///
24/// Labels leave the open list in lexicographic `f` order. A label is
25/// dropped when `f2 > budget`, or, as in BOA*, when an earlier label at its
26/// state had a second cost no larger (it reaches everything this one does,
27/// no dearer). The first goal label is the answer: every label still open
28/// costs at least as much in the first objective.
29///
30/// Requirements, not checked at run time: non-negative costs and a
31/// `heuristic` consistent in both objectives and zero on every goal.
32/// Expansion counters go to `stats`.
33///
34/// # Examples
35///
36/// ```
37/// use multiobjective_search::{Graph, Stats, ZeroHeuristic, constrained_shortest_path};
38///
39/// /// Three routes from 0 to 1: (time, fuel).
40/// struct Routes;
41///
42/// impl Graph for Routes {
43///     type State = u8;
44///     type Weight = [u32; 2];
45///
46///     fn successors(&self, state: &u8, out: &mut Vec<(u8, [u32; 2])>) {
47///         if *state == 0 {
48///             out.extend([(1, [1, 9]), (1, [3, 5]), (1, [8, 1])]);
49///         }
50///     }
51/// }
52///
53/// let mut stats = Stats::default();
54/// let best = constrained_shortest_path(&Routes, ZeroHeuristic, 0, |s| *s == 1, 6, &mut stats);
55/// assert_eq!(best.map(|s| s.cost), Some([3, 5]));
56/// ```
57pub fn constrained_shortest_path<G, H, C, P>(
58    graph: &G,
59    mut heuristic: H,
60    start: G::State,
61    is_goal: P,
62    budget: C,
63    stats: &mut Stats,
64) -> Option<Solution<G::State, [C; 2]>>
65where
66    G: Graph<Weight = [C; 2]>,
67    H: Heuristic<G::State, [C; 2]>,
68    C: Cost,
69    P: Fn(&G::State) -> bool,
70{
71    let mut nodes: Vec<(G::State, [C; 2], Option<usize>)> = Vec::new();
72    let mut open = BinaryHeap::new();
73    let mut g2_min: BTreeMap<G::State, C> = BTreeMap::new();
74    let mut successors = Vec::new();
75
76    let h = heuristic.estimate(&start)?;
77    if h[1] > budget {
78        return None;
79    }
80
81    nodes.push((start, [C::ZERO; 2], None));
82    open.push(Reverse((h, 0)));
83    stats.generated += 1;
84
85    while let Some(Reverse((_, index))) = open.pop() {
86        let (here, g, _) = nodes[index].clone();
87        if g2_min.get(&here).is_some_and(|&m| g[1] >= m) {
88            continue;
89        }
90
91        g2_min.insert(here.clone(), g[1]);
92        if is_goal(&here) {
93            return Some(rebuild(&nodes, index));
94        }
95
96        stats.expanded += 1;
97        graph.successors(&here, &mut successors);
98        for (next, weight) in successors.drain(..) {
99            let g_next = add(g, weight);
100            if g2_min.get(&next).is_some_and(|&m| g_next[1] >= m) {
101                continue;
102            }
103
104            let Some(h) = heuristic.estimate(&next) else {
105                continue;
106            };
107
108            let f = add(g_next, h);
109            if f[1] > budget {
110                continue;
111            }
112
113            nodes.push((next, g_next, Some(index)));
114            open.push(Reverse((f, nodes.len() - 1)));
115            stats.generated += 1;
116        }
117    }
118
119    None
120}
121
122/// Rebuilds the solution ending in node `index`.
123pub(crate) fn rebuild<S: Clone, C: Copy, const N: usize>(
124    nodes: &[(S, [C; N], Option<usize>)],
125    index: usize,
126) -> Solution<S, [C; N]> {
127    let mut path = Vec::new();
128    let mut current = Some(index);
129
130    while let Some(i) = current {
131        path.push(nodes[i].0.clone());
132        current = nodes[i].2;
133    }
134
135    path.reverse();
136
137    Solution {
138        cost: nodes[index].1,
139        path,
140    }
141}