1use alloc::collections::{BTreeMap, BinaryHeap};
7use alloc::vec::Vec;
8use core::cmp::Reverse;
9
10use search_core::{Budget, Cost, Heuristic, WideMul};
11
12use super::Excess;
13use crate::anytime_boa::{AnytimeFront, ApproxFactor};
14use crate::cost::{add, weakly_dominates};
15use crate::epsilon::Epsilon;
16use crate::graph::Graph;
17use crate::output::{Solution, Stats};
18use crate::pareto::Front;
19use crate::pp_a::iterative::as_factor;
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
23pub enum AnytimeApex {
24 #[default]
27 Reuse,
28 ReuseEnhanced,
32 Restart,
35 Hybrid {
39 threshold: u32,
41 },
42}
43
44pub fn apex_star_anytime<G, H, C, P, const N: usize>(
73 graph: &G,
74 heuristic: H,
75 start: G::State,
76 is_goal: P,
77 schedule: impl IntoIterator<Item = [Epsilon; N]>,
78 on_front: impl FnMut(&[Solution<G::State, [C; N]>], ApproxFactor<C>),
79 budget: impl Budget<Stats>,
80) -> AnytimeFront<G::State, C, N>
81where
82 G: Graph<Weight = [C; N]>,
83 H: Heuristic<G::State, [C; N]>,
84 C: Cost + WideMul,
85 P: Fn(&G::State) -> bool,
86{
87 apex_star_anytime_with(
88 graph,
89 heuristic,
90 start,
91 is_goal,
92 schedule,
93 AnytimeApex::Reuse,
94 on_front,
95 budget,
96 )
97}
98
99#[expect(
129 clippy::too_many_arguments,
130 reason = "the anytime search inputs plus the variant"
131)]
132pub fn apex_star_anytime_with<G, H, C, P, const N: usize>(
133 graph: &G,
134 heuristic: H,
135 start: G::State,
136 is_goal: P,
137 schedule: impl IntoIterator<Item = [Epsilon; N]>,
138 variant: AnytimeApex,
139 mut on_front: impl FnMut(&[Solution<G::State, [C; N]>], ApproxFactor<C>),
140 mut budget: impl Budget<Stats>,
141) -> AnytimeFront<G::State, C, N>
142where
143 G: Graph<Weight = [C; N]>,
144 H: Heuristic<G::State, [C; N]>,
145 C: Cost + WideMul,
146 P: Fn(&G::State) -> bool,
147{
148 let mut search = Anytime::new(graph, heuristic, is_goal, variant, start);
149 let mut reported: Option<ApproxFactor<C>> = None;
150 let mut complete = false;
151 let mut reuse = matches!(variant, AnytimeApex::Reuse | AnytimeApex::ReuseEnhanced);
152
153 for eps in schedule {
154 if reported.is_some() && budget.exhausted(&search.stats) {
155 break;
156 }
157
158 let (expanded, pruned) = search.iterate(eps, reuse);
159 if let AnytimeApex::Hybrid { threshold } = variant {
160 reuse = reuse || expanded > pruned.saturating_mul(threshold as usize);
161 }
162
163 complete = search.pruned.is_empty();
164 let front = search.front();
165 let factor = if complete {
166 ApproxFactor::Zero
167 } else {
168 as_factor(widest(eps), &front)
169 };
170 if reported.is_none_or(|r| factor < r) {
171 reported = Some(factor);
172 on_front(&front, factor);
173 }
174
175 if complete {
176 break;
177 }
178 }
179
180 AnytimeFront {
181 solutions: search.front(),
182 factor: reported.unwrap_or(ApproxFactor::Infinite),
183 complete,
184 stats: search.stats,
185 }
186}
187
188fn widest<const N: usize>(eps: [Epsilon; N]) -> Epsilon {
190 eps.into_iter()
191 .reduce(|a, b| {
192 let larger =
193 u64::from(b.num()) * u64::from(a.den()) > u64::from(a.num()) * u64::from(b.den());
194 if larger { b } else { a }
195 })
196 .unwrap_or(Epsilon::ZERO)
197}
198
199#[derive(Clone, Copy)]
201struct Pair<C, const N: usize> {
202 apex: [C; N],
204 rep: usize,
206 h: [C; N],
208 alive: bool,
210}
211
212struct Anytime<'a, G: Graph, H, C, P, const N: usize> {
214 graph: &'a G,
216 heuristic: H,
218 is_goal: P,
220 variant: AnytimeApex,
222 start: G::State,
224 paths: Vec<(G::State, [C; N], Option<usize>)>,
226 pairs: Vec<Pair<C, N>>,
228 open: BinaryHeap<Reverse<([C; N], usize)>>,
230 open_at: BTreeMap<G::State, Vec<usize>>,
232 closed: BTreeMap<G::State, Vec<([C; N], usize)>>,
235 expanded: BTreeMap<G::State, Front<C, N>>,
238 solutions: Vec<usize>,
240 pruned: Vec<usize>,
242 eps: [Epsilon; N],
244 stats: Stats,
246}
247
248impl<'a, G, H, C, P, const N: usize> Anytime<'a, G, H, C, P, N>
249where
250 G: Graph<Weight = [C; N]>,
251 H: Heuristic<G::State, [C; N]>,
252 C: Cost + WideMul,
253 P: Fn(&G::State) -> bool,
254{
255 fn new(graph: &'a G, heuristic: H, is_goal: P, variant: AnytimeApex, start: G::State) -> Self {
257 let mut search = Self {
258 graph,
259 heuristic,
260 is_goal,
261 variant,
262 start: start.clone(),
263 paths: Vec::new(),
264 pairs: Vec::new(),
265 open: BinaryHeap::new(),
266 open_at: BTreeMap::new(),
267 closed: BTreeMap::new(),
268 expanded: BTreeMap::new(),
269 solutions: Vec::new(),
270 pruned: Vec::new(),
271 eps: [Epsilon::ZERO; N],
272 stats: Stats::default(),
273 };
274 search.paths.push((start, [C::ZERO; N], None));
275 search.pruned.push(0);
276 search
277 }
278
279 fn iterate(&mut self, eps: [Epsilon; N], reuse: bool) -> (usize, usize) {
282 self.eps = eps;
283 self.pairs.clear();
284 self.open.clear();
285 self.open_at.clear();
286 self.closed.clear();
287 let before = self.stats.expanded;
288
289 let seeds = core::mem::take(&mut self.pruned);
290 let seeds = if reuse {
291 seeds
292 } else {
293 self.paths.push((self.start.clone(), [C::ZERO; N], None));
294 alloc::vec![self.paths.len() - 1]
295 };
296
297 for path in seeds {
298 let (state, cost) = (self.paths[path].0.clone(), self.paths[path].1);
299 if let Some(h) = self.heuristic.estimate(&state) {
300 self.add_to_open(Pair {
301 apex: cost,
302 rep: path,
303 h,
304 alive: true,
305 });
306 }
307 }
308
309 self.find_approx_front();
310 (self.stats.expanded - before, self.pruned.len())
311 }
312
313 fn find_approx_front(&mut self) {
315 while let Some(Reverse((_, index))) = self.open.pop() {
316 let pair = self.pairs[index];
317 if !pair.alive {
318 continue;
319 }
320
321 let state = self.paths[pair.rep].0.clone();
322 if let Some(list) = self.open_at.get_mut(&state) {
323 list.retain(|&i| i != index);
324 }
325
326 if self.is_dominated(&pair) {
327 continue;
328 }
329
330 self.closed
331 .entry(state.clone())
332 .or_default()
333 .push((pair.apex, pair.rep));
334 if self.variant == AnytimeApex::ReuseEnhanced {
335 let cost = self.paths[pair.rep].1;
336 self.expanded.entry(state.clone()).or_default().insert(cost);
337 }
338
339 if (self.is_goal)(&state) {
340 let cost = self.paths[pair.rep].1;
341 let paths = &self.paths;
342 self.solutions
343 .retain(|&s| !weakly_dominates(&cost, &paths[s].1));
344 self.solutions.push(pair.rep);
345 continue;
346 }
347
348 self.expand(pair);
349 }
350 }
351
352 fn expand(&mut self, pair: Pair<C, N>) {
354 self.stats.expanded += 1;
355
356 let state = self.paths[pair.rep].0.clone();
357 let mut edges = Vec::new();
358 self.graph.successors(&state, &mut edges);
359 for (next, weight) in edges {
360 let Some(h) = self.heuristic.estimate(&next) else {
361 continue;
362 };
363
364 let cost = add(self.paths[pair.rep].1, weight);
365 self.paths.push((next, cost, Some(pair.rep)));
366 let child = Pair {
367 apex: add(pair.apex, weight),
368 rep: self.paths.len() - 1,
369 h,
370 alive: true,
371 };
372 if !self.is_dominated(&child) {
373 self.add_to_open(child);
374 self.stats.generated += 1;
375 }
376 }
377 }
378
379 fn is_dominated(&mut self, pair: &Pair<C, N>) -> bool {
382 let (state, rep_cost) = (self.paths[pair.rep].0.clone(), self.paths[pair.rep].1);
383 let f = add(pair.apex, pair.h);
384 let rep_f = add(rep_cost, pair.h);
385
386 let covering = self
387 .solutions
388 .iter()
389 .map(|&s| self.paths[s].1)
390 .find(|c| (0..N).all(|i| self.eps[i].within(c[i], f[i])));
391 if let Some(c) = covering {
392 if !weakly_dominates(&c, &rep_f) {
393 self.pruned.push(pair.rep);
394 }
395
396 return true;
397 }
398
399 let dominator = self.closed.get(&state).and_then(|list| {
400 list.iter()
401 .find(|(x, _)| (1..N).all(|i| x[i] <= pair.apex[i]))
402 .map(|&(_, r)| r)
403 });
404 if let Some(r) = dominator {
405 if !weakly_dominates(&self.paths[r].1, &rep_cost) {
406 self.pruned.push(pair.rep);
407 }
408
409 return true;
410 }
411
412 self.variant == AnytimeApex::ReuseEnhanced
413 && self
414 .expanded
415 .get(&state)
416 .is_some_and(|c| c.weakly_dominates(&pair.apex))
417 }
418
419 fn add_to_open(&mut self, pair: Pair<C, N>) {
423 let state = self.paths[pair.rep].0.clone();
424 let candidates = self.open_at.get(&state).cloned().unwrap_or_default();
425 for other in candidates {
426 let Some(merged) = self.merge(pair, self.pairs[other]) else {
427 continue;
428 };
429
430 self.pairs[other].alive = false;
431 if let Some(list) = self.open_at.get_mut(&state) {
432 list.retain(|&i| i != other);
433 }
434
435 let dropped = if merged.rep == pair.rep {
436 self.pairs[other].rep
437 } else {
438 pair.rep
439 };
440 if !weakly_dominates(&self.paths[merged.rep].1, &self.paths[dropped].1) {
441 self.pruned.push(dropped);
442 }
443
444 self.push(merged);
445 return;
446 }
447
448 self.push(pair);
449 }
450
451 fn push(&mut self, pair: Pair<C, N>) {
453 let state = self.paths[pair.rep].0.clone();
454 self.pairs.push(pair);
455 let index = self.pairs.len() - 1;
456 self.open.push(Reverse((add(pair.apex, pair.h), index)));
457 self.open_at.entry(state).or_default().push(index);
458 }
459
460 fn merge(&self, a: Pair<C, N>, b: Pair<C, N>) -> Option<Pair<C, N>> {
463 let apex = core::array::from_fn(|i| a.apex[i].min(b.apex[i]));
464 let for_a = Pair {
465 apex,
466 rep: a.rep,
467 h: a.h,
468 alive: true,
469 };
470 let for_b = Pair {
471 apex,
472 rep: b.rep,
473 h: a.h,
474 alive: true,
475 };
476
477 match (self.excess(&for_a), self.excess(&for_b)) {
478 (Some(x), Some(y)) if x.is_greater(y) => Some(for_b),
479 (Some(_), _) => Some(for_a),
480 (None, Some(_)) => Some(for_b),
481 (None, None) => None,
482 }
483 }
484
485 fn excess(&self, pair: &Pair<C, N>) -> Option<Excess<C>> {
488 let f_rep = add(self.paths[pair.rep].1, pair.h);
489 let f_apex = add(pair.apex, pair.h);
490 if !(0..N).all(|i| self.eps[i].within(f_rep[i], f_apex[i])) {
491 return None;
492 }
493
494 let ratios = (0..N)
495 .filter(|&i| f_rep[i] != f_apex[i])
496 .map(|i| Excess::Ratio {
497 over: f_rep[i]
498 .abs_diff(f_apex[i])
499 .saturating_times(self.eps[i].den()),
500 of: f_apex[i].saturating_times(self.eps[i].num()),
501 });
502
503 Some(ratios.fold(Excess::Zero, |x, y| if y.is_greater(x) { y } else { x }))
504 }
505
506 fn front(&self) -> Vec<Solution<G::State, [C; N]>> {
508 let mut out: Vec<_> = self.solutions.iter().map(|&s| self.solution(s)).collect();
509 out.sort_by_key(|s| s.cost);
510 out
511 }
512
513 fn solution(&self, index: usize) -> Solution<G::State, [C; N]> {
515 let mut path = Vec::new();
516 let mut at = Some(index);
517 while let Some(i) = at {
518 path.push(self.paths[i].0.clone());
519 at = self.paths[i].2;
520 }
521
522 path.reverse();
523 Solution {
524 cost: self.paths[index].1,
525 path,
526 }
527 }
528}