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`].
3
4use alloc::vec::Vec;
5use core::fmt;
6
7use crate::graph::{Graph, Vertex};
8
9/// Index of an agent in [`Instance::agents`].
10pub type AgentId = usize;
11
12/// One agent: where it starts and where it must end up and stay.
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
14pub struct Agent {
15    /// The vertex the agent occupies at time `0`.
16    pub start: Vertex,
17    /// The vertex the agent must reach and then occupy forever (goal-stay semantics).
18    pub goal: Vertex,
19}
20
21/// A validated MAPF instance.
22///
23/// Starts are pairwise distinct, goals are pairwise distinct, and every start and goal is a
24/// vertex of the graph.
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub struct Instance<G> {
27    /// The graph the agents move on.
28    graph: G,
29    /// The agents, indexed by [`AgentId`].
30    agents: Vec<Agent>,
31}
32
33impl<G: Graph> Instance<G> {
34    /// Creates an instance after checking the agents against the graph.
35    ///
36    /// # Errors
37    ///
38    /// - [`InstanceError::OutOfRange`] if a start or goal is not a vertex of `graph`;
39    /// - [`InstanceError::SharedStart`] if two agents start at the same vertex;
40    /// - [`InstanceError::SharedGoal`] if two agents have the same goal, which goal-stay
41    ///   semantics makes unsolvable.
42    pub fn new(graph: G, agents: Vec<Agent>) -> Result<Self, InstanceError> {
43        let count = graph.vertex_count();
44        for (agent, a) in agents.iter().enumerate() {
45            if a.start >= count || a.goal >= count {
46                return Err(InstanceError::OutOfRange { agent });
47            }
48
49            if let Some(other) = agents[..agent].iter().position(|b| b.start == a.start) {
50                return Err(InstanceError::SharedStart(other, agent));
51            }
52
53            if let Some(other) = agents[..agent].iter().position(|b| b.goal == a.goal) {
54                return Err(InstanceError::SharedGoal(other, agent));
55            }
56        }
57
58        Ok(Self { graph, agents })
59    }
60
61    /// The graph the agents move on.
62    #[must_use]
63    pub fn graph(&self) -> &G {
64        &self.graph
65    }
66
67    /// The agents, indexed by [`AgentId`].
68    #[must_use]
69    pub fn agents(&self) -> &[Agent] {
70        &self.agents
71    }
72}
73
74/// Why [`Instance::new`] rejected an instance.
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76pub enum InstanceError {
77    /// The start or goal of `agent` is not a vertex of the graph.
78    OutOfRange {
79        /// The offending agent.
80        agent: AgentId,
81    },
82    /// Two agents, the earlier one first, start at the same vertex.
83    SharedStart(AgentId, AgentId),
84    /// Two agents, the earlier one first, have the same goal.
85    SharedGoal(AgentId, AgentId),
86}
87
88impl fmt::Display for InstanceError {
89    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90        match self {
91            Self::OutOfRange { agent } => {
92                write!(f, "agent {agent} starts or ends outside the graph")
93            }
94            Self::SharedStart(a, b) => write!(f, "agents {a} and {b} share a start"),
95            Self::SharedGoal(a, b) => write!(f, "agents {a} and {b} share a goal"),
96        }
97    }
98}
99
100impl core::error::Error for InstanceError {}