1use 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#[derive(Debug, Clone)]
31pub struct Scalarization<C, const N: usize> {
32 ideal: [C; N],
34 weights: [BigUint; N],
36 k: BigUint,
38 limit: BigUint,
40}
41
42impl<C: ExactArith<Exact = BigUint>, const N: usize> Scalarization<C, N> {
43 #[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 #[must_use]
62 pub const fn limit(&self) -> &BigUint {
63 &self.limit
64 }
65}
66
67pub trait TchebycheffSolver<C, const N: usize> {
71 type Solution;
73
74 fn minimize(&mut self, scalarization: &Scalarization<C, N>)
76 -> Option<(Self::Solution, [C; N])>;
77}
78
79pub type TpaResult<X, C, const N: usize> = (Vec<(X, [C; N])>, bool);
82
83type Adjacency<S, W> = BTreeMap<S, Vec<(S, W)>>;
85
86#[derive(Debug, Clone)]
89struct Zone<C, const N: usize> {
90 lower: [C; N],
92 upper: [C; N],
94 priority: BigUint,
97}
98
99pub 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 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 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
195fn 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
223fn 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
237fn 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 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 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
283fn 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
309pub struct PathTchebycheff<'a, G: Graph, H, P> {
313 graph: &'a G,
315 heuristic: H,
317 start: <G as Graph>::State,
319 is_goal: P,
321 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
396pub 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 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
514fn 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 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 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}