1use alloc::collections::{BTreeSet, VecDeque};
10use alloc::vec::Vec;
11
12use search_core::Cost;
13
14use crate::cost::{add, weakly_dominates};
15use crate::graph::{EdgeGraph, Graph, ReverseGraph};
16use crate::output::{Output, Solution, Stats};
17use crate::pareto::Front;
18
19#[derive(Debug, Clone)]
23pub struct DynamicGraph<C, const N: usize> {
24 edges: Vec<Option<(u32, u32, [C; N])>>,
26 out: Vec<Vec<usize>>,
28 into: Vec<Vec<usize>>,
30}
31
32impl<C: Cost, const N: usize> DynamicGraph<C, N> {
33 #[must_use]
39 pub fn new(nodes: u32) -> Self {
40 let n = usize::try_from(nodes).expect("u32 fits in usize");
41 Self {
42 edges: Vec::new(),
43 out: alloc::vec![Vec::new(); n],
44 into: alloc::vec![Vec::new(); n],
45 }
46 }
47
48 pub fn add_edge(&mut self, from: u32, to: u32, cost: [C; N]) -> usize {
54 let id = self.edges.len();
55 self.edges.push(Some((from, to, cost)));
56 self.out[index(from)].push(id);
57 self.into[index(to)].push(id);
58 id
59 }
60
61 #[must_use]
63 pub fn edge(&self, id: usize) -> Option<(u32, u32, [C; N])> {
64 self.edges.get(id).copied().flatten()
65 }
66
67 #[must_use]
69 pub fn node_count(&self) -> usize {
70 self.out.len()
71 }
72}
73
74fn index(state: u32) -> usize {
76 usize::try_from(state).expect("u32 fits in usize")
77}
78
79impl<C: Cost, const N: usize> Graph for DynamicGraph<C, N> {
80 type State = u32;
81 type Weight = [C; N];
82
83 fn successors(&self, state: &u32, out: &mut Vec<(u32, [C; N])>) {
84 out.extend(
85 self.out[index(*state)]
86 .iter()
87 .filter_map(|&e| self.edges[e])
88 .map(|(_, to, c)| (to, c)),
89 );
90 }
91}
92
93impl<C: Cost, const N: usize> ReverseGraph for DynamicGraph<C, N> {
94 fn predecessors(&self, state: &u32, out: &mut Vec<(u32, [C; N])>) {
95 out.extend(
96 self.into[index(*state)]
97 .iter()
98 .filter_map(|&e| self.edges[e])
99 .map(|(from, _, c)| (from, c)),
100 );
101 }
102}
103
104impl<C: Cost, const N: usize> EdgeGraph for DynamicGraph<C, N> {
105 type Edge = usize;
106
107 fn edges(&self, state: &u32, out: &mut Vec<(usize, u32, [C; N])>) {
108 out.extend(
109 self.out[index(*state)]
110 .iter()
111 .filter_map(|&e| self.edges[e].map(|(_, to, c)| (e, to, c))),
112 );
113 }
114}
115
116#[derive(Debug, Clone)]
118struct Label<C, const N: usize> {
119 state: u32,
121 cost: [C; N],
123 parent: Option<usize>,
125 alive: bool,
127 children: Vec<usize>,
129}
130
131pub struct DynamicSearch<C, P, const N: usize> {
163 graph: DynamicGraph<C, N>,
165 is_goal: P,
167 labels: Vec<Label<C, N>>,
169 sets: Vec<Vec<usize>>,
171 via: Vec<Vec<usize>>,
173 stats: Stats,
175}
176
177impl<C: Cost, P: Fn(&u32) -> bool, const N: usize> DynamicSearch<C, P, N> {
178 pub fn new(graph: DynamicGraph<C, N>, start: u32, is_goal: P) -> Self {
184 let mut search = Self {
185 sets: alloc::vec![Vec::new(); graph.node_count()],
186 via: alloc::vec![Vec::new(); graph.edges.len()],
187 graph,
188 is_goal,
189 labels: Vec::new(),
190 stats: Stats::default(),
191 };
192
193 let root = search
194 .insert(start, [C::ZERO; N], None, None)
195 .expect("the first label");
196 search.propagate(VecDeque::from([root]));
197 search
198 }
199
200 pub const fn graph(&self) -> &DynamicGraph<C, N> {
202 &self.graph
203 }
204
205 pub const fn stats(&self) -> Stats {
207 self.stats
208 }
209
210 pub fn set_cost(&mut self, id: usize, cost: [C; N]) {
216 let edge = self.graph.edges[id].as_mut().expect("an existing edge");
217 edge.2 = cost;
218 let head = edge.1;
219 self.repair(id, head);
220 }
221
222 pub fn remove_edge(&mut self, id: usize) {
228 let (_, head, _) = self.graph.edges[id].take().expect("an existing edge");
229 self.repair(id, head);
230 }
231
232 pub fn add_edge(&mut self, from: u32, to: u32, cost: [C; N]) -> usize {
234 let id = self.graph.add_edge(from, to, cost);
235 self.via.push(Vec::new());
236 self.repair(id, to);
237 id
238 }
239
240 #[must_use]
246 pub fn front(&self) -> Output<u32, [C; N]> {
247 let mut ends: Vec<usize> = (0..self.sets.len())
248 .filter(|&s| (self.is_goal)(&u32::try_from(s).expect("state index")))
249 .flat_map(|s| self.sets[s].iter().copied())
250 .collect();
251 ends.sort_by_key(|&l| self.labels[l].cost);
252 let mut front = Front::new();
253
254 Output {
255 solutions: ends
256 .into_iter()
257 .filter(|&l| front.insert(self.labels[l].cost))
258 .map(|l| self.solution(l))
259 .collect(),
260 stats: self.stats,
261 }
262 }
263
264 fn repair(&mut self, id: usize, head: u32) {
268 let mut affected = BTreeSet::from([head]);
269 for root in core::mem::take(&mut self.via[id]) {
270 self.kill(root, &mut affected);
271 }
272
273 let mut queue = VecDeque::new();
274 for &target in &affected {
275 for &e in &self.graph.into[index(target)].clone() {
276 let Some((from, to, w)) = self.graph.edges[e] else {
277 continue;
278 };
279 if (self.is_goal)(&from) {
280 continue;
281 }
282
283 for l in self.sets[index(from)].clone() {
284 let cost = add(self.labels[l].cost, w);
285 if let Some(new) = self.insert(to, cost, Some(l), Some(e)) {
286 queue.push_back(new);
287 }
288 }
289 }
290 }
291
292 self.propagate(queue);
293 }
294
295 fn kill(&mut self, root: usize, affected: &mut BTreeSet<u32>) {
297 let mut stack = alloc::vec![root];
298 while let Some(l) = stack.pop() {
299 let label = &mut self.labels[l];
300 if label.alive {
301 label.alive = false;
302 let state = label.state;
303 self.sets[index(state)].retain(|&k| k != l);
304 affected.insert(state);
305 }
306
307 stack.append(&mut self.labels[l].children);
308 }
309 }
310
311 fn insert(
314 &mut self,
315 state: u32,
316 cost: [C; N],
317 parent: Option<usize>,
318 via: Option<usize>,
319 ) -> Option<usize> {
320 let set = &self.sets[index(state)];
321 if set
322 .iter()
323 .any(|&k| weakly_dominates(&self.labels[k].cost, &cost))
324 {
325 return None;
326 }
327
328 let labels = &mut self.labels;
329 self.sets[index(state)].retain(|&k| {
330 let dominated = weakly_dominates(&cost, &labels[k].cost);
331 if dominated {
332 labels[k].alive = false;
333 }
334
335 !dominated
336 });
337
338 let id = self.labels.len();
339 self.labels.push(Label {
340 state,
341 cost,
342 parent,
343 alive: true,
344 children: Vec::new(),
345 });
346 self.sets[index(state)].push(id);
347 if let Some(p) = parent {
348 self.labels[p].children.push(id);
349 }
350
351 if let Some(e) = via {
352 self.via[e].push(id);
353 }
354
355 self.stats.generated += 1;
356 Some(id)
357 }
358
359 fn propagate(&mut self, mut queue: VecDeque<usize>) {
361 while let Some(l) = queue.pop_front() {
362 let (state, cost) = (self.labels[l].state, self.labels[l].cost);
363 if !self.labels[l].alive || (self.is_goal)(&state) {
364 continue;
365 }
366
367 self.stats.expanded += 1;
368 for &e in &self.graph.out[index(state)].clone() {
369 let Some((_, to, w)) = self.graph.edges[e] else {
370 continue;
371 };
372 if let Some(new) = self.insert(to, add(cost, w), Some(l), Some(e)) {
373 queue.push_back(new);
374 }
375 }
376 }
377 }
378
379 fn solution(&self, l: usize) -> Solution<u32, [C; N]> {
381 let mut path = Vec::new();
382 let mut at = Some(l);
383 while let Some(i) = at {
384 path.push(self.labels[i].state);
385 at = self.labels[i].parent;
386 }
387
388 path.reverse();
389 Solution {
390 cost: self.labels[l].cost,
391 path,
392 }
393 }
394}