Skip to main content

multiobjective_search/
fptas.rs

1//! A fully polynomial-time approximation scheme for the resource
2//! constrained shortest path.
3//!
4//! Hansen 1980 and Warburton 1987 gave the first FPTASes for bicriterion
5//! and constrained paths; this follows the label-trimming form of
6//! Tsaggouris and Zaroliagis ("Multiobjective optimization: improved FPTAS
7//! for shortest paths and non-linear objectives with applications", 2009),
8//! as surveyed by Craveirinha et al., Algorithms 17(6):222, 2024, Section
9//! 2.3.
10
11use alloc::collections::{BTreeMap, VecDeque};
12use alloc::vec::Vec;
13
14use search_core::Cost;
15
16use crate::cost::add;
17use crate::epsilon::Epsilon;
18use crate::graph::Graph;
19use crate::output::{Solution, Stats};
20
21/// An FPTAS for the constrained shortest path: a path from `start` to a
22/// goal with second cost at most `budget` and first cost at most `1 + ε`
23/// times the optimum [`constrained_shortest_path`](crate::constrained_shortest_path)
24/// finds; `None` if no path fits the budget.
25///
26/// The reachable graph (`n` states, which must be finite) is relaxed in
27/// `n - 1` Bellman-Ford rounds. Each state keeps at most one label per
28/// box of first costs, the boxes growing geometrically by `1 + δ` with
29/// `δ = ε / (2 (n - 1))`, and in each box the label with the smallest
30/// second cost. So every state holds `O(n log(C) / ε)` labels, polynomial
31/// in the input and `1 / ε`, unlike the exact and ε-searches, whose label
32/// counts can grow exponentially. Trimming loses at most a factor `1 + δ`
33/// per edge of the optimal path, and `(1 + δ)^(n-1) <= e^(ε/2) <= 1 + ε`
34/// for `ε <= 2`; larger tolerances are capped at 2. `ε = 0` is exact.
35///
36/// Requirements, not checked at run time: non-negative costs and a finite
37/// reachable graph. Costs must convert into `u64` for the box arithmetic.
38/// Goal states are not expanded. Counters go to `stats`.
39///
40/// # Examples
41///
42/// ```
43/// use multiobjective_search::{Epsilon, Graph, Stats, fptas_constrained};
44///
45/// /// Three routes from 0 to 1: (time, fuel).
46/// struct Routes;
47///
48/// impl Graph for Routes {
49///     type State = u8;
50///     type Weight = [u32; 2];
51///
52///     fn successors(&self, state: &u8, out: &mut Vec<(u8, [u32; 2])>) {
53///         if *state == 0 {
54///             out.extend([(1, [10, 9]), (1, [30, 5]), (1, [31, 4])]);
55///         }
56///     }
57/// }
58///
59/// let mut stats = Stats::default();
60/// let tenth = Epsilon::new(1, 10);
61/// let best = fptas_constrained(&Routes, 0, |s| *s == 1, 5, tenth, &mut stats).unwrap();
62/// assert!(best.cost[1] <= 5 && best.cost[0] <= 33); // optimum 30, within 10 %
63/// ```
64pub fn fptas_constrained<G, C, P>(
65    graph: &G,
66    start: G::State,
67    is_goal: P,
68    budget: C,
69    eps: Epsilon,
70    stats: &mut Stats,
71) -> Option<Solution<G::State, [C; 2]>>
72where
73    G: Graph<Weight = [C; 2]>,
74    C: Cost + Into<u64>,
75    P: Fn(&G::State) -> bool,
76{
77    let reachable = Reachable::explore(graph, start, &is_goal);
78    let rounds = reachable.states.len().saturating_sub(1).max(1);
79    let mut grid = Grid::new(eps, rounds);
80
81    // Labels: (state index, cost, parent label).
82    let mut labels: Vec<(usize, [C; 2], Option<usize>)> = alloc::vec![(0, [C::ZERO; 2], None)];
83    let mut boxes: Vec<BTreeMap<u64, usize>> = alloc::vec![BTreeMap::new(); reachable.states.len()];
84    boxes[0].insert(0, 0);
85    let mut frontier = alloc::vec![0];
86    stats.generated += 1;
87
88    for _ in 0..rounds {
89        let mut next = Vec::new();
90        for &label in &frontier {
91            let (from, cost, _) = labels[label];
92            if reachable.goal[from] {
93                continue;
94            }
95
96            stats.expanded += 1;
97            for &(to, weight) in &reachable.edges[from] {
98                let c = add(cost, weight);
99                if c[1] > budget {
100                    continue;
101                }
102
103                let key = grid.index(c[0].into());
104                if boxes[to]
105                    .get(&key)
106                    .is_some_and(|&kept| labels[kept].1[1] <= c[1])
107                {
108                    continue;
109                }
110
111                labels.push((to, c, Some(label)));
112                boxes[to].insert(key, labels.len() - 1);
113                next.push(labels.len() - 1);
114                stats.generated += 1;
115            }
116        }
117
118        if next.is_empty() {
119            break;
120        }
121
122        frontier = next;
123    }
124
125    let best = (0..reachable.states.len())
126        .filter(|&s| reachable.goal[s])
127        .flat_map(|s| boxes[s].values().copied())
128        .min_by_key(|&l| labels[l].1)?;
129
130    let mut path = Vec::new();
131    let mut current = Some(best);
132    while let Some(l) = current {
133        path.push(reachable.states[labels[l].0].clone());
134        current = labels[l].2;
135    }
136
137    path.reverse();
138
139    Some(Solution {
140        cost: labels[best].1,
141        path,
142    })
143}
144
145/// The reachable part of the graph, with dense state indices (the start
146/// is 0).
147struct Reachable<S, W> {
148    /// States by index.
149    states: Vec<S>,
150    /// Outgoing edges by state index.
151    edges: Vec<Vec<(usize, W)>>,
152    /// Goal flags by state index.
153    goal: Vec<bool>,
154}
155
156impl<S: Clone + Ord, W> Reachable<S, W> {
157    /// Breadth-first exploration from `start`; goals are not expanded.
158    fn explore<G: Graph<State = S, Weight = W>>(
159        graph: &G,
160        start: S,
161        is_goal: impl Fn(&S) -> bool,
162    ) -> Self {
163        let mut index = BTreeMap::new();
164        let mut reachable = Self {
165            states: Vec::new(),
166            edges: Vec::new(),
167            goal: Vec::new(),
168        };
169        let mut queue = VecDeque::new();
170        let mut buffer = Vec::new();
171
172        index.insert(start.clone(), 0);
173        reachable.push(start, &is_goal);
174        queue.push_back(0);
175
176        while let Some(i) = queue.pop_front() {
177            if reachable.goal[i] {
178                continue;
179            }
180
181            graph.successors(&reachable.states[i].clone(), &mut buffer);
182            for (to, weight) in buffer.drain(..) {
183                let j = *index.entry(to.clone()).or_insert_with(|| {
184                    queue.push_back(reachable.states.len());
185                    reachable.push(to, &is_goal);
186                    reachable.states.len() - 1
187                });
188                reachable.edges[i].push((j, weight));
189            }
190        }
191
192        reachable
193    }
194
195    /// Adds a state.
196    fn push(&mut self, state: S, is_goal: &impl Fn(&S) -> bool) {
197        self.goal.push(is_goal(&state));
198        self.states.push(state);
199        self.edges.push(Vec::new());
200    }
201}
202
203/// Geometric boxes of first costs: box 0 holds 0, then `[t_k, t_(k+1))`
204/// with `t_0 = 1` and `t_(k+1) = max(t_k + 1, floor(t_k (1 + δ)))`, so any
205/// two costs in one box are within `1 + δ` of each other.
206struct Grid {
207    /// `δ = num / den`.
208    num: u128,
209    /// See `num`; positive.
210    den: u128,
211    /// The thresholds `t_0, t_1, ...` computed so far.
212    thresholds: Vec<u128>,
213}
214
215impl Grid {
216    /// The grid for tolerance `eps` (capped at 2) over `rounds` rounds.
217    fn new(eps: Epsilon, rounds: usize) -> Self {
218        let (mut num, den) = (u128::from(eps.num()), u128::from(eps.den()));
219        if num > 2 * den {
220            num = 2 * den;
221        }
222
223        let rounds = u128::try_from(rounds).expect("state counts fit in u128");
224        Self {
225            num,
226            den: den * 2 * rounds,
227            thresholds: alloc::vec![1],
228        }
229    }
230
231    /// The box of first cost `value`.
232    fn index(&mut self, value: u64) -> u64 {
233        if value == 0 {
234            return 0;
235        }
236
237        let value = u128::from(value);
238        while *self.thresholds.last().expect("never empty") <= value {
239            let t = *self.thresholds.last().expect("never empty");
240            let grown = t
241                .checked_mul(self.den + self.num)
242                .map_or(u128::MAX, |p| p / self.den);
243            self.thresholds.push(grown.max(t + 1));
244        }
245
246        let k = self.thresholds.partition_point(|&t| t <= value);
247        u64::try_from(k).expect("box counts fit in u64")
248    }
249}