Skip to main content

multiobjective_search/
anytime_boa.rs

1//! A-BOA*ε: anytime approximate bi-objective search.
2//!
3//! "Anytime Approximate Bi-Objective Search" (anonymous preprint,
4//! crl.cs.technion.ac.il).
5//!
6//! The search keeps the Pareto-optimal solutions found so far as the
7//! corners of a list of *intervals*. An interval holds two consecutive
8//! solutions, top-left `tl` and bottom-right `br`, and the *to-expand*
9//! paths whose `f` lies between them and that may still lead to a new
10//! Pareto-optimal solution there. Its approximation factor `ε̂` is the
11//! worst, over its to-expand paths, of how well `tl` or `br` covers the
12//! path. Each iteration takes the interval with the largest `ε̂` and runs
13//! BOA*ε on its to-expand paths with `ε = ε̂ / d` (Algorithm 3), which
14//! splits it at every solution found into intervals of factor at most `ε`.
15//! The paths BOA*ε prunes only because of the tolerance are kept as the
16//! new intervals' to-expand paths, so no work is repeated.
17//!
18//! ```mermaid
19//! graph TD
20//!     seed["tl, br: lexicographic optima (c1, c2) and (c2, c1)"] --> list["ILIST = [(tl, br, {start})]"]
21//!     list --> pick{"some interval with ε̂ > 0?"}
22//!     pick -- no --> done[exact Pareto-optimal front]
23//!     pick -- yes --> search["BOA*ε with ε = ε̂ / d on the interval<br/>with the largest ε̂"]
24//!     search --> split["replace it by the intervals between<br/>the solutions found"] --> report["on_front if the overall ε̂ fell"] --> pick
25//! ```
26
27mod factor;
28pub(crate) mod lex;
29
30use alloc::collections::{BTreeMap, BinaryHeap};
31use alloc::vec::Vec;
32use core::cmp::Reverse;
33use core::mem;
34
35use search_core::{Budget, Cost, Heuristic, WideMul};
36
37use crate::cost::add;
38use crate::graph::Graph;
39use crate::output::{Solution, Stats};
40
41pub use factor::ApproxFactor;
42
43/// What an anytime search returns, for `N` objectives (two by default): the solutions found, the
44/// approximation factor they are known to achieve, and whether the search
45/// ran to completion.
46#[derive(Debug, Clone)]
47pub struct AnytimeFront<S, C, const N: usize = 2> {
48    /// Solutions, one per cost vector, sorted by cost lexicographically
49    /// ascending (first objective strictly ascending, second strictly
50    /// descending). Empty when no goal is reachable. Pareto-optimal for
51    /// A-BOA*ε; for [`pp_a_star_iterative`](crate::pp_a_star_iterative)
52    /// only mutually non-dominated until the search is complete.
53    pub solutions: Vec<Solution<S, [C; N]>>,
54    /// An `ε` such that every Pareto-optimal cost is within `1 + ε` of
55    /// some solution in every objective. Zero when
56    /// [`AnytimeFront::complete`] is set.
57    pub factor: ApproxFactor<C>,
58    /// `true` if the search finished on its own rather than being stopped
59    /// by its budget: then [`AnytimeFront::solutions`] is the whole
60    /// Pareto-optimal front.
61    pub complete: bool,
62    /// Counters collected over all iterations, the two seeding searches
63    /// included.
64    pub stats: Stats,
65}
66
67/// The weighted-sum heuristic of the paper's Section 5 for
68/// [`boa_star_anytime_ws`]: a scalar lower bound `heuristic(s)` on
69/// `c1 + weight · c2` of every path from `s` to a goal.
70///
71/// The exact one is a single-objective Dijkstra from the goal with edge
72/// cost `c1 + weight · c2`; any admissible bound is sound. A state for
73/// which `heuristic` returns `None` is treated as a dead end.
74#[derive(Debug, Clone, Copy)]
75pub struct WeightedSum<W> {
76    /// The weight `w > 0` of the second objective.
77    pub weight: u32,
78    /// The lower bound on `c1 + weight · c2`.
79    pub heuristic: W,
80}
81
82/// A-BOA*ε: finds the Pareto-optimal front from `start` to a state that
83/// satisfies `is_goal`, reporting ever better approximations of it.
84///
85/// After seeding with the two lexicographically optimal solutions and
86/// after every iteration that lowers the overall approximation factor,
87/// `on_front` gets the solutions found so far and an `ε` they achieve:
88/// every Pareto-optimal cost `s` has a reported `r` with
89/// `r_i <= (1 + ε) · s_i` (the paper's Theorem 1). The factors strictly
90/// decrease and the last call of a complete run has `ε = 0`, the exact
91/// front (Theorem 2). The search stops early when `budget` is exhausted;
92/// the result then carries the last known factor.
93///
94/// `d` is the paper's divisor: each iteration targets `ε̂ / d` for the
95/// interval it refines (the paper uses 4).
96///
97/// Requirements, not checked at run time:
98///
99/// - edge costs are non-negative;
100/// - `heuristic` is consistent in both objectives and zero on every goal.
101///
102/// # Panics
103///
104/// Panics if `d < 2`.
105///
106/// # Examples
107///
108/// ```
109/// use multiobjective_search::{Graph, ZeroHeuristic, boa_star_anytime};
110///
111/// /// Four routes from 0 to 1.
112/// struct Routes;
113///
114/// impl Graph for Routes {
115///     type State = u8;
116///     type Weight = [u32; 2];
117///
118///     fn successors(&self, state: &u8, out: &mut Vec<(u8, [u32; 2])>) {
119///         if *state == 0 {
120///             out.extend([(1, [10, 100]), (1, [40, 45]), (1, [42, 41]), (1, [100, 10])]);
121///         }
122///     }
123/// }
124///
125/// let mut sizes = Vec::new();
126/// let result = boa_star_anytime(
127///     &Routes,
128///     ZeroHeuristic,
129///     0,
130///     |s| *s == 1,
131///     4,
132///     |front, _factor| sizes.push(front.len()),
133///     |_: &_| false,
134/// );
135///
136/// assert!(result.complete && result.factor.is_zero());
137/// assert_eq!(result.solutions.len(), 4);
138/// // The two lexicographic optima first, then the improved fronts.
139/// assert_eq!(sizes.first(), Some(&2));
140/// assert_eq!(sizes.last(), Some(&4));
141/// ```
142pub fn boa_star_anytime<G, H, C, P>(
143    graph: &G,
144    heuristic: H,
145    start: G::State,
146    is_goal: P,
147    d: u32,
148    on_front: impl FnMut(&[Solution<G::State, [C; 2]>], ApproxFactor<C>),
149    budget: impl Budget<Stats>,
150) -> AnytimeFront<G::State, C>
151where
152    G: Graph<Weight = [C; 2]>,
153    H: Heuristic<G::State, [C; 2]>,
154    C: Cost + WideMul,
155    P: Fn(&G::State) -> bool,
156{
157    let variant = Variant::<NoSum> {
158        reuse: true,
159        weighted: None,
160    };
161
162    run(
163        graph, heuristic, start, is_goal, d, variant, on_front, budget,
164    )
165}
166
167/// A-BOA*ε-w: [`boa_star_anytime`] with the paper's weighted-sum pruning.
168///
169/// Inside an interval, with `π'` the last solution found and `π''` the
170/// interval's bottom-right solution, a path `π` is pruned when
171/// `g1(π) + w · g2(π) + h_w(s(π)) >= f1(π'') + w · f2(π')`: every solution
172/// through it lies on or above that line, where neither `π'` nor `π''`
173/// leaves room for a new non-dominated one (Property 1). Same guarantees
174/// and requirements as [`boa_star_anytime`], plus an admissible
175/// `weighted.heuristic`.
176///
177/// # Panics
178///
179/// Panics if `d < 2`.
180///
181/// # Examples
182///
183/// ```
184/// use multiobjective_search::{
185///     Graph, WeightedSum, ZeroHeuristic, boa_star_anytime_ws, heuristic_fn,
186/// };
187///
188/// /// Three routes from 0 to the goal 2 through 1.
189/// struct Routes;
190///
191/// impl Graph for Routes {
192///     type State = u8;
193///     type Weight = [u32; 2];
194///
195///     fn successors(&self, state: &u8, out: &mut Vec<(u8, [u32; 2])>) {
196///         match state {
197///             0 => out.push((1, [1, 1])),
198///             1 => out.extend([(2, [1, 9]), (2, [5, 5]), (2, [9, 1])]),
199///             _ => {}
200///         }
201///     }
202/// }
203///
204/// // Exact c1 + c2 to the goal: 11 from 0, 10 from 1.
205/// let sum = heuristic_fn(|s: &u8| Some([11_u32, 10, 0][usize::from(*s)]));
206/// let weighted = WeightedSum { weight: 1, heuristic: sum };
207/// let result = boa_star_anytime_ws(
208///     &Routes,
209///     ZeroHeuristic,
210///     0,
211///     |s| *s == 2,
212///     4,
213///     weighted,
214///     |_, _| {},
215///     |_: &_| false,
216/// );
217///
218/// let costs: Vec<_> = result.solutions.iter().map(|s| s.cost).collect();
219/// assert_eq!(costs, [[2, 10], [6, 6], [10, 2]]);
220/// ```
221#[expect(
222    clippy::too_many_arguments,
223    reason = "the paper's inputs plus the anytime callback and budget, as in boa_star_anytime"
224)]
225pub fn boa_star_anytime_ws<G, H, W, C, P>(
226    graph: &G,
227    heuristic: H,
228    start: G::State,
229    is_goal: P,
230    d: u32,
231    weighted: WeightedSum<W>,
232    on_front: impl FnMut(&[Solution<G::State, [C; 2]>], ApproxFactor<C>),
233    budget: impl Budget<Stats>,
234) -> AnytimeFront<G::State, C>
235where
236    G: Graph<Weight = [C; 2]>,
237    H: Heuristic<G::State, [C; 2]>,
238    W: Heuristic<G::State, C>,
239    C: Cost + WideMul,
240    P: Fn(&G::State) -> bool,
241{
242    let variant = Variant {
243        reuse: true,
244        weighted: Some(weighted),
245    };
246
247    run(
248        graph, heuristic, start, is_goal, d, variant, on_front, budget,
249    )
250}
251
252/// Basic-A-BOA*ε, the paper's baseline: [`boa_star_anytime`] without reuse.
253///
254/// Every iteration runs BOA*ε from scratch over the whole front with `ε`
255/// the current overall factor divided by `d`, and keeps its result. Same
256/// reports and guarantees as [`boa_star_anytime`]; slower, since every
257/// iteration repeats the work of the last. Mainly for comparison.
258///
259/// # Panics
260///
261/// Panics if `d < 2`.
262///
263/// # Examples
264///
265/// ```
266/// use multiobjective_search::{Graph, ZeroHeuristic, boa_star_anytime_basic};
267///
268/// /// Two routes from 0 to 1.
269/// struct Routes;
270///
271/// impl Graph for Routes {
272///     type State = u8;
273///     type Weight = [u32; 2];
274///
275///     fn successors(&self, state: &u8, out: &mut Vec<(u8, [u32; 2])>) {
276///         if *state == 0 {
277///             out.extend([(1, [1, 2]), (1, [2, 1])]);
278///         }
279///     }
280/// }
281///
282/// let result =
283///     boa_star_anytime_basic(&Routes, ZeroHeuristic, 0, |s| *s == 1, 4, |_, _| {}, |_: &_| false);
284/// assert_eq!(result.solutions.len(), 2);
285/// ```
286pub fn boa_star_anytime_basic<G, H, C, P>(
287    graph: &G,
288    heuristic: H,
289    start: G::State,
290    is_goal: P,
291    d: u32,
292    on_front: impl FnMut(&[Solution<G::State, [C; 2]>], ApproxFactor<C>),
293    budget: impl Budget<Stats>,
294) -> AnytimeFront<G::State, C>
295where
296    G: Graph<Weight = [C; 2]>,
297    H: Heuristic<G::State, [C; 2]>,
298    C: Cost + WideMul,
299    P: Fn(&G::State) -> bool,
300{
301    let variant = Variant::<NoSum> {
302        reuse: false,
303        weighted: None,
304    };
305
306    run(
307        graph, heuristic, start, is_goal, d, variant, on_front, budget,
308    )
309}
310
311/// Which A-BOA*ε variant runs.
312struct Variant<W> {
313    /// `true`: refine one interval per iteration and keep the others
314    /// (A-BOA*ε); `false`: rerun over the whole front (Basic-A-BOA*ε).
315    reuse: bool,
316    /// The weighted-sum pruning of A-BOA*ε-w, if enabled.
317    weighted: Option<WeightedSum<W>>,
318}
319
320/// The weighted-sum heuristic type when the pruning is off; never queried.
321struct NoSum;
322
323impl<S, C: Cost> Heuristic<S, C> for NoSum {
324    fn estimate(&mut self, _state: &S) -> Option<C> {
325        Some(C::ZERO)
326    }
327}
328
329/// Seeds the search and runs the iterations (Algorithm 2).
330#[expect(
331    clippy::too_many_arguments,
332    reason = "the public entry points' arguments plus the variant"
333)]
334fn run<G, H, W, C, P>(
335    graph: &G,
336    mut heuristic: H,
337    start: G::State,
338    is_goal: P,
339    d: u32,
340    variant: Variant<W>,
341    mut on_front: impl FnMut(&[Solution<G::State, [C; 2]>], ApproxFactor<C>),
342    mut budget: impl Budget<Stats>,
343) -> AnytimeFront<G::State, C>
344where
345    G: Graph<Weight = [C; 2]>,
346    H: Heuristic<G::State, [C; 2]>,
347    W: Heuristic<G::State, C>,
348    C: Cost + WideMul,
349    P: Fn(&G::State) -> bool,
350{
351    assert!(d >= 2, "the divisor d must be at least 2");
352
353    let mut stats = Stats::default();
354    let Some(tl) = lex::lex_first(graph, &mut heuristic, &start, &is_goal, 0, &mut stats) else {
355        return AnytimeFront {
356            solutions: Vec::new(),
357            factor: ApproxFactor::Zero,
358            complete: true,
359            stats,
360        };
361    };
362    let br = lex::lex_first(graph, &mut heuristic, &start, &is_goal, 1, &mut stats)
363        .expect("a goal reachable in one order is reachable in the other");
364
365    if tl.cost == br.cost {
366        let solutions = alloc::vec![tl];
367        on_front(&solutions, ApproxFactor::Zero);
368        return AnytimeFront {
369            solutions,
370            factor: ApproxFactor::Zero,
371            complete: true,
372            stats,
373        };
374    }
375
376    let mut search = Anytime {
377        graph,
378        heuristic,
379        is_goal,
380        weighted: variant.weighted,
381        start,
382        nodes: Vec::new(),
383        solutions: alloc::vec![tl, br],
384        intervals: Vec::new(),
385        successors: Vec::new(),
386        stats,
387    };
388    search.intervals = alloc::vec![search.seed_interval()];
389
390    let complete = search.iterate(d, variant.reuse, &mut on_front, &mut budget);
391    search.into_front(complete)
392}
393
394/// One path of the search, stored in the node arena.
395struct Node<S, C> {
396    /// The state the path ends in.
397    state: S,
398    /// Cost of the path.
399    g: [C; 2],
400    /// `g + h`.
401    f: [C; 2],
402    /// The weighted-sum heuristic at `state`; `None` if not in use or a
403    /// dead end.
404    sum: Option<C>,
405    /// Arena index of the path without its last edge; `None` for the start.
406    parent: Option<usize>,
407}
408
409/// An interval `⟨π_tl, π_br, Π⟩` (Definition 1) with its factor
410/// (Definition 2).
411struct Interval<C> {
412    /// Index of the top-left solution in [`Anytime::solutions`].
413    tl: usize,
414    /// Index of the bottom-right solution in [`Anytime::solutions`].
415    br: usize,
416    /// Arena indices of the to-expand paths.
417    paths: Vec<usize>,
418    /// `ε̂`: zero when `paths` is empty.
419    factor: ApproxFactor<C>,
420}
421
422/// Mutable state of one A-BOA*ε run.
423struct Anytime<'a, G: Graph, H, W, C, P> {
424    /// The graph being searched.
425    graph: &'a G,
426    /// Per-objective lower bounds on the remaining cost.
427    heuristic: H,
428    /// Goal test.
429    is_goal: P,
430    /// The weighted-sum pruning, if enabled.
431    weighted: Option<WeightedSum<W>>,
432    /// The start state, for Basic-A-BOA*ε's restarts.
433    start: G::State,
434    /// Every path generated; intervals and parents index into it.
435    nodes: Vec<Node<G::State, C>>,
436    /// Every solution found, the two seeds first. Intervals index into it.
437    solutions: Vec<Solution<G::State, [C; 2]>>,
438    /// `ILIST`, sorted by the first cost of the top-left solution; each
439    /// interval's `br` is the next one's `tl` (Property 2).
440    intervals: Vec<Interval<C>>,
441    /// Reused successor buffer, empty between expansions.
442    successors: Vec<(G::State, [C; 2])>,
443    /// Effort counters.
444    stats: Stats,
445}
446
447/// The per-call bookkeeping of Algorithm 3.
448struct Refine<S, C> {
449    /// `ε` of this call.
450    eps: ApproxFactor<C>,
451    /// Cost of the input interval's top-left solution.
452    tl: [C; 2],
453    /// Cost of the input interval's bottom-right solution.
454    br: [C; 2],
455    /// Cost of the last solution found, `π_tmp`; starts at `tl`.
456    last: [C; 2],
457    /// `g2_min` per state, reset for every call.
458    g2_min: BTreeMap<S, C>,
459    /// Paths pruned only by the tolerance since the last solution: `Π_tmp`.
460    kept: Vec<usize>,
461}
462
463impl<G, H, W, C, P> Anytime<'_, G, H, W, C, P>
464where
465    G: Graph<Weight = [C; 2]>,
466    H: Heuristic<G::State, [C; 2]>,
467    W: Heuristic<G::State, C>,
468    C: Cost + WideMul,
469    P: Fn(&G::State) -> bool,
470{
471    /// The interval `⟨π_tl, π_br, {[s_start]}⟩` over the whole front, with
472    /// a fresh start path.
473    fn seed_interval(&mut self) -> Interval<C> {
474        let start = self.start.clone();
475        let paths: Vec<usize> = self
476            .new_node(start, [C::ZERO; 2], None)
477            .into_iter()
478            .collect();
479        self.stats.generated += paths.len();
480
481        self.interval(0, 1, paths)
482    }
483
484    /// Runs iterations until every interval has factor zero (returns
485    /// `true`) or the budget is exhausted (returns `false`).
486    fn iterate(
487        &mut self,
488        d: u32,
489        reuse: bool,
490        on_front: &mut impl FnMut(&[Solution<G::State, [C; 2]>], ApproxFactor<C>),
491        budget: &mut impl Budget<Stats>,
492    ) -> bool {
493        let mut reported = self.factor();
494        on_front(&self.front(), reported);
495
496        loop {
497            let (index, factor) = self.widest();
498            if factor.is_zero() {
499                return true;
500            }
501
502            let eps = self.target(factor, d);
503            let finished = if reuse {
504                let interval = self.intervals.remove(index);
505                let (parts, finished) = self.refine(&interval, eps, budget);
506                self.intervals.splice(index..index, parts);
507                finished
508            } else {
509                let seed = self.seed_interval();
510                let (parts, finished) = self.refine(&seed, eps, budget);
511                self.intervals = parts;
512                finished
513            };
514
515            let now = self.factor();
516            if now < reported {
517                reported = now;
518                on_front(&self.front(), reported);
519            }
520
521            if !finished {
522                return false;
523            }
524        }
525    }
526
527    /// The `ε` to refine an interval of factor `factor` with: `factor / d`,
528    /// or `1` for an infinite factor (see `docs/design.md`).
529    fn target(&self, factor: ApproxFactor<C>, d: u32) -> ApproxFactor<C> {
530        match factor {
531            ApproxFactor::Infinite => {
532                // Any positive cost over itself: ε = 1. The seeds' first costs
533                // differ, so the bottom-right one is positive.
534                let one = self.solutions[1].cost[0];
535                ApproxFactor::Ratio { num: one, den: one }
536            }
537            finite => finite.divided(d),
538        }
539    }
540
541    /// Algorithm 3: BOA*ε with `eps` on the to-expand paths of `interval`,
542    /// returning the intervals between the solutions it finds, and `false`
543    /// if the budget stopped it (then the unexplored paths stay in the last
544    /// interval).
545    fn refine(
546        &mut self,
547        interval: &Interval<C>,
548        eps: ApproxFactor<C>,
549        budget: &mut impl Budget<Stats>,
550    ) -> (Vec<Interval<C>>, bool) {
551        let tl = self.solutions[interval.tl].cost;
552        let mut refine = Refine {
553            eps,
554            tl,
555            br: self.solutions[interval.br].cost,
556            last: tl,
557            g2_min: BTreeMap::new(),
558            kept: Vec::new(),
559        };
560        let mut open: BinaryHeap<_> = interval
561            .paths
562            .iter()
563            .map(|&i| Reverse((self.nodes[i].f, i)))
564            .collect();
565        let mut parts = Vec::new();
566        let mut top_left = interval.tl;
567        let mut best: Option<C> = None;
568
569        while let Some(Reverse((_, index))) = open.pop() {
570            if budget.exhausted(&self.stats) {
571                refine.kept.push(index);
572                refine.kept.extend(open.drain().map(|Reverse((_, i))| i));
573                parts.push(self.interval(top_left, interval.br, refine.kept));
574                return (parts, false);
575            }
576
577            if self.is_dominated(index, best, &mut refine) {
578                continue;
579            }
580
581            let node = &self.nodes[index];
582            refine.g2_min.insert(node.state.clone(), node.g[1]);
583            if (self.is_goal)(&self.nodes[index].state) {
584                let solution = self.record(index);
585                parts.push(self.interval(top_left, solution, mem::take(&mut refine.kept)));
586                top_left = solution;
587                refine.last = self.nodes[index].g;
588                best = Some(self.nodes[index].g[1]);
589                continue;
590            }
591
592            self.expand(index, best, &mut refine, &mut open);
593        }
594
595        parts.push(self.interval(top_left, interval.br, refine.kept));
596        (parts, true)
597    }
598
599    /// Generates the children of the path at `index` and pushes those that
600    /// are not dominated (Algorithm 3, lines 13 to 17).
601    fn expand(
602        &mut self,
603        index: usize,
604        best: Option<C>,
605        refine: &mut Refine<G::State, C>,
606        open: &mut BinaryHeap<Reverse<([C; 2], usize)>>,
607    ) {
608        self.stats.expanded += 1;
609
610        let mut successors = mem::take(&mut self.successors);
611        let g = self.nodes[index].g;
612        self.graph
613            .successors(&self.nodes[index].state, &mut successors);
614
615        for (state, weight) in successors.drain(..) {
616            let Some(child) = self.new_node(state, add(g, weight), Some(index)) else {
617                continue;
618            };
619
620            if !self.is_dominated(child, best, refine) {
621                open.push(Reverse((self.nodes[child].f, child)));
622                self.stats.generated += 1;
623            }
624        }
625
626        self.successors = successors;
627    }
628
629    /// `is_dominated` of Algorithm 3 (lines 20 to 27). Paths pruned only by
630    /// the tolerance, not by BOA*'s own tests, are kept in
631    /// [`Refine::kept`].
632    fn is_dominated(
633        &self,
634        index: usize,
635        best: Option<C>,
636        refine: &mut Refine<G::State, C>,
637    ) -> bool {
638        let node = &self.nodes[index];
639        let (g, f) = (node.g, node.f);
640
641        if f[0] >= refine.br[0] || f[1] >= refine.tl[1] || self.below_line(node, refine) {
642            return true;
643        }
644
645        let exact = refine.g2_min.get(&node.state).is_some_and(|&m| g[1] >= m)
646            || best.is_some_and(|b| f[1] >= b);
647        let tolerated = best.is_some_and(|b| refine.eps.covers(b, f[1]));
648        if exact || tolerated {
649            if !exact {
650                refine.kept.push(index);
651            }
652
653            return true;
654        }
655
656        false
657    }
658
659    /// The weighted-sum test of Section 5: `g1 + w · g2 + h_w >= f1(π_br) +
660    /// w · f2(π_tmp)`. Off when the pruning is disabled or the right-hand
661    /// side saturates.
662    fn below_line(&self, node: &Node<G::State, C>, refine: &Refine<G::State, C>) -> bool {
663        let Some(weighted) = &self.weighted else {
664            return false;
665        };
666
667        let Some(sum) = node.sum else {
668            return true;
669        };
670
671        let w = weighted.weight;
672        let line = refine.br[0].saturating_add(refine.last[1].saturating_times(w));
673        if line.saturating_add(line) == line && line != C::ZERO {
674            return false;
675        }
676
677        let reach = node.g[0]
678            .saturating_add(node.g[1].saturating_times(w))
679            .saturating_add(sum);
680
681        reach >= line
682    }
683
684    /// Adds a path to the arena unless its state is a dead end, and
685    /// returns its index.
686    fn new_node(&mut self, state: G::State, g: [C; 2], parent: Option<usize>) -> Option<usize> {
687        let h = self.heuristic.estimate(&state)?;
688        let sum = match &mut self.weighted {
689            Some(weighted) => weighted.heuristic.estimate(&state),
690            None => None,
691        };
692
693        self.nodes.push(Node {
694            state,
695            g,
696            f: add(g, h),
697            sum,
698            parent,
699        });
700
701        Some(self.nodes.len() - 1)
702    }
703
704    /// Records the goal path at `index` as a solution and returns its index.
705    fn record(&mut self, index: usize) -> usize {
706        let mut path = Vec::new();
707        let mut current = Some(index);
708
709        while let Some(i) = current {
710            path.push(self.nodes[i].state.clone());
711            current = self.nodes[i].parent;
712        }
713
714        path.reverse();
715        self.solutions.push(Solution {
716            cost: self.nodes[index].g,
717            path,
718        });
719
720        self.solutions.len() - 1
721    }
722
723    /// The interval between solutions `tl` and `br` with to-expand paths
724    /// `paths`, and its factor `max_π min(DF(tl, π), DF(br, π))`.
725    fn interval(&self, tl: usize, br: usize, paths: Vec<usize>) -> Interval<C> {
726        let (tl_cost, br_cost) = (self.solutions[tl].cost, self.solutions[br].cost);
727        let factor = paths
728            .iter()
729            .map(|&i| {
730                let f = self.nodes[i].f;
731                ApproxFactor::domination(tl_cost, f).min(ApproxFactor::domination(br_cost, f))
732            })
733            .max()
734            .unwrap_or(ApproxFactor::Zero);
735
736        Interval {
737            tl,
738            br,
739            paths,
740            factor,
741        }
742    }
743
744    /// The index and factor of the interval with the largest factor; the
745    /// first on a tie.
746    fn widest(&self) -> (usize, ApproxFactor<C>) {
747        self.intervals
748            .iter()
749            .enumerate()
750            .fold((0, ApproxFactor::Zero), |acc, (i, interval)| {
751                if interval.factor > acc.1 {
752                    (i, interval.factor)
753                } else {
754                    acc
755                }
756            })
757    }
758
759    /// The overall factor: the largest over all intervals (Theorem 1).
760    fn factor(&self) -> ApproxFactor<C> {
761        self.widest().1
762    }
763
764    /// The solutions at the intervals' corners, sorted by cost.
765    fn front(&self) -> Vec<Solution<G::State, [C; 2]>> {
766        let first = self.intervals.first().map(|interval| interval.tl);
767        first
768            .into_iter()
769            .chain(self.intervals.iter().map(|interval| interval.br))
770            .map(|i| self.solutions[i].clone())
771            .collect()
772    }
773
774    /// Consumes the search and returns the result.
775    fn into_front(self, complete: bool) -> AnytimeFront<G::State, C> {
776        AnytimeFront {
777            solutions: self.front(),
778            factor: self.factor(),
779            complete,
780            stats: self.stats,
781        }
782    }
783}