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/// Reports conflicts to `visit` in time order until it returns `false`.
96fn scan<P: AsRef<[Vertex]>>(paths: &[P], mut visit: impl FnMut(Conflict) -> bool) {
97    let paths: Vec<&[Vertex]> = paths.iter().map(AsRef::as_ref).collect();
98    let horizon = paths.iter().map(|path| path.len()).max().unwrap_or(0);
99    let horizon = Time::try_from(horizon).expect("path lengths fit in u32 time steps");
100
101    for time in 0..horizon {
102        if !scan_time(&paths, time, &mut visit) {
103            return;
104        }
105    }
106}
107
108/// Reports the conflicts at `time` (and swaps starting at `time`) between every pair of
109/// `paths` to `visit`. Returns `false` as soon as `visit` does.
110fn scan_time(paths: &[&[Vertex]], time: Time, visit: &mut impl FnMut(Conflict) -> bool) -> bool {
111    for (i, a) in paths.iter().enumerate() {
112        for (j, b) in paths.iter().enumerate().skip(i + 1) {
113            let pair = conflicts_at(a, b, (i, j), time);
114            if pair.into_iter().flatten().any(|conflict| !visit(conflict)) {
115                return false;
116            }
117        }
118    }
119
120    true
121}
122
123/// The vertex conflict at `time` and the swap from `time` to `time + 1` between paths `a`
124/// and `b` of `agents`, if any.
125fn conflicts_at(
126    a: &[Vertex],
127    b: &[Vertex],
128    agents: (AgentId, AgentId),
129    time: Time,
130) -> [Option<Conflict>; 2] {
131    let (a_now, b_now) = (position_at(a, time), position_at(b, time));
132    let (a_next, b_next) = (position_at(a, time + 1), position_at(b, time + 1));
133
134    let vertex = (a_now == b_now).then_some(Conflict::Vertex {
135        agents,
136        vertex: a_now,
137        time,
138    });
139    let swap = (a_now != a_next && a_now == b_next && a_next == b_now).then_some(Conflict::Edge {
140        agents,
141        from: a_now,
142        to: a_next,
143        time,
144    });
145
146    [vertex, swap]
147}