use alloc::vec::Vec;
use core::fmt;
use crate::graph::{Graph, Vertex};
pub type AgentId = usize;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Agent {
pub start: Vertex,
pub goal: Vertex,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Instance<G> {
graph: G,
agents: Vec<Agent>,
}
impl<G: Graph> Instance<G> {
pub fn new(graph: G, agents: Vec<Agent>) -> Result<Self, InstanceError> {
let count = graph.vertex_count();
for (agent, a) in agents.iter().enumerate() {
if a.start >= count || a.goal >= count {
return Err(InstanceError::OutOfRange { agent });
}
if let Some(other) = agents[..agent].iter().position(|b| b.start == a.start) {
return Err(InstanceError::SharedStart(other, agent));
}
if let Some(other) = agents[..agent].iter().position(|b| b.goal == a.goal) {
return Err(InstanceError::SharedGoal(other, agent));
}
}
Ok(Self { graph, agents })
}
#[must_use]
pub fn graph(&self) -> &G {
&self.graph
}
#[must_use]
pub fn agents(&self) -> &[Agent] {
&self.agents
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct TaskAgent {
pub start: Vertex,
pub goals: Vec<Vertex>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TaskInstance<G> {
graph: G,
agents: Vec<TaskAgent>,
}
impl<G: Graph> TaskInstance<G> {
pub fn new(graph: G, agents: Vec<TaskAgent>) -> Result<Self, InstanceError> {
let count = graph.vertex_count();
for (agent, a) in agents.iter().enumerate() {
if a.start >= count || a.goals.iter().any(|&goal| goal >= count) {
return Err(InstanceError::OutOfRange { agent });
}
if let Some(other) = agents[..agent].iter().position(|b| b.start == a.start) {
return Err(InstanceError::SharedStart(other, agent));
}
}
Ok(Self { graph, agents })
}
#[must_use]
pub fn graph(&self) -> &G {
&self.graph
}
#[must_use]
pub fn agents(&self) -> &[TaskAgent] {
&self.agents
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InstanceError {
OutOfRange {
agent: AgentId,
},
SharedStart(AgentId, AgentId),
SharedGoal(AgentId, AgentId),
}
impl fmt::Display for InstanceError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::OutOfRange { agent } => {
write!(f, "agent {agent} starts or ends outside the graph")
}
Self::SharedStart(a, b) => write!(f, "agents {a} and {b} share a start"),
Self::SharedGoal(a, b) => write!(f, "agents {a} and {b} share a goal"),
}
}
}
impl core::error::Error for InstanceError {}