Skip to main content

mapf_search/
mstar.rs

1//! M* ([`mstar`], Wagner and Choset 2015): A* in the joint space of all agents with
2//! subdimensional expansion, optimal for sum of costs or makespan ([`Objective`]), in its
3//! basic and its recursive form, each with or without operator decomposition
4//! ([`MStarConfig`]).
5//!
6//! Each agent follows its individual optimal policy (a fixed shortest path to its goal)
7//! until it collides. Colliding agents join the *collision set* of the state where the
8//! collision was found, and that set is passed back to every predecessor. Only agents in a
9//! state's collision set leave their policy; the others keep following it. So the search
10//! stays low-dimensional where agents do not interact.
11//!
12//! - **Basic M\*** keeps one collision set per state, and its agents branch over all their
13//!   moves.
14//! - **Recursive M\* (rM\*)** keeps the collision set as disjoint groups: two collisions
15//!   that share no agent stay apart. A group that holds every agent of the search branches
16//!   over all moves, as in basic M\*. A smaller group moves along its own optimal joint
17//!   path, which a separate M\* search over just that group computes, recursively, and
18//!   caches. Only when a group's path collides with another agent do the two merge. So
19//!   two pairs of interacting agents far apart cost two small searches, not one over all
20//!   four.
21//! - **Operator decomposition** (`OD-M*` and `ODrM*`, Ferner, Wagner and Choset 2013): where
22//!   agents would branch over all combinations of their moves, they move one at a time
23//!   instead, through intermediate states that have their own collision sets. An agent
24//!   branches at an intermediate state only once a collision put it into that state's set.
25//!
26//! Goal-stay pricing, the same as an exact joint search: a joint state is every agent's
27//! vertex plus a *finished* flag. An unfinished agent at its goal may finish; from then on
28//! it stays there for free. Every other unfinished agent pays 1 per step, move or wait. So
29//! waiting at the goal before leaving it again is paid for. The heuristic, the sum of the
30//! unfinished agents' distances to their goals, is consistent.
31//!
32//! **Makespan** is solved through sum of costs under a deadline. The sum-of-costs plan's
33//! makespan `U` bounds the optimum from above, the largest individual distance `L` from
34//! below. For each deadline `M` from `L` up to `U - 1`, a sum-of-costs search over states
35//! that carry their time, pruning every state from which an unfinished agent cannot reach
36//! its goal by `M`, either finds a plan (whose makespan is then optimal) or proves there is
37//! none; if none succeeds, the sum-of-costs plan is optimal. So the plan returned for
38//! makespan also has the least sum of costs among the makespan-optimal plans. (Pricing a
39//! joint step at 1 whenever any agent pays, as the oracle does, is also exact but leaves
40//! the search wide plateaus of equal `f`; it took 83 s on the benchmark instance.)
41//!
42//! ```mermaid
43//! flowchart TD
44//!     pop[pop the state with the lowest f] -->|all agents finished| solved[Solved]
45//!     pop -->|open list empty| unsolvable[Unsolvable]
46//!     pop --> succ[successors: a group of all agents branches, a smaller group follows its own optimal path, the rest follow their policy]
47//!     succ -.->|rM*: a smaller group's path is not cached| sub[M* over that group alone]
48//!     sub -.-> succ
49//!     succ -->|transition collides| back[merge the colliders into the collision set, pass it back to predecessors, reopen them]
50//!     succ -->|collision-free| relax[record predecessor, pass back its collision set, relax g]
51//!     back --> pop
52//!     relax --> pop
53//! ```
54
55mod collision;
56mod context;
57mod planner;
58mod state;
59
60use alloc::collections::BTreeMap;
61use alloc::vec::Vec;
62
63use heuristic_search::{Budget, Stats};
64
65use self::context::{Context, LimitReached};
66use self::planner::Planner;
67use self::state::Key;
68use crate::graph::{Graph, Vertex};
69use crate::instance::Instance;
70use crate::low_level::{distance_tables, makespan_lower_bound};
71use crate::path::{Objective, Path, Time, trim_trailing_waits};
72use crate::solution::{MapfResult, Outcome, Solution, makespan_by_deadlines};
73
74/// What [`mstar_with`] optimizes and which form of M* it runs.
75///
76/// Every form returns a plan with the optimal value of the objective; they differ in
77/// speed.
78#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
79pub struct MStarConfig {
80    /// What the search minimizes.
81    pub objective: Objective,
82    /// Recursive M*: plan disjoint collision groups as separate subproblems. `false` runs
83    /// basic M*, with one collision set per state.
84    pub recursive: bool,
85    /// Operator decomposition (OD-M*, Ferner, Wagner and Choset 2013): where agents branch,
86    /// move them one at a time through intermediate states with their own collision sets,
87    /// instead of generating every combination of their moves at once.
88    pub operator_decomposition: bool,
89}
90
91impl MStarConfig {
92    /// Basic M*: one collision set per state.
93    #[must_use]
94    pub const fn basic(objective: Objective) -> Self {
95        Self {
96            objective,
97            recursive: false,
98            operator_decomposition: false,
99        }
100    }
101
102    /// Recursive M* (rM*).
103    #[must_use]
104    pub const fn recursive(objective: Objective) -> Self {
105        Self {
106            objective,
107            recursive: true,
108            operator_decomposition: false,
109        }
110    }
111
112    /// Recursive M* with operator decomposition (`ODrM*`); what [`mstar`] and
113    /// [`MStarConfig::default`] use. Often much faster than rM* on tightly coupled groups,
114    /// but not always: see `docs/design.md`.
115    #[must_use]
116    pub const fn od_recursive(objective: Objective) -> Self {
117        Self {
118            objective,
119            recursive: true,
120            operator_decomposition: true,
121        }
122    }
123}
124
125impl Default for MStarConfig {
126    /// [`MStarConfig::od_recursive`] for [`Objective::SumOfCosts`].
127    fn default() -> Self {
128        Self::od_recursive(Objective::SumOfCosts)
129    }
130}
131
132/// Finds a conflict-free plan with the optimal `objective` value with recursive M* and
133/// operator decomposition ([`MStarConfig::od_recursive`]).
134///
135/// See [`mstar_with`] for the budget and what is counted.
136///
137/// # Examples
138///
139/// ```
140/// use mapf_search::{Agent, Grid, Instance, Limits, MStarConfig, Objective, Outcome, mstar};
141///
142/// // Two agents swap the ends of a corridor with one side pocket.
143/// let grid = Grid::parse(&["...", "@.@"]);
144/// let agents = vec![
145///     Agent { start: grid.vertex(0, 0), goal: grid.vertex(2, 0) },
146///     Agent { start: grid.vertex(2, 0), goal: grid.vertex(0, 0) },
147/// ];
148/// let instance = Instance::new(grid.clone(), agents)?;
149/// let result = mstar(&instance, Objective::SumOfCosts, Limits::NONE);
150/// assert_eq!(MStarConfig::default(), MStarConfig::od_recursive(Objective::SumOfCosts));
151/// assert_eq!(result.solution().expect("solvable").sum_of_costs, 7);
152///
153/// // Without the pocket they cannot pass, and M* proves it.
154/// let corridor = mapf_search::Grid::parse(&["..."]);
155/// let agents = vec![Agent { start: 0, goal: 2 }, Agent { start: 2, goal: 0 }];
156/// let instance = Instance::new(corridor, agents)?;
157/// let result = mstar(&instance, Objective::Makespan, Limits::NONE);
158/// assert_eq!(result.outcome, Outcome::Unsolvable);
159/// # Ok::<(), mapf_search::InstanceError>(())
160/// ```
161pub fn mstar<G: Graph>(
162    instance: &Instance<G>,
163    objective: Objective,
164    budget: impl Budget<Stats>,
165) -> MapfResult {
166    mstar_with(instance, MStarConfig::od_recursive(objective), budget)
167}
168
169/// Finds a conflict-free plan with the optimal `config.objective` value with the form of M*
170/// that `config` selects.
171///
172/// The joint space is finite, so M* proves unsolvability by exhausting it
173/// ([`Outcome::Unsolvable`]), also where CBS and ICTS only stop at their budget, such as
174/// two agents swapping the ends of a corridor. `budget` is asked before every expansion, in
175/// the top-level search and in every subgroup search of recursive M*;
176/// [`MapfResult::stats`] counts expansions (re-expansions included) in
177/// [`Stats::expanded`], generated joint states in [`Stats::generated`] and expansions after
178/// a collision set grew in [`Stats::reopened`], all summed over every search.
179///
180/// For [`Objective::Makespan`] the plan has the optimal makespan and, among such plans, the
181/// least sum of costs; the counters sum over the searches of the module docs. On the
182/// benchmark's 8-agent instance recursive M* takes about 30-60 ms for either objective.
183///
184/// # Examples
185///
186/// ```
187/// use mapf_search::{Agent, Grid, Instance, Limits, MStarConfig, Objective, mstar_with};
188///
189/// // Two pairs of agents swap places in two rooms, one sooner than the other.
190/// let grid = Grid::parse(&["...@.....", "@.@@@@@.@"]);
191/// let at = |x, y| grid.vertex(x, y);
192/// let agents = vec![
193///     Agent { start: at(0, 0), goal: at(2, 0) },
194///     Agent { start: at(2, 0), goal: at(0, 0) },
195///     Agent { start: at(4, 0), goal: at(8, 0) },
196///     Agent { start: at(8, 0), goal: at(4, 0) },
197/// ];
198/// let instance = Instance::new(grid, agents)?;
199///
200/// let soc = Objective::SumOfCosts;
201/// let basic = mstar_with(&instance, MStarConfig::basic(soc), Limits::NONE);
202/// let recursive = mstar_with(&instance, MStarConfig::recursive(soc), Limits::NONE);
203/// let cost = |result: &mapf_search::MapfResult| result.solution().map(|s| s.sum_of_costs);
204/// assert_eq!(cost(&basic), Some(18));
205/// assert_eq!(cost(&recursive), Some(18));
206/// assert!(recursive.stats.expanded < basic.stats.expanded);
207/// # Ok::<(), mapf_search::InstanceError>(())
208/// ```
209pub fn mstar_with<G: Graph>(
210    instance: &Instance<G>,
211    config: MStarConfig,
212    mut budget: impl Budget<Stats>,
213) -> MapfResult {
214    let distances = distance_tables(instance.graph(), instance.agents());
215    let policy = policies(instance.graph(), &distances);
216    let mut run = Run {
217        instance,
218        config,
219        distances,
220        policy,
221        stats: Stats::default(),
222    };
223
224    let outcome = match config.objective {
225        Objective::SumOfCosts => run.search(None, &mut budget),
226        Objective::Makespan => {
227            let lower_bound = makespan_lower_bound(instance.agents(), &run.distances);
228            makespan_by_deadlines(lower_bound, |deadline| run.search(deadline, &mut budget))
229        }
230    };
231
232    MapfResult {
233        outcome,
234        stats: run.stats,
235    }
236}
237
238/// One [`mstar_with`] call: what its searches share, and the counters over all of them.
239struct Run<'a, G> {
240    /// The instance being solved.
241    instance: &'a Instance<G>,
242    /// The form of M*.
243    config: MStarConfig,
244    /// Distances to each agent's goal, indexed by agent.
245    distances: Vec<Vec<Option<u32>>>,
246    /// Each agent's individual optimal policy ([`policies`]).
247    policy: Vec<Vec<Option<Vertex>>>,
248    /// Counters over every search so far.
249    stats: Stats,
250}
251
252impl<G: Graph> Run<'_, G> {
253    /// One search for the plan with the optimal sum of costs among those in which every
254    /// agent finishes by `deadline` (any time if `None`).
255    fn search(&mut self, deadline: Option<Time>, budget: &mut impl Budget<Stats>) -> Outcome {
256        let mut cx = Context {
257            instance: self.instance,
258            recursive: self.config.recursive,
259            decompose: self.config.operator_decomposition,
260            deadline,
261            distances: &self.distances,
262            policy: &self.policy,
263            planners: BTreeMap::new(),
264            stats: self.stats,
265        };
266        let agents = self.instance.agents();
267        let start = Key::standard(0, agents.iter().map(|a| (a.start, false)).collect());
268        let mut planner = Planner::new((0..agents.len()).collect());
269
270        let outcome = match planner.search(&mut cx, start, budget) {
271            Ok(Some(states)) => Outcome::Solved(Solution::new(paths(&states))),
272            Ok(None) => Outcome::Unsolvable,
273            Err(LimitReached) => Outcome::LimitReached,
274        };
275        self.stats = cx.stats;
276
277        outcome
278    }
279}
280
281/// Each agent's path along the standard `states`, trimmed of trailing waits.
282fn paths(states: &[Key]) -> Vec<Path> {
283    let agents = states.first().map_or(0, |state| state.base.len());
284
285    (0..agents)
286        .map(|agent| {
287            let mut path: Path = states.iter().map(|state| state.base[agent].0).collect();
288            trim_trailing_waits(&mut path);
289
290            path
291        })
292        .collect()
293}
294
295/// Each agent's individual optimal policy: from every vertex, the smallest-numbered
296/// neighbour one step closer to its goal.
297fn policies<G: Graph>(graph: &G, distances: &[Vec<Option<u32>>]) -> Vec<Vec<Option<Vertex>>> {
298    distances
299        .iter()
300        .map(|distances| {
301            (0..graph.vertex_count())
302                .map(|vertex| {
303                    let closer = distances[vertex]?.checked_sub(1)?;
304                    let mut best = None;
305                    graph.neighbors(vertex, |next| {
306                        if distances[next] == Some(closer) {
307                            best = Some(best.map_or(next, |b: Vertex| b.min(next)));
308                        }
309                    });
310
311                    best
312                })
313                .collect()
314        })
315        .collect()
316}