mapf_search/instance.rs
1//! A MAPF problem instance: a [`Graph`] and a list of [`Agent`]s, validated by
2//! [`Instance::new`]; and its task-assignment variant, [`TaskInstance`], whose agents each
3//! have a set of candidate goals.
4
5use alloc::vec::Vec;
6use core::fmt;
7
8use crate::graph::{Graph, Vertex};
9
10/// Index of an agent in [`Instance::agents`].
11pub type AgentId = usize;
12
13/// One agent: where it starts and where it must end up and stay.
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
15pub struct Agent {
16 /// The vertex the agent occupies at time `0`.
17 pub start: Vertex,
18 /// The vertex the agent must reach and then occupy forever (goal-stay semantics).
19 pub goal: Vertex,
20}
21
22/// A validated MAPF instance.
23///
24/// Starts are pairwise distinct, goals are pairwise distinct, and every start and goal is a
25/// vertex of the graph.
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub struct Instance<G> {
28 /// The graph the agents move on.
29 graph: G,
30 /// The agents, indexed by [`AgentId`].
31 agents: Vec<Agent>,
32}
33
34impl<G: Graph> Instance<G> {
35 /// Creates an instance after checking the agents against the graph.
36 ///
37 /// # Errors
38 ///
39 /// - [`InstanceError::OutOfRange`] if a start or goal is not a vertex of `graph`;
40 /// - [`InstanceError::SharedStart`] if two agents start at the same vertex;
41 /// - [`InstanceError::SharedGoal`] if two agents have the same goal, which goal-stay
42 /// semantics makes unsolvable.
43 pub fn new(graph: G, agents: Vec<Agent>) -> Result<Self, InstanceError> {
44 let count = graph.vertex_count();
45 for (agent, a) in agents.iter().enumerate() {
46 if a.start >= count || a.goal >= count {
47 return Err(InstanceError::OutOfRange { agent });
48 }
49
50 if let Some(other) = agents[..agent].iter().position(|b| b.start == a.start) {
51 return Err(InstanceError::SharedStart(other, agent));
52 }
53
54 if let Some(other) = agents[..agent].iter().position(|b| b.goal == a.goal) {
55 return Err(InstanceError::SharedGoal(other, agent));
56 }
57 }
58
59 Ok(Self { graph, agents })
60 }
61
62 /// The graph the agents move on.
63 #[must_use]
64 pub fn graph(&self) -> &G {
65 &self.graph
66 }
67
68 /// The agents, indexed by [`AgentId`].
69 #[must_use]
70 pub fn agents(&self) -> &[Agent] {
71 &self.agents
72 }
73}
74
75/// One agent of a [`TaskInstance`]: where it starts and the goals it may be assigned.
76#[derive(Debug, Clone, PartialEq, Eq, Hash)]
77pub struct TaskAgent {
78 /// The vertex the agent occupies at time `0`.
79 pub start: Vertex,
80 /// The vertices the agent may end up at, one of which a solution assigns to it and to
81 /// no other agent. The order does not matter; an empty list makes the instance
82 /// unsolvable.
83 pub goals: Vec<Vertex>,
84}
85
86/// A validated task-assignment MAPF instance: each agent must end at one of its candidate
87/// goals, and no two agents at the same one.
88///
89/// Starts are pairwise distinct, and every start and candidate goal is a vertex of the
90/// graph. Agents may share candidate goals.
91///
92/// # Examples
93///
94/// ```
95/// use mapf_search::{Grid, TaskAgent, TaskInstance};
96///
97/// let grid = Grid::new(3, 1);
98/// let anywhere = vec![0, 1, 2];
99/// let agents = vec![
100/// TaskAgent { start: 0, goals: anywhere.clone() },
101/// TaskAgent { start: 2, goals: anywhere },
102/// ];
103///
104/// let instance = TaskInstance::new(grid, agents)?;
105/// assert_eq!(instance.agents()[1].goals, [0, 1, 2]);
106/// # Ok::<(), mapf_search::InstanceError>(())
107/// ```
108#[derive(Debug, Clone, PartialEq, Eq)]
109pub struct TaskInstance<G> {
110 /// The graph the agents move on.
111 graph: G,
112 /// The agents, indexed by [`AgentId`].
113 agents: Vec<TaskAgent>,
114}
115
116impl<G: Graph> TaskInstance<G> {
117 /// Creates a task-assignment instance after checking the agents against the graph.
118 ///
119 /// # Errors
120 ///
121 /// - [`InstanceError::OutOfRange`] if a start or a candidate goal is not a vertex of
122 /// `graph`;
123 /// - [`InstanceError::SharedStart`] if two agents start at the same vertex.
124 ///
125 /// Never [`InstanceError::SharedGoal`]: shared candidates are allowed, and the solver
126 /// assigns distinct goals.
127 pub fn new(graph: G, agents: Vec<TaskAgent>) -> Result<Self, InstanceError> {
128 let count = graph.vertex_count();
129 for (agent, a) in agents.iter().enumerate() {
130 if a.start >= count || a.goals.iter().any(|&goal| goal >= count) {
131 return Err(InstanceError::OutOfRange { agent });
132 }
133
134 if let Some(other) = agents[..agent].iter().position(|b| b.start == a.start) {
135 return Err(InstanceError::SharedStart(other, agent));
136 }
137 }
138
139 Ok(Self { graph, agents })
140 }
141
142 /// The graph the agents move on.
143 #[must_use]
144 pub fn graph(&self) -> &G {
145 &self.graph
146 }
147
148 /// The agents, indexed by [`AgentId`].
149 #[must_use]
150 pub fn agents(&self) -> &[TaskAgent] {
151 &self.agents
152 }
153}
154
155/// A validated instance of MAPF with unassigned agents (MAPF-UA): agents with a goal, and
156/// agents with only a start that may end anywhere but must not get in the way.
157///
158/// Starts are pairwise distinct over all agents, goals pairwise distinct, and every start
159/// and goal is a vertex of the graph. See [`focbs`](crate::focbs()).
160///
161/// # Examples
162///
163/// ```
164/// use mapf_search::{Agent, Grid, InstanceError, UaInstance};
165///
166/// let grid = Grid::new(3, 1);
167/// let assigned = vec![Agent { start: 0, goal: 2 }];
168///
169/// assert!(UaInstance::new(grid.clone(), assigned.clone(), vec![1]).is_ok());
170/// assert_eq!(
171/// UaInstance::new(grid, assigned, vec![0]).unwrap_err(),
172/// InstanceError::SharedStart(0, 1)
173/// );
174/// ```
175#[derive(Debug, Clone, PartialEq, Eq)]
176pub struct UaInstance<G> {
177 /// The graph the agents move on.
178 graph: G,
179 /// The agents with a goal.
180 assigned: Vec<Agent>,
181 /// The starts of the agents without one.
182 unassigned: Vec<Vertex>,
183}
184
185impl<G: Graph> UaInstance<G> {
186 /// Creates an instance after checking the agents against the graph. In errors, agents
187 /// are numbered with the assigned ones first: unassigned agent `j` is agent
188 /// `assigned.len() + j`.
189 ///
190 /// # Errors
191 ///
192 /// - [`InstanceError::OutOfRange`] if a start or goal is not a vertex of `graph`;
193 /// - [`InstanceError::SharedStart`] if two agents start at the same vertex;
194 /// - [`InstanceError::SharedGoal`] if two assigned agents have the same goal.
195 pub fn new(
196 graph: G,
197 assigned: Vec<Agent>,
198 unassigned: Vec<Vertex>,
199 ) -> Result<Self, InstanceError> {
200 let count = graph.vertex_count();
201 let checked = Instance::new(graph, assigned)?;
202 let Instance { graph, agents } = checked;
203 let starts: Vec<Vertex> = agents
204 .iter()
205 .map(|agent| agent.start)
206 .chain(unassigned.iter().copied())
207 .collect();
208 for (agent, &start) in starts.iter().enumerate().skip(agents.len()) {
209 if start >= count {
210 return Err(InstanceError::OutOfRange { agent });
211 }
212
213 if let Some(other) = starts[..agent].iter().position(|&s| s == start) {
214 return Err(InstanceError::SharedStart(other, agent));
215 }
216 }
217
218 Ok(Self {
219 graph,
220 assigned: agents,
221 unassigned,
222 })
223 }
224
225 /// The graph the agents move on.
226 #[must_use]
227 pub fn graph(&self) -> &G {
228 &self.graph
229 }
230
231 /// The agents with a goal.
232 #[must_use]
233 pub fn assigned(&self) -> &[Agent] {
234 &self.assigned
235 }
236
237 /// The starts of the agents without a goal.
238 #[must_use]
239 pub fn unassigned(&self) -> &[Vertex] {
240 &self.unassigned
241 }
242}
243
244/// Why [`Instance::new`], [`TaskInstance::new`] or [`UaInstance::new`] rejected an
245/// instance.
246#[derive(Debug, Clone, Copy, PartialEq, Eq)]
247pub enum InstanceError {
248 /// The start or goal of `agent` is not a vertex of the graph.
249 OutOfRange {
250 /// The offending agent.
251 agent: AgentId,
252 },
253 /// Two agents, the earlier one first, start at the same vertex.
254 SharedStart(AgentId, AgentId),
255 /// Two agents, the earlier one first, have the same goal.
256 SharedGoal(AgentId, AgentId),
257}
258
259impl fmt::Display for InstanceError {
260 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
261 match self {
262 Self::OutOfRange { agent } => {
263 write!(f, "agent {agent} starts or ends outside the graph")
264 }
265 Self::SharedStart(a, b) => write!(f, "agents {a} and {b} share a start"),
266 Self::SharedGoal(a, b) => write!(f, "agents {a} and {b} share a goal"),
267 }
268 }
269}
270
271impl core::error::Error for InstanceError {}