Skip to main content

multiobjective_search/
dynamic.rs

1//! Dynamic multi-objective search: a graph whose edges change between
2//! queries, and a search that repairs its labels instead of starting over.
3//!
4//! The dynamic MOS setting of the survey by Salzman et al. (arXiv
5//! 2510.25504, Section 3.2), with the incremental repair of LPA* and D*
6//! Lite (Koenig and Likhachev) as carried to multiple objectives by
7//! multi-objective path-based D* Lite (Ren et al. 2022).
8
9use 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/// An explicit directed graph over states `0..nodes` whose edges can be
20/// added, re-costed and removed. Edge identities are the indices
21/// [`DynamicGraph::add_edge`] returns; a removed edge keeps its index.
22#[derive(Debug, Clone)]
23pub struct DynamicGraph<C, const N: usize> {
24    /// Edges by identity: `(from, to, cost)`, `None` once removed.
25    edges: Vec<Option<(u32, u32, [C; N])>>,
26    /// Outgoing edge identities per state.
27    out: Vec<Vec<usize>>,
28    /// Incoming edge identities per state.
29    into: Vec<Vec<usize>>,
30}
31
32impl<C: Cost, const N: usize> DynamicGraph<C, N> {
33    /// A graph over `nodes` states without edges.
34    ///
35    /// # Panics
36    ///
37    /// Never on 32- and 64-bit targets.
38    #[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    /// Adds an edge and returns its identity.
49    ///
50    /// # Panics
51    ///
52    /// Panics if a state is out of range.
53    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    /// The edge `id`, if it exists.
62    #[must_use]
63    pub fn edge(&self, id: usize) -> Option<(u32, u32, [C; N])> {
64        self.edges.get(id).copied().flatten()
65    }
66
67    /// The number of states.
68    #[must_use]
69    pub fn node_count(&self) -> usize {
70        self.out.len()
71    }
72}
73
74/// `state` as an index.
75fn 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/// One label: a path from the start, in the label tree.
117#[derive(Debug, Clone)]
118struct Label<C, const N: usize> {
119    /// The state it ends in.
120    state: u32,
121    /// Its cost under the current edge costs.
122    cost: [C; N],
123    /// The label it extends; `None` for the start.
124    parent: Option<usize>,
125    /// `false` once dominated or invalidated.
126    alive: bool,
127    /// Labels that extend this one.
128    children: Vec<usize>,
129}
130
131/// An incremental multi-objective search on a [`DynamicGraph`]: every
132/// state keeps the Pareto set of path costs from the start (label
133/// correcting), and edge changes repair only what they touch.
134///
135/// After [`DynamicSearch::set_cost`], [`DynamicSearch::remove_edge`] or
136/// [`DynamicSearch::add_edge`], the labels whose paths use the changed
137/// edge, and everything built on them, are dropped; every state that lost a
138/// label is re-seeded from the live labels of its predecessors, and label
139/// correcting runs from there, as LPA* re-expands only the inconsistent
140/// part of its search tree. Labels elsewhere stay. [`DynamicSearch::front`]
141/// then equals a fresh search's front.
142///
143/// Goal states end paths. Edge costs must be non-negative.
144///
145/// # Examples
146///
147/// ```
148/// use multiobjective_search::{DynamicGraph, DynamicSearch};
149///
150/// let mut graph = DynamicGraph::new(3);
151/// let direct = graph.add_edge(0, 2, [10_u32, 1]);
152/// graph.add_edge(0, 1, [1, 5]);
153/// graph.add_edge(1, 2, [1, 5]);
154///
155/// let mut search = DynamicSearch::new(graph, 0, |s: &u32| *s == 2);
156/// let costs = |s: &DynamicSearch<_, _, 2>| s.front().solutions.iter().map(|x| x.cost).collect::<Vec<_>>();
157/// assert_eq!(costs(&search), [[2, 10], [10, 1]]);
158///
159/// search.set_cost(direct, [1, 1]); // the direct road got better
160/// assert_eq!(costs(&search), [[1, 1]]);
161/// ```
162pub struct DynamicSearch<C, P, const N: usize> {
163    /// The current graph.
164    graph: DynamicGraph<C, N>,
165    /// Goal test.
166    is_goal: P,
167    /// Every label ever made.
168    labels: Vec<Label<C, N>>,
169    /// Live labels per state, mutually non-dominated.
170    sets: Vec<Vec<usize>>,
171    /// Labels per edge identity that extend along it.
172    via: Vec<Vec<usize>>,
173    /// Effort counters over all repairs.
174    stats: Stats,
175}
176
177impl<C: Cost, P: Fn(&u32) -> bool, const N: usize> DynamicSearch<C, P, N> {
178    /// Searches `graph` from `start`.
179    ///
180    /// # Panics
181    ///
182    /// Panics if `start` is not a state of `graph`.
183    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    /// The current graph.
201    pub const fn graph(&self) -> &DynamicGraph<C, N> {
202        &self.graph
203    }
204
205    /// Effort counters over the initial search and every repair.
206    pub const fn stats(&self) -> Stats {
207        self.stats
208    }
209
210    /// Changes the cost of edge `id` and repairs.
211    ///
212    /// # Panics
213    ///
214    /// Panics if the edge does not exist.
215    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    /// Removes edge `id` and repairs.
223    ///
224    /// # Panics
225    ///
226    /// Panics if the edge does not exist.
227    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    /// Adds an edge, repairs, and returns its identity.
233    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    /// The current Pareto-optimal goal paths, one per cost, sorted.
241    ///
242    /// # Panics
243    ///
244    /// Never: states are indexed by `u32`.
245    #[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    /// Drops every label built on edge `id`, re-seeds the states that lost
265    /// labels (and `head`, which a cheaper or new edge may improve) from
266    /// their predecessors, and propagates.
267    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    /// Kills `root` and every label built on it, recording their states.
296    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    /// Adds a label at `state` unless a live one there weakly dominates it,
312    /// dropping the live ones it dominates (but not what they built).
313    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    /// Label correcting from the labels in `queue`.
360    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    /// The path of label `l`.
380    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}