Skip to main content

multiobjective_search/
tpa.rs

1//! TPA: an exact anytime method for multi-objective combinatorial problems
2//! that splits the objective space into boxes and solves one
3//! augmented-Tchebycheff subproblem per box.
4//!
5//! Domínguez-Ríos, Chicano, Alba, "Effective anytime algorithm for
6//! multiobjective combinatorial optimization problems", arXiv 2403.08807
7//! (Algorithms 2 to 4).
8
9use alloc::collections::{BTreeMap, BinaryHeap};
10use alloc::vec::Vec;
11use core::cmp::Reverse;
12
13use search_core::{BigUint, Budget, Cost, ExactArith, ExactNumber, Heuristic};
14
15use crate::anytime_boa::{AnytimeFront, ApproxFactor};
16use crate::cost::{add, weakly_dominates};
17use crate::graph::Graph;
18use crate::output::{Solution, Stats};
19use crate::pareto::Front;
20
21/// One augmented-Tchebycheff subproblem `P(u, ω)` (Algorithm 2, line 7) in
22/// exact integer form.
23///
24/// With `ω_i = 1 / d_i` and `ϵ = 1 / K`, the objective
25/// `max_i ω_i (f_i - z^I_i) + ϵ Σ_i ω_i (f_i - z^I_i)` times `K · Π d_i`
26/// is the integer [`Scalarization::score`]
27/// `K · max_i W_i (f_i - z^I_i) + Σ_i W_i (f_i - z^I_i)` with
28/// `W_i = Π_j d_j / d_i`, and the paper's test `obj < 1` is
29/// `score < `[`Scalarization::limit`].
30#[derive(Debug, Clone)]
31pub struct Scalarization<C, const N: usize> {
32    /// The ideal point `z^I`.
33    ideal: [C; N],
34    /// `W_i`.
35    weights: [BigUint; N],
36    /// `K = 1 / ϵ`.
37    k: BigUint,
38    /// `K · Π d_i`.
39    limit: BigUint,
40}
41
42impl<C: ExactArith<Exact = BigUint>, const N: usize> Scalarization<C, N> {
43    /// The integer objective of a cost vector; components below the ideal
44    /// point count as zero, which keeps it a lower bound for partial costs.
45    #[must_use]
46    pub fn score(&self, cost: &[C; N]) -> BigUint {
47        let gaps: [BigUint; N] = core::array::from_fn(|i| {
48            if cost[i] > self.ideal[i] {
49                self.weights[i].clone() * cost[i].exact().abs_diff(&self.ideal[i].exact())
50            } else {
51                BigUint::zero()
52            }
53        });
54        let max = gaps.iter().max().cloned().unwrap_or_else(BigUint::zero);
55        let sum = gaps.into_iter().fold(BigUint::zero(), |s, g| s + g);
56
57        self.k.clone() * max + sum
58    }
59
60    /// The score below which a point lies in the box (the paper's `obj < 1`).
61    #[must_use]
62    pub const fn limit(&self) -> &BigUint {
63        &self.limit
64    }
65}
66
67/// A single-objective solver for TPA's subproblems: the solution with the
68/// smallest [`Scalarization::score`] over the whole feasible set, with its
69/// cost vector, or `None` if there is none.
70pub trait TchebycheffSolver<C, const N: usize> {
71    /// The solution type.
72    type Solution;
73
74    /// Minimizes `scalarization.score` over all solutions.
75    fn minimize(&mut self, scalarization: &Scalarization<C, N>)
76    -> Option<(Self::Solution, [C; N])>;
77}
78
79/// What [`tpa`] returns: the solutions with their points, and whether the
80/// front is complete.
81pub type TpaResult<X, C, const N: usize> = (Vec<(X, [C; N])>, bool);
82
83/// Adjacency lists of an explored graph.
84type Adjacency<S, W> = BTreeMap<S, Vec<(S, W)>>;
85
86/// A search zone: the half-open box `[lower, upper)` with a direction and
87/// a priority.
88#[derive(Debug, Clone)]
89struct Zone<C, const N: usize> {
90    /// Lower bound.
91    lower: [C; N],
92    /// Upper bound, exclusive.
93    upper: [C; N],
94    /// The numerator of the paper's (reduced) scaled priority; the
95    /// denominator `Π (z^N_i - z^I_i)` is the same for every zone.
96    priority: BigUint,
97}
98
99/// TPA (Algorithm 2) over any solver: the exact Pareto front of the problem
100/// whose ideal point is `ideal` and whose costs all lie below `nadir`
101/// (strictly, in every objective), found box by box.
102///
103/// The objective space starts as one box `[ideal, nadir)`. Each step
104/// selects a box from the next direction's queue in turn (Algorithm 3), by
105/// highest priority, and solves the augmented-Tchebycheff subproblem with
106/// weights `ω_i = 1 / max(1, u_i - z^I_i)` and `ϵ = 1 / (2p(r - 1))`
107/// (`r` the widest range). A score below the limit means a new
108/// non-dominated point inside the box (Holzmann and Smith's Theorem 5); it
109/// is reported, and every box whose upper bound lies above it is split by
110/// the p-partition (Definition 1, Algorithm 4), boxes with comparable
111/// upper bounds are joined (Definition 3), and the new boxes get the
112/// reduced scaled priority (Definition 4). Otherwise the box is dropped.
113/// Every point found is efficient, none twice, and the front is complete
114/// when no box is left (Theorem 1).
115///
116/// `on_point` gets each new solution and point; `budget` sees the solver
117/// and is checked before each subproblem.
118///
119/// Returns the solutions found and whether the front is complete.
120///
121/// # Panics
122///
123/// Panics if `ideal` is not below `nadir` in every objective.
124pub fn tpa<C, S, const N: usize>(
125    solver: &mut S,
126    ideal: [C; N],
127    nadir: [C; N],
128    mut on_point: impl FnMut(&S::Solution, [C; N]),
129    mut budget: impl FnMut(&S) -> bool,
130) -> TpaResult<S::Solution, C, N>
131where
132    C: Cost + ExactArith<Exact = BigUint>,
133    S: TchebycheffSolver<C, N>,
134{
135    assert!(
136        (0..N).all(|i| ideal[i] < nadir[i]),
137        "the ideal point must lie below the nadir bound"
138    );
139    let e = |c: C| c.exact();
140    let range = |i: usize| e(nadir[i]).abs_diff(&e(ideal[i]));
141    let widest = (0..N).map(range).max().unwrap_or_else(BigUint::one);
142    let p = BigUint::from(u128::try_from(2 * N).expect("small"));
143    // K = 2p(r - 1), at least 1.
144    let k = (p * widest.abs_diff(&BigUint::one())).max(BigUint::one());
145
146    let mut queues: Vec<Vec<Zone<C, N>>> = (0..N).map(|_| Vec::new()).collect();
147    let whole = Zone {
148        lower: ideal,
149        upper: nadir,
150        priority: volume(&ideal, &nadir),
151    };
152    queues[0].push(whole);
153    let mut direction = N - 1;
154    let mut found = Vec::new();
155
156    while queues.iter().any(|q| !q.is_empty()) {
157        if budget(solver) {
158            return (found, false);
159        }
160
161        // Algorithm 3: the next non-empty direction, its highest priority.
162        direction = (direction + 1) % N;
163        while queues[direction].is_empty() {
164            direction = (direction + 1) % N;
165        }
166
167        let pick = (0..queues[direction].len())
168            .max_by(|&a, &b| {
169                queues[direction][a]
170                    .priority
171                    .cmp(&queues[direction][b].priority)
172            })
173            .expect("non-empty");
174        let upper = queues[direction][pick].upper;
175        let scalarization = scalarize(&ideal, &upper, &k);
176
177        let inside = (0..N).all(|i| ideal[i] < upper[i]);
178        match solver.minimize(&scalarization) {
179            Some((solution, point))
180                if inside && scalarization.score(&point) < scalarization.limit =>
181            {
182                on_point(&solution, point);
183                update(&mut queues, &point);
184                found.push((solution, point));
185            }
186            _ => {
187                queues[direction].swap_remove(pick);
188            }
189        }
190    }
191
192    (found, true)
193}
194
195/// The subproblem for a box with upper bound `upper`.
196fn scalarize<C: Cost + ExactArith<Exact = BigUint>, const N: usize>(
197    ideal: &[C; N],
198    upper: &[C; N],
199    k: &BigUint,
200) -> Scalarization<C, N> {
201    let d: [BigUint; N] = core::array::from_fn(|i| {
202        upper[i]
203            .exact()
204            .abs_diff(&ideal[i].exact())
205            .max(BigUint::one())
206    });
207    let product = d.iter().fold(BigUint::one(), |p, x| p * x.clone());
208    let weights = core::array::from_fn(|i| {
209        d.iter()
210            .enumerate()
211            .filter(|&(j, _)| j != i)
212            .fold(BigUint::one(), |p, (_, x)| p * x.clone())
213    });
214
215    Scalarization {
216        ideal: *ideal,
217        weights,
218        k: k.clone(),
219        limit: k.clone() * product,
220    }
221}
222
223/// `Π (upper_i - lower_i)`, zero for an empty box.
224fn volume<C: Cost + ExactArith<Exact = BigUint>, const N: usize>(
225    lower: &[C; N],
226    upper: &[C; N],
227) -> BigUint {
228    if (0..N).any(|i| lower[i] >= upper[i]) {
229        return BigUint::zero();
230    }
231
232    (0..N).fold(BigUint::one(), |p, i| {
233        p * upper[i].exact().abs_diff(&lower[i].exact())
234    })
235}
236
237/// Algorithm 4: p-partition of every box whose upper bound lies above `z`,
238/// then joins of boxes with comparable upper bounds per direction.
239fn update<C: Cost + ExactArith<Exact = BigUint>, const N: usize>(
240    queues: &mut [Vec<Zone<C, N>>],
241    z: &[C; N],
242) {
243    let boxes: Vec<Zone<C, N>> = queues
244        .iter_mut()
245        .flat_map(|q| {
246            let (split, kept): (Vec<_>, Vec<_>) = core::mem::take(q)
247                .into_iter()
248                .partition(|b| (0..N).all(|i| z[i] < b.upper[i]));
249            *q = kept;
250            split
251        })
252        .collect();
253
254    for b in boxes {
255        let hat: [C; N] = core::array::from_fn(|i| z[i].max(b.lower[i]));
256        for (i, queue) in queues.iter_mut().enumerate() {
257            // B_i(z) = [(l_1..l_i, ẑ_{i+1}..ẑ_p), (u_1..u_{i-1}, ẑ_i, u_{i+1}..u_p)].
258            let lower = core::array::from_fn(|j| if j <= i { b.lower[j] } else { hat[j] });
259            let upper = core::array::from_fn(|j| if j == i { hat[j] } else { b.upper[j] });
260            let mut priority = volume(&lower, &upper);
261            if priority == BigUint::zero() {
262                continue;
263            }
264
265            if i == N - 1 {
266                // The part [l, z] cannot hold a non-dominated point.
267                priority = priority.abs_diff(&volume(&b.lower, z));
268            }
269
270            queue.push(Zone {
271                lower,
272                upper,
273                priority,
274            });
275        }
276    }
277
278    for queue in queues.iter_mut() {
279        join(queue);
280    }
281}
282
283/// Joins boxes with comparable upper bounds (Definition 3) until none are.
284fn join<C: Cost + ExactArith<Exact = BigUint>, const N: usize>(queue: &mut Vec<Zone<C, N>>) {
285    'outer: loop {
286        for a in 0..queue.len() {
287            for b in 0..queue.len() {
288                if a != b && weakly_dominates(&queue[a].upper, &queue[b].upper) {
289                    let (small, large) = (queue[a].clone(), queue[b].clone());
290                    let lower = core::array::from_fn(|i| small.lower[i].min(large.lower[i]));
291                    let priority = volume(&lower, &large.upper);
292                    let (hi, lo) = (a.max(b), a.min(b));
293                    queue.swap_remove(hi);
294                    queue.swap_remove(lo);
295                    queue.push(Zone {
296                        lower,
297                        upper: large.upper,
298                        priority,
299                    });
300                    continue 'outer;
301                }
302            }
303        }
304
305        return;
306    }
307}
308
309/// The TPA subproblem on a graph: the path to a goal that minimizes the
310/// scalarized score, by best-first search on the score of `g + h` with
311/// per-state dominance pruning.
312pub struct PathTchebycheff<'a, G: Graph, H, P> {
313    /// The graph.
314    graph: &'a G,
315    /// An admissible heuristic.
316    heuristic: H,
317    /// The start state.
318    start: <G as Graph>::State,
319    /// Goal test.
320    is_goal: P,
321    /// Effort counters over all subproblems.
322    stats: Stats,
323}
324
325impl<G: Graph, H, P> core::fmt::Debug for PathTchebycheff<'_, G, H, P> {
326    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
327        f.debug_struct("PathTchebycheff")
328            .field("stats", &self.stats)
329            .finish_non_exhaustive()
330    }
331}
332
333impl<G, H, C, P, const N: usize> TchebycheffSolver<C, N> for PathTchebycheff<'_, G, H, P>
334where
335    G: Graph<Weight = [C; N]>,
336    H: Heuristic<G::State, [C; N]>,
337    C: Cost + ExactArith<Exact = BigUint>,
338    P: Fn(&G::State) -> bool,
339{
340    type Solution = Vec<G::State>;
341
342    fn minimize(&mut self, scalarization: &Scalarization<C, N>) -> Option<(Vec<G::State>, [C; N])> {
343        let mut nodes: Vec<(G::State, [C; N], Option<usize>)> = Vec::new();
344        let mut open = BinaryHeap::new();
345        let mut closed: BTreeMap<G::State, Front<C, N>> = BTreeMap::new();
346        let mut successors = Vec::new();
347
348        let h = self.heuristic.estimate(&self.start)?;
349        nodes.push((self.start.clone(), [C::ZERO; N], None));
350        open.push(Reverse((scalarization.score(&h), h, 0)));
351
352        while let Some(Reverse((_, _, index))) = open.pop() {
353            let (state, g) = (nodes[index].0.clone(), nodes[index].1);
354            if closed.get(&state).is_some_and(|c| c.weakly_dominates(&g)) {
355                continue;
356            }
357
358            closed.entry(state.clone()).or_default().insert(g);
359            if (self.is_goal)(&state) {
360                let mut path = Vec::new();
361                let mut at = Some(index);
362                while let Some(i) = at {
363                    path.push(nodes[i].0.clone());
364                    at = nodes[i].2;
365                }
366
367                path.reverse();
368                return Some((path, g));
369            }
370
371            self.stats.expanded += 1;
372            self.graph.successors(&state, &mut successors);
373            for (next, w) in successors.drain(..) {
374                let g_next = add(g, w);
375                if closed
376                    .get(&next)
377                    .is_some_and(|c| c.weakly_dominates(&g_next))
378                {
379                    continue;
380                }
381
382                let Some(h) = self.heuristic.estimate(&next) else {
383                    continue;
384                };
385                let f = add(g_next, h);
386                nodes.push((next, g_next, Some(index)));
387                open.push(Reverse((scalarization.score(&f), f, nodes.len() - 1)));
388                self.stats.generated += 1;
389            }
390        }
391
392        None
393    }
394}
395
396/// TPA for shortest paths: the exact Pareto front from `start` to a state
397/// that satisfies `is_goal`, found well spread over the objective space
398/// first and completed if the budget allows.
399///
400/// The ideal point and a strict upper bound of the nadir point (the sum of
401/// all reachable edge costs plus one, since Pareto-optimal paths are
402/// simple) come from one exploration of the finite reachable graph and one
403/// Dijkstra per objective; each subproblem is a [`PathTchebycheff`] search
404/// with `heuristic`. `on_front` gets the solutions after every new point,
405/// with an infinite factor until the front is complete (TPA has no
406/// approximation guarantee before that) and zero when it is. `budget` sees
407/// the expansions so far and is checked before each subproblem.
408///
409/// Requirements: non-negative integer-like costs (`ExactArith` into
410/// `BigUint`), a finite reachable graph, an admissible `heuristic` zero on
411/// goals.
412///
413/// # Examples
414///
415/// ```
416/// use multiobjective_search::{Graph, ZeroHeuristic, boa_star, tpa_paths};
417///
418/// /// Four routes from 0 to 1.
419/// struct Routes;
420///
421/// impl Graph for Routes {
422///     type State = u8;
423///     type Weight = [u32; 2];
424///
425///     fn successors(&self, state: &u8, out: &mut Vec<(u8, [u32; 2])>) {
426///         if *state == 0 {
427///             out.extend([(1, [1, 9]), (1, [3, 5]), (1, [5, 3]), (1, [9, 1])]);
428///         }
429///     }
430/// }
431///
432/// let result = tpa_paths(&Routes, ZeroHeuristic, 0, |s| *s == 1, |_, _| {}, |_: &_| false);
433/// assert!(result.complete);
434/// assert_eq!(result.solutions, boa_star(&Routes, ZeroHeuristic, 0, |s| *s == 1).solutions);
435/// ```
436pub fn tpa_paths<G, H, C, P, const N: usize>(
437    graph: &G,
438    heuristic: H,
439    start: G::State,
440    is_goal: P,
441    mut on_front: impl FnMut(&[Solution<G::State, [C; N]>], ApproxFactor<C>),
442    mut budget: impl Budget<Stats>,
443) -> AnytimeFront<G::State, C, N>
444where
445    G: Graph<Weight = [C; N]>,
446    H: Heuristic<G::State, [C; N]>,
447    C: Cost + ExactArith<Exact = BigUint>,
448    P: Fn(&G::State) -> bool,
449{
450    let Some((ideal, nadir)) = bounds(graph, &start, &is_goal) else {
451        return AnytimeFront {
452            solutions: Vec::new(),
453            factor: ApproxFactor::Zero,
454            complete: true,
455            stats: Stats::default(),
456        };
457    };
458
459    let mut solver = PathTchebycheff {
460        graph,
461        heuristic,
462        start,
463        is_goal,
464        stats: Stats::default(),
465    };
466    let mut front: Vec<Solution<G::State, [C; N]>> = Vec::new();
467
468    // Without any positive edge cost every path costs zero: one subproblem
469    // finds the only point.
470    if (0..N).any(|i| nadir[i] <= ideal[i]) {
471        let only = solver.minimize(&scalarize(&ideal, &ideal, &BigUint::one()));
472        front.extend(only.map(|(path, cost)| Solution { cost, path }));
473        on_front(&front, ApproxFactor::Zero);
474        return AnytimeFront {
475            solutions: front,
476            factor: ApproxFactor::Zero,
477            complete: true,
478            stats: solver.stats,
479        };
480    }
481
482    let (_, complete) = tpa(
483        &mut solver,
484        ideal,
485        nadir,
486        |path, cost| {
487            front.push(Solution {
488                cost,
489                path: path.clone(),
490            });
491            front.sort_by_key(|s| s.cost);
492            on_front(&front, ApproxFactor::Infinite);
493        },
494        |solver| budget.exhausted(&solver.stats),
495    );
496
497    let factor = if complete {
498        ApproxFactor::Zero
499    } else {
500        ApproxFactor::Infinite
501    };
502    if complete {
503        on_front(&front, factor);
504    }
505
506    AnytimeFront {
507        solutions: front,
508        factor,
509        complete,
510        stats: solver.stats,
511    }
512}
513
514/// The ideal point and a strict nadir bound of the paths from `start` to a
515/// goal; `None` if no goal is reachable.
516fn bounds<G, C, P, const N: usize>(
517    graph: &G,
518    start: &G::State,
519    is_goal: &P,
520) -> Option<([C; N], [C; N])>
521where
522    G: Graph<Weight = [C; N]>,
523    C: Cost,
524    P: Fn(&G::State) -> bool,
525{
526    // Explore, summing every edge's costs.
527    let mut seen = alloc::collections::BTreeSet::from([start.clone()]);
528    let mut stack = alloc::vec![start.clone()];
529    let mut sum = [C::ZERO; N];
530    let mut edges = Vec::new();
531    let mut adjacency: Adjacency<G::State, [C; N]> = BTreeMap::new();
532    while let Some(s) = stack.pop() {
533        if is_goal(&s) {
534            continue;
535        }
536
537        graph.successors(&s, &mut edges);
538        for (t, w) in &edges {
539            sum = add(sum, *w);
540            if seen.insert(t.clone()) {
541                stack.push(t.clone());
542            }
543        }
544
545        adjacency.insert(s, core::mem::take(&mut edges));
546    }
547
548    let ideal: Option<[C; N]> = (0..N)
549        .map(|i| {
550            let mut dist: BTreeMap<G::State, C> = BTreeMap::new();
551            let mut heap = BinaryHeap::from([Reverse((C::ZERO, start.clone()))]);
552            while let Some(Reverse((d, s))) = heap.pop() {
553                if dist.contains_key(&s) {
554                    continue;
555                }
556
557                dist.insert(s.clone(), d);
558                if is_goal(&s) {
559                    return Some(d);
560                }
561
562                for (t, w) in adjacency.get(&s).into_iter().flatten() {
563                    heap.push(Reverse((d + w[i], t.clone())));
564                }
565            }
566
567            None
568        })
569        .collect::<Option<Vec<C>>>()
570        .map(|v| core::array::from_fn(|i| v[i]));
571
572    // Pareto-optimal paths are simple, so no cost exceeds the edge sums;
573    // `2 · sum + unit` is strictly above them, with `unit` the smallest
574    // positive edge cost (Cost has no one).
575    let unit = adjacency
576        .values()
577        .flatten()
578        .flat_map(|(_, w)| *w)
579        .filter(|&c| c > C::ZERO)
580        .min();
581    ideal.map(|ideal| {
582        let unit = unit.unwrap_or(C::ZERO);
583        (ideal, sum.map(|c| c.saturating_add(c).saturating_add(unit)))
584    })
585}