Skip to main content

mapf_search/
conflict.rs

1//! Conflicts between agents' paths ([`Conflict`]) and their detection
2//! ([`first_conflict`], [`conflicts`]).
3//!
4//! Detection follows goal-stay semantics: a path that ended keeps occupying its last
5//! vertex, so an agent waiting at its goal conflicts with every agent passing through it.
6
7use alloc::vec::Vec;
8
9use crate::graph::Vertex;
10use crate::instance::AgentId;
11use crate::path::{Time, position_at};
12
13/// A conflict between the paths of two agents.
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
15pub enum Conflict {
16    /// Both agents occupy `vertex` at `time`.
17    Vertex {
18        /// The two agents, the smaller id first.
19        agents: (AgentId, AgentId),
20        /// The shared vertex.
21        vertex: Vertex,
22        /// The time step.
23        time: Time,
24    },
25    /// The agents swap vertices: the first moves `from -> to` while the second moves
26    /// `to -> from`, between `time` and `time + 1`. `from != to`.
27    Edge {
28        /// The two agents, the smaller id first.
29        agents: (AgentId, AgentId),
30        /// The vertex the first agent leaves and the second enters.
31        from: Vertex,
32        /// The vertex the first agent enters and the second leaves.
33        to: Vertex,
34        /// The time step at which the swap starts.
35        time: Time,
36    },
37}
38
39impl Conflict {
40    /// The two agents involved, the smaller id first.
41    #[must_use]
42    pub fn agents(&self) -> (AgentId, AgentId) {
43        match *self {
44            Self::Vertex { agents, .. } | Self::Edge { agents, .. } => agents,
45        }
46    }
47
48    /// The time step the conflict happens at (for swaps: the step it starts at).
49    #[must_use]
50    pub fn time(&self) -> Time {
51        match *self {
52            Self::Vertex { time, .. } | Self::Edge { time, .. } => time,
53        }
54    }
55}
56
57/// The earliest conflict among `paths`, indexed by agent: smallest time first, then the
58/// smallest agent pair, and a vertex conflict before a swap starting at the same time.
59///
60/// Returns `None` if the paths are conflict-free.
61///
62/// # Panics
63///
64/// Panics if a path is empty.
65#[must_use]
66pub fn first_conflict<P: AsRef<[Vertex]>>(paths: &[P]) -> Option<Conflict> {
67    let mut found = None;
68    scan(paths, |conflict| {
69        found = Some(conflict);
70        false
71    });
72
73    found
74}
75
76/// All conflicts among `paths`, in the order of [`first_conflict`].
77///
78/// An agent that waits at its goal can conflict with another agent at many time steps;
79/// each counts.
80///
81/// # Panics
82///
83/// Panics if a path is empty.
84#[must_use]
85pub fn conflicts<P: AsRef<[Vertex]>>(paths: &[P]) -> Vec<Conflict> {
86    let mut found = Vec::new();
87    scan(paths, |conflict| {
88        found.push(conflict);
89        true
90    });
91
92    found
93}
94
95/// `found`, the conflicts among an earlier version of `paths`, after the agents in
96/// `changed` took new paths: the old conflicts between unchanged agents, and those of the
97/// changed agents rescanned, in the order of [`first_conflict`].
98///
99/// Costs `O(k n T)` for `k` changed agents of `n` with paths of up to `T` positions,
100/// where [`conflicts`] costs `O(n^2 T)`.
101///
102/// # Panics
103///
104/// Panics if a path is empty.
105pub(crate) fn update_conflicts<P: AsRef<[Vertex]>>(
106    found: &[Conflict],
107    paths: &[P],
108    changed: &[AgentId],
109) -> Vec<Conflict> {
110    let paths: Vec<&[Vertex]> = paths.iter().map(AsRef::as_ref).collect();
111    let involved = |conflict: &Conflict| {
112        let (a, b) = conflict.agents();
113        changed.contains(&a) || changed.contains(&b)
114    };
115
116    let mut updated: Vec<Conflict> = found.iter().filter(|c| !involved(c)).copied().collect();
117    for time in 0..horizon(&paths) {
118        for &a in changed {
119            // A pair of two changed agents is scanned once, from its smaller agent.
120            let others = (0..paths.len()).filter(|&b| b != a && !(b < a && changed.contains(&b)));
121            for b in others {
122                let pair = (a.min(b), a.max(b));
123                let found = conflicts_at(paths[pair.0], paths[pair.1], pair, time);
124                updated.extend(found.into_iter().flatten());
125            }
126        }
127    }
128
129    updated.sort_unstable_by_key(scan_order);
130
131    updated
132}
133
134/// The position of `conflict` in the order of [`first_conflict`]: by time, then agent
135/// pair, then a vertex conflict before a swap.
136fn scan_order(conflict: &Conflict) -> (Time, (AgentId, AgentId), bool) {
137    (
138        conflict.time(),
139        conflict.agents(),
140        matches!(conflict, Conflict::Edge { .. }),
141    )
142}
143
144/// The number of time steps to scan `paths` for conflicts: the longest path's length.
145fn horizon(paths: &[&[Vertex]]) -> Time {
146    let longest = paths.iter().map(|path| path.len()).max().unwrap_or(0);
147
148    Time::try_from(longest).expect("path lengths fit in u32 time steps")
149}
150
151/// Reports conflicts to `visit` in time order until it returns `false`.
152fn scan<P: AsRef<[Vertex]>>(paths: &[P], mut visit: impl FnMut(Conflict) -> bool) {
153    let paths: Vec<&[Vertex]> = paths.iter().map(AsRef::as_ref).collect();
154
155    for time in 0..horizon(&paths) {
156        if !scan_time(&paths, time, &mut visit) {
157            return;
158        }
159    }
160}
161
162/// Reports the conflicts at `time` (and swaps starting at `time`) between every pair of
163/// `paths` to `visit`. Returns `false` as soon as `visit` does.
164fn scan_time(paths: &[&[Vertex]], time: Time, visit: &mut impl FnMut(Conflict) -> bool) -> bool {
165    for (i, a) in paths.iter().enumerate() {
166        for (j, b) in paths.iter().enumerate().skip(i + 1) {
167            let pair = conflicts_at(a, b, (i, j), time);
168            if pair.into_iter().flatten().any(|conflict| !visit(conflict)) {
169                return false;
170            }
171        }
172    }
173
174    true
175}
176
177/// The vertex conflict at `time` and the swap from `time` to `time + 1` between paths `a`
178/// and `b` of `agents`, if any.
179fn conflicts_at(
180    a: &[Vertex],
181    b: &[Vertex],
182    agents: (AgentId, AgentId),
183    time: Time,
184) -> [Option<Conflict>; 2] {
185    let (a_now, b_now) = (position_at(a, time), position_at(b, time));
186    let (a_next, b_next) = (position_at(a, time + 1), position_at(b, time + 1));
187
188    let vertex = (a_now == b_now).then_some(Conflict::Vertex {
189        agents,
190        vertex: a_now,
191        time,
192    });
193    let swap = (a_now != a_next && a_now == b_next && a_next == b_now).then_some(Conflict::Edge {
194        agents,
195        from: a_now,
196        to: a_next,
197        time,
198    });
199
200    [vertex, swap]
201}
202
203#[cfg(test)]
204mod tests {
205    //! Unit tests for incremental conflict detection.
206
207    use super::*;
208    use alloc::vec;
209
210    /// Updating after some agents changed gives what a full scan gives, in the same order.
211    #[test]
212    fn update_matches_a_full_scan() {
213        let before = [vec![0, 1, 2], vec![2, 1, 0], vec![5, 1, 6], vec![7, 6, 5]];
214        let after = [
215            vec![0, 1, 2],
216            vec![2, 2, 1, 0],
217            vec![5, 1, 6],
218            vec![6, 6, 5],
219        ];
220        let found = conflicts(&before);
221
222        for changed in [&[][..], &[1], &[3], &[1, 3], &[3, 1], &[0, 1, 2, 3]] {
223            let paths: Vec<_> = (0..4)
224                .map(|agent| {
225                    if changed.contains(&agent) {
226                        &after[agent]
227                    } else {
228                        &before[agent]
229                    }
230                })
231                .collect();
232
233            assert_eq!(
234                update_conflicts(&found, &paths, changed),
235                conflicts(&paths),
236                "changed {changed:?}"
237            );
238        }
239    }
240}