1use alloc::collections::{BTreeMap, BinaryHeap};
10use alloc::vec::Vec;
11use core::cmp::{Ordering, Reverse};
12
13use search_core::{Cost, Heuristic, WideMul};
14
15use crate::constrained::rebuild;
16use crate::cost::add;
17use crate::graph::Graph;
18use crate::output::{Solution, Stats};
19use crate::pareto::Front;
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
23pub enum Achievement<C> {
24 Below(C),
27 Above(C),
29}
30
31impl<C: Ord> PartialOrd for Achievement<C> {
32 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
33 Some(self.cmp(other))
34 }
35}
36
37impl<C: Ord> Ord for Achievement<C> {
38 fn cmp(&self, other: &Self) -> Ordering {
39 match (self, other) {
40 (Self::Below(a), Self::Below(b)) => b.cmp(a),
41 (Self::Above(a), Self::Above(b)) => a.cmp(b),
42 (Self::Below(_), Self::Above(_)) => Ordering::Less,
43 (Self::Above(_), Self::Below(_)) => Ordering::Greater,
44 }
45 }
46}
47
48#[must_use]
51pub fn achievement<C: Cost + WideMul, const N: usize>(
52 cost: &[C; N],
53 reference: &[C; N],
54 weights: &[u32; N],
55) -> Achievement<C> {
56 (0..N)
57 .map(|i| {
58 let gap = cost[i].abs_diff(reference[i]).saturating_times(weights[i]);
59 if cost[i] >= reference[i] {
60 Achievement::Above(gap)
61 } else {
62 Achievement::Below(gap)
63 }
64 })
65 .max()
66 .unwrap_or(Achievement::Above(C::ZERO))
67}
68
69type Key<C, const N: usize> = (Achievement<C>, [C; N], usize);
71
72pub struct ReferencePoint<'a, G: Graph, H, C, P, const N: usize> {
118 graph: &'a G,
120 heuristic: H,
122 is_goal: P,
124 reference: [C; N],
126 weights: [u32; N],
128 nodes: Vec<(G::State, [C; N], Option<usize>)>,
130 open: BinaryHeap<Reverse<Key<C, N>>>,
132 closed: BTreeMap<G::State, Front<C, N>>,
134 returned: Front<C, N>,
136 successors: Vec<(G::State, [C; N])>,
138 stats: Stats,
140}
141
142impl<'a, G, H, C, P, const N: usize> ReferencePoint<'a, G, H, C, P, N>
143where
144 G: Graph<Weight = [C; N]>,
145 H: Heuristic<G::State, [C; N]>,
146 C: Cost + WideMul,
147 P: Fn(&G::State) -> bool,
148{
149 pub fn new(
151 graph: &'a G,
152 mut heuristic: H,
153 start: G::State,
154 is_goal: P,
155 reference: [C; N],
156 weights: [u32; N],
157 ) -> Self {
158 let first = heuristic.estimate(&start);
159 let mut search = Self {
160 graph,
161 heuristic,
162 is_goal,
163 reference,
164 weights,
165 nodes: Vec::new(),
166 open: BinaryHeap::new(),
167 closed: BTreeMap::new(),
168 returned: Front::new(),
169 successors: Vec::new(),
170 stats: Stats::default(),
171 };
172
173 if let Some(h) = first {
174 search.push(start, [C::ZERO; N], h, None);
175 }
176
177 search
178 }
179
180 pub fn aim(&mut self, reference: [C; N], weights: [u32; N]) {
183 self.reference = reference;
184 self.weights = weights;
185
186 let entries: Vec<_> = self.open.drain().map(|Reverse((_, f, i))| (f, i)).collect();
187 for (f, index) in entries {
188 let key = achievement(&f, &self.reference, &self.weights);
189 self.open.push(Reverse((key, f, index)));
190 }
191 }
192
193 #[must_use]
195 pub const fn stats(&self) -> Stats {
196 self.stats
197 }
198
199 fn push(&mut self, state: G::State, g: [C; N], h: [C; N], parent: Option<usize>) {
201 let f = add(g, h);
202 let key = achievement(&f, &self.reference, &self.weights);
203 self.nodes.push((state, g, parent));
204 self.open.push(Reverse((key, f, self.nodes.len() - 1)));
205 self.stats.generated += 1;
206 }
207
208 fn expand(&mut self, index: usize) {
210 self.stats.expanded += 1;
211
212 let mut successors = core::mem::take(&mut self.successors);
213 let (state, g) = (self.nodes[index].0.clone(), self.nodes[index].1);
214 self.graph.successors(&state, &mut successors);
215
216 for (next, weight) in successors.drain(..) {
217 let g_next = add(g, weight);
218 if self
219 .closed
220 .get(&next)
221 .is_some_and(|c| c.weakly_dominates(&g_next))
222 {
223 continue;
224 }
225
226 let Some(h) = self.heuristic.estimate(&next) else {
227 continue;
228 };
229
230 if !self.returned.weakly_dominates(&add(g_next, h)) {
231 self.push(next, g_next, h, Some(index));
232 }
233 }
234
235 self.successors = successors;
236 }
237}
238
239impl<G, H, C, P, const N: usize> Iterator for ReferencePoint<'_, G, H, C, P, N>
240where
241 G: Graph<Weight = [C; N]>,
242 H: Heuristic<G::State, [C; N]>,
243 C: Cost + WideMul,
244 P: Fn(&G::State) -> bool,
245{
246 type Item = Solution<G::State, [C; N]>;
247
248 fn next(&mut self) -> Option<Self::Item> {
250 while let Some(Reverse((_, f, index))) = self.open.pop() {
251 let (state, g) = (self.nodes[index].0.clone(), self.nodes[index].1);
252 if self.returned.weakly_dominates(&f)
253 || self
254 .closed
255 .get(&state)
256 .is_some_and(|c| c.weakly_dominates(&g))
257 {
258 continue;
259 }
260
261 self.closed.entry(state.clone()).or_default().insert(g);
262 if (self.is_goal)(&state) {
263 self.returned.insert(g);
264 return Some(rebuild(&self.nodes, index));
265 }
266
267 self.expand(index);
268 }
269
270 None
271 }
272}