1use alloc::collections::{BTreeMap, BTreeSet, BinaryHeap};
11use alloc::vec::Vec;
12use core::cmp::{Ordering, Reverse};
13
14use search_core::{Cost, Heuristic, WideMul};
15
16use crate::anytime_boa::lex::lex_first;
17use crate::constrained::rebuild;
18use crate::cost::add;
19use crate::graph::Graph;
20use crate::output::{Output, Solution, Stats};
21
22#[expect(
60 clippy::needless_pass_by_value,
61 reason = "takes the start by value like every other search in the crate"
62)]
63pub fn supported_solutions<G, H, C, P>(
64 graph: &G,
65 mut heuristic: H,
66 start: G::State,
67 is_goal: P,
68) -> Output<G::State, [C; 2]>
69where
70 G: Graph<Weight = [C; 2]>,
71 H: Heuristic<G::State, [C; 2]>,
72 C: Cost + WideMul,
73 P: Fn(&G::State) -> bool,
74{
75 let mut stats = Stats::default();
76 let solutions = phase_one(graph, &mut heuristic, &start, &is_goal, &mut stats);
77
78 Output { solutions, stats }
79}
80
81#[expect(
117 clippy::needless_pass_by_value,
118 reason = "takes the start by value like every other search in the crate"
119)]
120pub fn two_phase<G, H, C, P>(
121 graph: &G,
122 mut heuristic: H,
123 start: G::State,
124 is_goal: P,
125) -> Output<G::State, [C; 2]>
126where
127 G: Graph<Weight = [C; 2]>,
128 H: Heuristic<G::State, [C; 2]>,
129 C: Cost + WideMul,
130 P: Fn(&G::State) -> bool,
131{
132 let mut stats = Stats::default();
133 let supported = phase_one(graph, &mut heuristic, &start, &is_goal, &mut stats);
134
135 let mut solutions = Vec::new();
136 for pair in supported.windows(2) {
137 let (a, b) = (pair[0].cost, pair[1].cost);
138 solutions.extend(in_box(
139 graph,
140 &mut heuristic,
141 &start,
142 &is_goal,
143 a,
144 b,
145 &mut stats,
146 ));
147 }
148
149 solutions.extend(supported);
150 solutions.sort_by_key(|s| s.cost);
151
152 Output { solutions, stats }
153}
154
155fn phase_one<G, H, C, P>(
157 graph: &G,
158 heuristic: &mut H,
159 start: &G::State,
160 is_goal: &P,
161 stats: &mut Stats,
162) -> Vec<Solution<G::State, [C; 2]>>
163where
164 G: Graph<Weight = [C; 2]>,
165 H: Heuristic<G::State, [C; 2]>,
166 C: Cost + WideMul,
167 P: Fn(&G::State) -> bool,
168{
169 let Some(left) = lex_first(graph, heuristic, start, is_goal, 0, stats) else {
170 return Vec::new();
171 };
172 let right = lex_first(graph, heuristic, start, is_goal, 1, stats)
173 .expect("reachable in one order, reachable in the other");
174 if left.cost == right.cost {
175 return alloc::vec![left];
176 }
177
178 let mut found = alloc::vec![left];
179 let mut pending = alloc::vec![right];
180 while let Some(b) = pending.pop() {
181 let a = found.last().expect("starts with the left optimum").cost;
182 let weights = [a[1].abs_diff(b.cost[1]), b.cost[0].abs_diff(a[0])];
183 let best = weighted_best(graph, heuristic, start, is_goal, weights, stats)
184 .expect("a solution exists");
185
186 if weighted_cmp(weights, best.cost, a) == Ordering::Less {
187 pending.push(b);
188 pending.push(best);
189 } else {
190 found.push(b);
191 }
192 }
193
194 found
195}
196
197fn weighted_cmp<C: Cost + WideMul>(w: [C; 2], x: [C; 2], y: [C; 2]) -> Ordering {
199 let part = |i: usize| (x[i].cmp(&y[i]), w[i].wide_mul(x[i].abs_diff(y[i])));
200 let ((s1, m1), (s2, m2)) = (part(0), part(1));
201
202 match (s1, s2) {
203 (Ordering::Equal, s) | (s, Ordering::Equal) => s,
204 (left, right) if left == right => left,
205 (Ordering::Greater, _) => m1.cmp(&m2),
207 (Ordering::Less, _) => m2.cmp(&m1),
208 }
209}
210
211fn weighted_best<G, H, C, P>(
214 graph: &G,
215 heuristic: &mut H,
216 start: &G::State,
217 is_goal: &P,
218 weights: [C; 2],
219 stats: &mut Stats,
220) -> Option<Solution<G::State, [C; 2]>>
221where
222 G: Graph<Weight = [C; 2]>,
223 H: Heuristic<G::State, [C; 2]>,
224 C: Cost + WideMul,
225 P: Fn(&G::State) -> bool,
226{
227 let mut nodes: Vec<(G::State, [C; 2], Option<usize>)> = Vec::new();
228 let mut open = BinaryHeap::new();
229 let mut closed = BTreeSet::new();
230 let mut successors = Vec::new();
231
232 let h = heuristic.estimate(start)?;
233 nodes.push((start.clone(), [C::ZERO; 2], None));
234 open.push(Reverse(Weighted {
235 weights,
236 f: h,
237 index: 0,
238 }));
239 stats.generated += 1;
240
241 while let Some(Reverse(Weighted { index, .. })) = open.pop() {
242 let (here, g, _) = nodes[index].clone();
243 if !closed.insert(here.clone()) {
244 continue;
245 }
246
247 if is_goal(&here) {
248 return Some(rebuild(&nodes, index));
249 }
250
251 stats.expanded += 1;
252 graph.successors(&here, &mut successors);
253 for (next, weight) in successors.drain(..) {
254 if closed.contains(&next) {
255 continue;
256 }
257
258 let Some(h) = heuristic.estimate(&next) else {
259 continue;
260 };
261
262 let g_next = add(g, weight);
263 nodes.push((next, g_next, Some(index)));
264 open.push(Reverse(Weighted {
265 weights,
266 f: add(g_next, h),
267 index: nodes.len() - 1,
268 }));
269 stats.generated += 1;
270 }
271 }
272
273 None
274}
275
276struct Weighted<C> {
279 weights: [C; 2],
281 f: [C; 2],
283 index: usize,
285}
286
287impl<C: Cost + WideMul> PartialEq for Weighted<C> {
288 fn eq(&self, other: &Self) -> bool {
289 self.cmp(other) == Ordering::Equal
290 }
291}
292
293impl<C: Cost + WideMul> Eq for Weighted<C> {}
294
295impl<C: Cost + WideMul> PartialOrd for Weighted<C> {
296 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
297 Some(self.cmp(other))
298 }
299}
300
301impl<C: Cost + WideMul> Ord for Weighted<C> {
302 fn cmp(&self, other: &Self) -> Ordering {
303 weighted_cmp(self.weights, self.f, other.f)
304 .then(self.f.cmp(&other.f))
305 .then(self.index.cmp(&other.index))
306 }
307}
308
309fn in_box<G, H, C, P>(
313 graph: &G,
314 heuristic: &mut H,
315 start: &G::State,
316 is_goal: &P,
317 left: [C; 2],
318 right: [C; 2],
319 stats: &mut Stats,
320) -> Vec<Solution<G::State, [C; 2]>>
321where
322 G: Graph<Weight = [C; 2]>,
323 H: Heuristic<G::State, [C; 2]>,
324 C: Cost,
325 P: Fn(&G::State) -> bool,
326{
327 let mut nodes: Vec<(G::State, [C; 2], Option<usize>)> = Vec::new();
328 let mut open = BinaryHeap::new();
329 let mut g2_min: BTreeMap<G::State, C> = BTreeMap::new();
330 let mut bound = left[1];
331 let mut found = Vec::new();
332 let mut successors = Vec::new();
333 let outside = |f: [C; 2], bound: C| f[0] >= right[0] || f[1] >= bound;
334
335 let Some(h) = heuristic.estimate(start) else {
336 return found;
337 };
338 nodes.push((start.clone(), [C::ZERO; 2], None));
339 open.push(Reverse((h, 0)));
340 stats.generated += 1;
341
342 while let Some(Reverse((f, index))) = open.pop() {
343 let (here, g, _) = nodes[index].clone();
344 if outside(f, bound) || g2_min.get(&here).is_some_and(|&m| g[1] >= m) {
345 continue;
346 }
347
348 g2_min.insert(here.clone(), g[1]);
349 if is_goal(&here) {
350 bound = g[1];
351 found.push(rebuild(&nodes, index));
352 continue;
353 }
354
355 stats.expanded += 1;
356 graph.successors(&here, &mut successors);
357 for (next, weight) in successors.drain(..) {
358 let g_next = add(g, weight);
359 if g2_min.get(&next).is_some_and(|&m| g_next[1] >= m) {
360 continue;
361 }
362
363 let Some(h) = heuristic.estimate(&next) else {
364 continue;
365 };
366
367 let f = add(g_next, h);
368 if !outside(f, bound) {
369 nodes.push((next, g_next, Some(index)));
370 open.push(Reverse((f, nodes.len() - 1)));
371 stats.generated += 1;
372 }
373 }
374 }
375
376 found.retain(|s| s.cost[0] > left[0] && s.cost[1] > right[1]);
379 found
380}