Skip to main content

mapf_search/
solution.rs

1//! What every solver returns: a [`Solution`], how the run ended ([`Outcome`]) and its
2//! counters ([`MapfResult`]).
3
4use alloc::vec::Vec;
5
6use heuristic_search::Stats;
7
8use crate::path::{Objective, Path, makespan, sum_of_costs};
9
10/// A conflict-free plan: one path per agent.
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub struct Solution {
13    /// The path of each agent, indexed by [`AgentId`](crate::AgentId). Each starts at the
14    /// agent's start and ends at its goal, where the agent stays.
15    pub paths: Vec<Path>,
16    /// The sum of costs of [`Solution::paths`] (see [`sum_of_costs`]).
17    pub sum_of_costs: u32,
18    /// The makespan of [`Solution::paths`] (see [`makespan`](crate::makespan())).
19    pub makespan: u32,
20}
21
22impl Solution {
23    /// A solution of `paths`, with both objectives computed.
24    pub(crate) fn new(paths: Vec<Path>) -> Self {
25        Self {
26            sum_of_costs: sum_of_costs(&paths),
27            makespan: makespan(&paths),
28            paths,
29        }
30    }
31
32    /// The value of `objective` for this solution.
33    #[must_use]
34    pub fn cost(&self, objective: Objective) -> u32 {
35        match objective {
36            Objective::SumOfCosts => self.sum_of_costs,
37            Objective::Makespan => self.makespan,
38        }
39    }
40}
41
42/// How a solver run ended.
43#[derive(Debug, Clone, PartialEq, Eq)]
44pub enum Outcome {
45    /// A conflict-free solution. Its quality is what the solver guarantees: optimal for
46    /// CBS, ICTS and M*, within the suboptimality factor for ECBS, none for PBS.
47    Solved(Solution),
48    /// Proven unsolvable: an agent cannot reach its goal even alone, or a complete solver
49    /// ran out of options.
50    Unsolvable,
51    /// The [`Budget`](crate::Budget) stopped the search. The instance may be unsolvable:
52    /// for some unsolvable instances, such as two agents swapping the ends of a corridor,
53    /// the search space is infinite and complete solvers only ever stop this way.
54    LimitReached,
55    /// An incomplete solver ([`pbs`](crate::pbs())) ran out of options before its budget.
56    /// This proves nothing: the instance may still be solvable.
57    Exhausted,
58}
59
60/// The result of a solver run.
61#[derive(Debug, Clone, PartialEq, Eq)]
62pub struct MapfResult {
63    /// How the run ended.
64    pub outcome: Outcome,
65    /// High-level counters; each solver documents what it counts.
66    pub stats: Stats,
67}
68
69impl MapfResult {
70    /// The solution, if one was found.
71    #[must_use]
72    pub fn solution(&self) -> Option<&Solution> {
73        match &self.outcome {
74            Outcome::Solved(solution) => Some(solution),
75            Outcome::Unsolvable | Outcome::LimitReached | Outcome::Exhausted => None,
76        }
77    }
78}