multiobjective_search/apex.rs
1//! A*pex: approximate multi-objective search over apex-path pairs.
2//!
3//! Zhang, Salzman, Kumar, Felner, Hernández, Koenig: "A*pex: Efficient
4//! Approximate Multi-Objective Search on Graphs", ICAPS 2022.
5//!
6//! An *apex-path pair* at a state is an apex, a cost vector component-wise
7//! no worse than every path the pair stands for, and one real
8//! *representative* path to the state. The pair is *ε-bounded* when the
9//! representative's `f` is within the tolerances of the apex's `f` in every
10//! objective: `g_i(rep) + h_i <= (1 + ε_i) · (apex_i + h_i)` (the paper's
11//! Contribution 3). With a consistent heuristic, extending both along an
12//! edge keeps the pair bounded, and at a goal (`h = 0`) the representative
13//! is within the tolerances of every path the pair stands for. The search
14//! is NAMOA*dr over apexes (Algorithm 2 of the paper), with three
15//! additions:
16//!
17//! - a new pair merges into an open pair at the same state when the merged
18//! pair (component-wise minimum apex, a representative chosen by a
19//! [`MergeRule`]) is ε-bounded;
20//! - a goal pair merges into a solution pair the same way;
21//! - a pair is dropped when some solution's representative is within the
22//! tolerances of its `f` in objectives `1..N`. That solution's apex then
23//! drops to the component-wise minimum of the two, so that later merges
24//! of the solution keep covering the dropped pair.
25//!
26//! ```mermaid
27//! graph TD
28//! pop[Pop min apex f] --> pruned{"a solution within (1+ε) of f, or<br/>f dominated by an expanded apex? (objectives 1..N)"}
29//! pruned -- yes --> pop
30//! pruned -- no --> close[Archive apex]
31//! close --> goal{Goal?}
32//! goal -- yes --> sol[Merge into a solution if bounded,<br/>else add as solution] --> pop
33//! goal -- no --> expand[Extend apex and representative, prune] --> merge[Merge into an open pair<br/>at the state if bounded, else push] --> pop
34//! ```
35//!
36//! Differences from the paper, which keep its guarantee: a goal predicate
37//! replaces the single goal, so solution pairs at different goal states
38//! may merge (they are never extended, and `h = 0` at every goal); and
39//! dominated or duplicate representatives are dropped from the output.
40
41mod anytime;
42
43use alloc::collections::{BTreeMap, BinaryHeap};
44use alloc::vec::Vec;
45use core::cmp::Reverse;
46use core::mem;
47
48use search_core::{Cost, Heuristic, WideMul};
49
50use crate::cost::add;
51use crate::epsilon::Epsilon;
52use crate::graph::{Graph, ZeroHeuristic};
53use crate::output::{Output, Solution, Stats};
54use crate::pareto::{Front, TruncatedFront};
55
56pub use anytime::{AnytimeApex, apex_star_anytime, apex_star_anytime_with};
57
58/// How [`apex_star_with`] picks the representative path when it merges two
59/// apex-path pairs. Both are the paper's; the choice never affects the
60/// guarantee, only how many pairs merge.
61#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
62pub enum MergeRule {
63 /// The paper's G method, the one its experiments favour: of the two representatives that
64 /// keep the merged pair ε-bounded, take the one with the larger slack
65 /// `min_i (1 + ε_i - f_i(π) / f_i(A)) / ε_i`, which leaves the most room
66 /// for later merges. The first pair's representative wins a tie.
67 /// Compared exactly by cross-multiplication with [`WideMul`].
68 #[default]
69 Greedy,
70 /// The paper's L method: take the representative whose cost is
71 /// lexicographically smaller read from the last objective to the first
72 /// (the first pair's on a tie), and do not merge if it is not
73 /// ε-bounded. For two objectives this is PP-A*'s bottom-right path.
74 ReverseLex,
75}
76
77/// A*pex: finds a set of solutions that covers the Pareto-optimal front
78/// within a factor `1 + eps[i]` in each objective `i`, for any number of
79/// objectives `N`.
80///
81/// Requirements, not checked at run time:
82///
83/// - edge costs are non-negative;
84/// - `heuristic` is consistent in every objective and zero on every goal.
85///
86/// Guarantees:
87///
88/// - for every Pareto-optimal cost vector `s` some returned solution `r`
89/// has `r[i] <= (1 + eps[i]) · s[i]` for every `i`;
90/// - the returned solutions are real paths with their exact costs, mutually
91/// non-dominated and sorted lexicographically ascending; they need not be
92/// Pareto-optimal themselves;
93/// - when two pairs merge, the representative is chosen by the paper's
94/// greedy G method ([`MergeRule::Greedy`]); [`apex_star_with`] selects
95/// another rule;
96/// - `eps = [Epsilon::ZERO; N]` returns exactly the cost vectors of
97/// [`emoa_star`](crate::emoa_star).
98///
99/// # Why the guarantee holds
100///
101/// This is Lemma 4 and Theorem 1 of the paper. Pop order keeps the first
102/// component of `f` non-decreasing (Lemma 1; a merged apex is the minimum
103/// of two apexes whose first components are both at least the last popped
104/// one), which is all that the truncated checks against expanded apexes
105/// and solutions need. Each pruning or merging step covers a pair relative
106/// to its own apex, and apexes only go down along these steps, so the
107/// tolerances never compound: an expanded apex at or below a pruned one
108/// covers it, a merged apex covers both pairs (Lemma 3), a solution whose
109/// apex was lowered to the pruned pair's `f` keeps covering it through
110/// later merges, and a bounded goal pair's representative covers its apex.
111///
112/// # Examples
113///
114/// ```
115/// use multiobjective_search::{Epsilon, Graph, ZeroHeuristic, apex_star};
116///
117/// /// Three routes from 0 to 1 with three objectives.
118/// struct Routes;
119///
120/// impl Graph for Routes {
121/// type State = u8;
122/// type Weight = [u32; 3];
123///
124/// fn successors(&self, state: &u8, out: &mut Vec<(u8, [u32; 3])>) {
125/// if *state == 0 {
126/// out.extend([(1, [100, 100, 50]), (1, [104, 98, 51]), (1, [50, 200, 100])]);
127/// }
128/// }
129/// }
130///
131/// let eps = [Epsilon::new(1, 10); 3];
132/// let out = apex_star(&Routes, ZeroHeuristic, 0, |s| *s == 1, eps);
133/// let costs: Vec<_> = out.solutions.iter().map(|s| s.cost).collect();
134/// // [100, 100, 50] leaves the merged apex [100, 98, 50] more slack than
135/// // [104, 98, 51], so it represents the merged pair and covers both.
136/// assert_eq!(costs, [[50, 200, 100], [100, 100, 50]]);
137/// ```
138pub fn apex_star<G, H, C, P, const N: usize>(
139 graph: &G,
140 heuristic: H,
141 start: G::State,
142 is_goal: P,
143 eps: [Epsilon; N],
144) -> Output<G::State, [C; N]>
145where
146 G: Graph<Weight = [C; N]>,
147 H: Heuristic<G::State, [C; N]>,
148 C: Cost + WideMul,
149 P: Fn(&G::State) -> bool,
150{
151 apex_star_with(graph, heuristic, start, is_goal, eps, MergeRule::Greedy)
152}
153
154/// [`apex_star`] with a chosen [`MergeRule`] for the representative of
155/// merged pairs.
156///
157/// Requirements and guarantees are those of [`apex_star`], for every rule.
158///
159/// # Examples
160///
161/// ```
162/// use multiobjective_search::{Epsilon, Graph, MergeRule, ZeroHeuristic, apex_star_with};
163///
164/// /// Two routes from 0 to 1 that merge within 50 %.
165/// struct Routes;
166///
167/// impl Graph for Routes {
168/// type State = u8;
169/// type Weight = [u32; 2];
170///
171/// fn successors(&self, state: &u8, out: &mut Vec<(u8, [u32; 2])>) {
172/// if *state == 0 {
173/// out.extend([(1, [10, 13]), (1, [14, 10])]);
174/// }
175/// }
176/// }
177///
178/// let eps = [Epsilon::new(1, 2); 2];
179/// let run = |rule| apex_star_with(&Routes, ZeroHeuristic, 0, |s| *s == 1, eps, rule);
180/// // Against the merged apex [10, 10], [10, 13] is 30 % over in one
181/// // objective and [14, 10] is 40 % over: the greedy rule keeps the first.
182/// assert_eq!(run(MergeRule::Greedy).solutions[0].cost, [10, 13]);
183/// // The reverse-lexicographic rule prefers the smaller last objective.
184/// assert_eq!(run(MergeRule::ReverseLex).solutions[0].cost, [14, 10]);
185/// ```
186pub fn apex_star_with<G, H, C, P, const N: usize>(
187 graph: &G,
188 heuristic: H,
189 start: G::State,
190 is_goal: P,
191 eps: [Epsilon; N],
192 rule: MergeRule,
193) -> Output<G::State, [C; N]>
194where
195 G: Graph<Weight = [C; N]>,
196 H: Heuristic<G::State, [C; N]>,
197 C: Cost + WideMul,
198 P: Fn(&G::State) -> bool,
199{
200 let mut search = Search::new(graph, heuristic, is_goal, eps, rule, false);
201 search.push_start(start);
202 search.run();
203
204 search.into_output()
205}
206
207/// One path in the path arena: its last state, its cost and its parent.
208struct PathNode<S, C, const N: usize> {
209 /// The state this path ends in.
210 state: S,
211 /// Cost vector of the path from the start.
212 g: [C; N],
213 /// Arena index of the path without its last edge; `None` for the start.
214 parent: Option<usize>,
215}
216
217/// An apex-path pair.
218#[derive(Clone, Copy)]
219struct Pair<C, const N: usize> {
220 /// The apex: component-wise no worse than every path the pair stands
221 /// for. Not itself the cost of a path in general.
222 apex: [C; N],
223 /// Path arena index of the representative path.
224 rep: usize,
225 /// Heuristic estimate at the pair's state.
226 h: [C; N],
227 /// `false` once the pair was merged into another; its open-list entry
228 /// is then skipped.
229 alive: bool,
230}
231
232/// Per-state bookkeeping.
233struct StateInfo<C, const N: usize> {
234 /// Apexes of the pairs expanded (or recorded as solutions) here,
235 /// compared on objectives `1..N`.
236 closed: TruncatedFront<C, N>,
237 /// Pair arena indices of this state's pairs on the open list.
238 open: Vec<usize>,
239 /// Full apexes of the pairs expanded here; only filled when the search
240 /// records them.
241 expanded: Front<C, N>,
242}
243
244/// Mutable state of one A*pex run.
245struct Search<'a, G: Graph, H, C, P, const N: usize> {
246 /// The graph being searched.
247 graph: &'a G,
248 /// Per-objective lower bounds on the remaining cost.
249 heuristic: H,
250 /// Goal test.
251 is_goal: P,
252 /// Tolerances per objective.
253 eps: [Epsilon; N],
254 /// How merges pick the representative.
255 rule: MergeRule,
256 /// Every representative path; pairs and parents index into it.
257 paths: Vec<PathNode<G::State, C, N>>,
258 /// Every pair ever pushed; open-list entries index into it.
259 pairs: Vec<Pair<C, N>>,
260 /// Open list as a min-heap on `(apex f, pair index)`, compared
261 /// lexicographically.
262 open: BinaryHeap<Reverse<([C; N], usize)>>,
263 /// Per-state bookkeeping. Absent means "not reached yet".
264 states: BTreeMap<G::State, StateInfo<C, N>>,
265 /// The solution pairs. Their apexes only go down, by merges and by
266 /// pruning updates.
267 solutions: Vec<Pair<C, N>>,
268 /// Reused successor buffer, empty between expansions.
269 successors: Vec<(G::State, [C; N])>,
270 /// Whether [`StateInfo::expanded`] is filled, for
271 /// [`expanded_apexes`].
272 record: bool,
273 /// Effort counters.
274 stats: Stats,
275}
276
277/// Runs A*pex from every state in `starts` with no goal and the zero
278/// heuristic, and returns, per reached state, the non-dominated apexes of
279/// the pairs expanded there.
280///
281/// Every path from a start to a state `s` has a cost weakly dominated by
282/// one of `s`'s apexes (case 1 of the paper's Lemma 4; with no goal the
283/// solution case never applies), and the apexes are within the tolerances
284/// of real path costs. This is how Wolff et al. (arXiv 2606.20644,
285/// Section 6) build a multi-valued heuristic, on the reversed graph.
286pub(crate) fn expanded_apexes<G, C, const N: usize>(
287 graph: &G,
288 starts: impl IntoIterator<Item = G::State>,
289 eps: [Epsilon; N],
290) -> BTreeMap<G::State, Front<C, N>>
291where
292 G: Graph<Weight = [C; N]>,
293 C: Cost + WideMul,
294{
295 let never = |_: &G::State| false;
296 let mut search = Search::new(graph, ZeroHeuristic, never, eps, MergeRule::Greedy, true);
297 for start in starts {
298 search.push_start(start);
299 }
300
301 search.run();
302 search
303 .states
304 .into_iter()
305 .filter(|(_, info)| !info.expanded.is_empty())
306 .map(|(state, info)| (state, info.expanded))
307 .collect()
308}
309
310impl<'a, G, H, C, P, const N: usize> Search<'a, G, H, C, P, N>
311where
312 G: Graph<Weight = [C; N]>,
313 H: Heuristic<G::State, [C; N]>,
314 C: Cost + WideMul,
315 P: Fn(&G::State) -> bool,
316{
317 /// Creates an empty search; `record` fills [`StateInfo::expanded`].
318 fn new(
319 graph: &'a G,
320 heuristic: H,
321 is_goal: P,
322 eps: [Epsilon; N],
323 rule: MergeRule,
324 record: bool,
325 ) -> Self {
326 Self {
327 graph,
328 heuristic,
329 is_goal,
330 eps,
331 rule,
332 paths: Vec::new(),
333 pairs: Vec::new(),
334 open: BinaryHeap::new(),
335 states: BTreeMap::new(),
336 solutions: Vec::new(),
337 successors: Vec::new(),
338 record,
339 stats: Stats::default(),
340 }
341 }
342
343 /// Processes pairs until the open list is empty.
344 fn run(&mut self) {
345 while let Some(Reverse((f, index))) = self.open.pop() {
346 self.process(f, index);
347 }
348 }
349
350 /// Pushes the start pair, unless the heuristic reports a dead end.
351 fn push_start(&mut self, start: G::State) {
352 if let Some(h) = self.heuristic.estimate(&start) {
353 let rep = self.new_path(start, [C::ZERO; N], None);
354 self.push(Pair {
355 apex: [C::ZERO; N],
356 rep,
357 h,
358 alive: true,
359 });
360 }
361 }
362
363 /// Handles one pair taken from the open list: skip it if merged away,
364 /// prune it, record a solution, or expand it.
365 fn process(&mut self, f: [C; N], index: usize) {
366 let pair = self.pairs[index];
367 if !pair.alive {
368 return;
369 }
370
371 let state = self.paths[pair.rep].state.clone();
372 self.info_mut(&state).open.retain(|&i| i != index);
373 if self.is_pruned(&state, &pair.apex, &f) {
374 return;
375 }
376
377 let record = self.record;
378 let info = self.info_mut(&state);
379 info.closed.insert(pair.apex);
380 if record {
381 info.expanded.insert(pair.apex);
382 }
383
384 if (self.is_goal)(&state) {
385 self.insert_solution(pair);
386 } else {
387 self.expand(pair);
388 }
389 }
390
391 /// Returns `true` if a pair at `state` with apex `apex` and apex
392 /// estimate `f` is covered by a solution or by an expanded pair there
393 /// (the paper's `is_dominated`, lines 19 to 26).
394 fn is_pruned(&mut self, state: &G::State, apex: &[C; N], f: &[C; N]) -> bool {
395 self.is_covered_by_solution(f)
396 || self
397 .states
398 .get(state)
399 .is_some_and(|info| info.closed.weakly_dominates(apex))
400 }
401
402 /// Returns `true` if some solution's representative is within the
403 /// tolerances of `f` in objectives `1..N`, and lowers that solution's
404 /// apex to the component-wise minimum with `f` (lines 20 to 22).
405 ///
406 /// Objective 0 needs no check: the solution's apex is no larger there
407 /// than `f` (Lemma 1), and its bounded representative is within the
408 /// tolerance of that apex.
409 fn is_covered_by_solution(&mut self, f: &[C; N]) -> bool {
410 let paths = &self.paths;
411 let eps = &self.eps;
412 let Some(solution) = self.solutions.iter_mut().find(|s| {
413 let g = &paths[s.rep].g;
414 (1..N).all(|i| eps[i].within(g[i], f[i]))
415 }) else {
416 return false;
417 };
418
419 solution.apex = core::array::from_fn(|i| solution.apex[i].min(f[i]));
420 true
421 }
422
423 /// Returns `true` if `cost[i] <= (1 + eps[i]) · bound[i]` for every `i`.
424 fn within(&self, cost: &[C; N], bound: &[C; N]) -> bool {
425 (0..N).all(|i| self.eps[i].within(cost[i], bound[i]))
426 }
427
428 /// Extends the apex and the representative of `pair` along every
429 /// outgoing edge and inserts the surviving pairs.
430 fn expand(&mut self, pair: Pair<C, N>) {
431 self.stats.expanded += 1;
432
433 let mut successors = mem::take(&mut self.successors);
434 let from = self.paths[pair.rep].state.clone();
435 self.graph.successors(&from, &mut successors);
436
437 for (state, weight) in successors.drain(..) {
438 let Some(h) = self.heuristic.estimate(&state) else {
439 continue;
440 };
441
442 let apex = add(pair.apex, weight);
443 if self.is_pruned(&state, &apex, &add(apex, h)) {
444 continue;
445 }
446
447 let g = add(self.paths[pair.rep].g, weight);
448 let rep = self.new_path(state, g, Some(pair.rep));
449 self.insert(Pair {
450 apex,
451 rep,
452 h,
453 alive: true,
454 });
455 }
456
457 self.successors = successors;
458 }
459
460 /// Merges the goal pair `pair` into the first solution pair it merges
461 /// with, or adds it as a new solution (line 11 and lines 27 to 35).
462 fn insert_solution(&mut self, pair: Pair<C, N>) {
463 let found = self
464 .solutions
465 .iter()
466 .enumerate()
467 .find_map(|(k, &other)| self.merge(pair, other).map(|merged| (k, merged)));
468
469 match found {
470 Some((k, merged)) => self.solutions[k] = merged,
471 None => self.solutions.push(pair),
472 }
473 }
474
475 /// Merges `pair` into the first open pair at its state that it merges
476 /// with, or pushes it as is (line 17 and lines 27 to 35).
477 fn insert(&mut self, pair: Pair<C, N>) {
478 let state = self.paths[pair.rep].state.clone();
479 let open = self
480 .states
481 .get(&state)
482 .map_or(&[][..], |info| &info.open[..]);
483 let found = open.iter().enumerate().find_map(|(position, &other)| {
484 self.merge(pair, self.pairs[other])
485 .map(|merged| (position, other, merged))
486 });
487
488 if let Some((position, other, merged)) = found {
489 self.pairs[other].alive = false;
490 self.info_mut(&state).open.swap_remove(position);
491 self.push(merged);
492 return;
493 }
494
495 self.push(pair);
496 }
497
498 /// The pair with the component-wise minimum apex of `a` and `b` and the
499 /// representative chosen by [`Search::rule`], or `None` if no choice
500 /// the rule allows is ε-bounded (lines 29 and 30).
501 ///
502 /// `a` and `b` share `h`: they are at the same state, or both at goals,
503 /// where `h` is zero.
504 fn merge(&self, a: Pair<C, N>, b: Pair<C, N>) -> Option<Pair<C, N>> {
505 let with_rep = |rep| Pair {
506 apex: core::array::from_fn(|i| a.apex[i].min(b.apex[i])),
507 rep,
508 h: a.h,
509 alive: true,
510 };
511 let (for_a, for_b) = (with_rep(a.rep), with_rep(b.rep));
512
513 match self.rule {
514 MergeRule::Greedy => {
515 let excess_a = self.excess(&for_a);
516 let excess_b = self.excess(&for_b);
517 match (excess_a, excess_b) {
518 (Some(x), Some(y)) if x.is_greater(y) => Some(for_b),
519 (Some(_), _) => Some(for_a),
520 (None, Some(_)) => Some(for_b),
521 (None, None) => None,
522 }
523 }
524 MergeRule::ReverseLex => {
525 let (ga, gb) = (&self.paths[a.rep].g, &self.paths[b.rep].g);
526 let merged = if gb.iter().rev().lt(ga.iter().rev()) {
527 for_b
528 } else {
529 for_a
530 };
531
532 self.is_bounded(&merged).then_some(merged)
533 }
534 }
535 }
536
537 /// Returns `true` if the representative's `f` is within the tolerances
538 /// of the apex's `f` in every objective.
539 fn is_bounded(&self, pair: &Pair<C, N>) -> bool {
540 let f_rep = add(self.paths[pair.rep].g, pair.h);
541 self.within(&f_rep, &add(pair.apex, pair.h))
542 }
543
544 /// The largest relative excess `max_i (f_i(π) - f_i(A)) / (ε_i f_i(A))`
545 /// of the representative over the apex, or `None` if the pair is not
546 /// ε-bounded.
547 ///
548 /// The paper's slack is one minus this, so the greedy rule's larger
549 /// slack is the smaller excess. Both terms of an [`Excess::Ratio`] are
550 /// exact: a bounded pair has `den_i · f_i(π)` and
551 /// `(den_i + num_i) · f_i(A)` without saturation (see
552 /// [`Epsilon::within`]), and both terms are at most those.
553 fn excess(&self, pair: &Pair<C, N>) -> Option<Excess<C>> {
554 if !self.is_bounded(pair) {
555 return None;
556 }
557
558 let f_rep = add(self.paths[pair.rep].g, pair.h);
559 let f_apex = add(pair.apex, pair.h);
560 let ratios = (0..N).filter(|&i| f_rep[i] != f_apex[i]).map(|i| {
561 let eps = self.eps[i];
562 let over = f_rep[i].abs_diff(f_apex[i]).saturating_times(eps.den());
563 Excess::Ratio {
564 over,
565 of: f_apex[i].saturating_times(eps.num()),
566 }
567 });
568
569 Some(ratios.fold(Excess::Zero, |x, y| if y.is_greater(x) { y } else { x }))
570 }
571
572 /// Adds a pair to the pair arena, the open list and its state's open
573 /// pairs.
574 fn push(&mut self, pair: Pair<C, N>) {
575 let index = self.pairs.len();
576 let state = self.paths[pair.rep].state.clone();
577
578 self.pairs.push(pair);
579 self.open.push(Reverse((add(pair.apex, pair.h), index)));
580 self.info_mut(&state).open.push(index);
581 self.stats.generated += 1;
582 }
583
584 /// Adds a path to the path arena and returns its index.
585 fn new_path(&mut self, state: G::State, g: [C; N], parent: Option<usize>) -> usize {
586 self.paths.push(PathNode { state, g, parent });
587 self.paths.len() - 1
588 }
589
590 /// The bookkeeping of `state`, created on first use.
591 fn info_mut(&mut self, state: &G::State) -> &mut StateInfo<C, N> {
592 self.states
593 .entry(state.clone())
594 .or_insert_with(|| StateInfo {
595 closed: TruncatedFront::new(),
596 open: Vec::new(),
597 expanded: Front::new(),
598 })
599 }
600
601 /// Consumes the search and returns the mutually non-dominated
602 /// representatives, sorted, with the counters.
603 fn into_output(self) -> Output<G::State, [C; N]> {
604 let mut reps: Vec<_> = self
605 .solutions
606 .iter()
607 .map(|s| (self.paths[s.rep].g, s.rep))
608 .collect();
609 reps.sort_unstable();
610
611 // In lexicographic order a later vector cannot dominate an earlier
612 // one, so one pass with a frontier drops every dominated or equal one.
613 let mut front = Front::new();
614 let solutions = reps
615 .into_iter()
616 .filter(|&(cost, _)| front.insert(cost))
617 .map(|(cost, r)| self.solution(r, cost))
618 .collect();
619
620 Output {
621 solutions,
622 stats: self.stats,
623 }
624 }
625
626 /// Rebuilds the path ending in path node `index`.
627 fn solution(&self, index: usize, cost: [C; N]) -> Solution<G::State, [C; N]> {
628 let mut path = Vec::new();
629 let mut current = Some(index);
630
631 while let Some(i) = current {
632 path.push(self.paths[i].state.clone());
633 current = self.paths[i].parent;
634 }
635
636 path.reverse();
637
638 Solution { cost, path }
639 }
640}
641
642/// How far a representative's `f` exceeds its apex's `f`, relative to the
643/// tolerance, in the worst objective.
644#[derive(Clone, Copy)]
645enum Excess<C> {
646 /// The representative's `f` equals the apex's in every objective.
647 Zero,
648 /// The positive ratio `over / of`: `over` is `den_i · (f_i(π) - f_i(A))`
649 /// and `of` is `num_i · f_i(A)`, both non-zero.
650 Ratio {
651 /// The scaled excess of the representative.
652 over: C,
653 /// The scaled tolerance it is measured against.
654 of: C,
655 },
656}
657
658impl<C: WideMul> Excess<C> {
659 /// Returns `true` if `self` is larger than `other`, compared exactly by
660 /// cross-multiplication.
661 fn is_greater(self, other: Self) -> bool {
662 match (self, other) {
663 (Self::Ratio { over, of }, Self::Ratio { over: o, of: f }) => {
664 over.wide_mul(f) > o.wide_mul(of)
665 }
666 (Self::Ratio { .. }, Self::Zero) => true,
667 (Self::Zero, _) => false,
668 }
669 }
670}