Skip to main content

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/// Why [`Instance::new`] or [`TaskInstance::new`] rejected an instance.
156#[derive(Debug, Clone, Copy, PartialEq, Eq)]
157pub enum InstanceError {
158    /// The start or goal of `agent` is not a vertex of the graph.
159    OutOfRange {
160        /// The offending agent.
161        agent: AgentId,
162    },
163    /// Two agents, the earlier one first, start at the same vertex.
164    SharedStart(AgentId, AgentId),
165    /// Two agents, the earlier one first, have the same goal.
166    SharedGoal(AgentId, AgentId),
167}
168
169impl fmt::Display for InstanceError {
170    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
171        match self {
172            Self::OutOfRange { agent } => {
173                write!(f, "agent {agent} starts or ends outside the graph")
174            }
175            Self::SharedStart(a, b) => write!(f, "agents {a} and {b} share a start"),
176            Self::SharedGoal(a, b) => write!(f, "agents {a} and {b} share a goal"),
177        }
178    }
179}
180
181impl core::error::Error for InstanceError {}