Skip to main content

mapf_search/
ecbs.rs

1//! Enhanced CBS ([`ecbs`], Barer et al. 2014): bounded-suboptimal for sum of costs or
2//! makespan ([`Objective`]), with focal search at both levels.
3//!
4//! - **Low level:** each agent's path costs at most `w` times its cheapest path under its
5//!   constraints, preferring few conflicts with the other agents' current paths, including
6//!   those it causes by staying at its goal after it finished. The search also reports
7//!   `f_min`, a lower bound on that cheapest cost.
8//! - **High level:** constraint-tree nodes are ordered by their lower bound: the sum of the
9//!   agents' bounds for sum of costs, their maximum for makespan. The focal sublist is
10//!   every node whose objective value is at most `w` times the smallest lower bound,
11//!   ordered by the number of conflicting agent pairs.
12//!
13//! Every agent's path costs at most `w` times its bound, so every node's sum of costs is at
14//! most `w` times the sum of the bounds and its makespan at most `w` times their maximum.
15//! The returned solution therefore costs at most `w` times the optimum of the objective.
16//! With `w = 1` ECBS is optimal.
17
18mod low_level;
19
20use alloc::vec::Vec;
21
22use heuristic_search::{Budget, Stats, Weight};
23
24use self::low_level::{FocalPath, Problem, focal_plan};
25use crate::conflict::{Conflict, conflicts};
26use crate::conflict_table::ConflictTable;
27use crate::constraint::{Constraint, ConstraintSet};
28use crate::focal::FocalList;
29use crate::graph::Graph;
30use crate::instance::{AgentId, Instance};
31use crate::low_level::distance_tables;
32use crate::path::{Objective, Path, makespan, path_cost, sum_of_costs};
33use crate::solution::{MapfResult, Outcome, Solution};
34
35/// Finds a conflict-free plan whose `objective` value is at most `weight` times the optimum,
36/// with enhanced conflict-based search.
37///
38/// `budget` is asked before every constraint-tree expansion; [`MapfResult::stats`] counts
39/// expanded nodes in [`Stats::expanded`] and nodes with paths (the root included) in
40/// [`Stats::generated`]. Low-level searches run to completion. Like CBS, ECBS can only
41/// prove unsolvability when an agent has no path at all or the tree runs empty.
42///
43/// # Panics
44///
45/// Panics if `weight` is below `1`.
46///
47/// # Examples
48///
49/// ```
50/// use mapf_search::{Agent, Grid, Instance, Limits, Objective, Weight, ecbs, first_conflict};
51///
52/// let grid = Grid::parse(&["@.@", "...", "@.@"]);
53/// let agents = vec![
54///     Agent { start: grid.vertex(0, 1), goal: grid.vertex(2, 1) },
55///     Agent { start: grid.vertex(1, 0), goal: grid.vertex(1, 2) },
56/// ];
57/// let instance = Instance::new(grid, agents)?;
58///
59/// let budget = Limits::expansions(1_000);
60/// let result = ecbs(&instance, Objective::SumOfCosts, Weight::new(3, 2), budget);
61/// let solution = result.solution().expect("solvable");
62/// assert_eq!(first_conflict(&solution.paths), None);
63/// assert!(2 * solution.sum_of_costs <= 3 * 5, "the optimum is 5");
64/// # Ok::<(), mapf_search::InstanceError>(())
65/// ```
66pub fn ecbs<G: Graph>(
67    instance: &Instance<G>,
68    objective: Objective,
69    weight: Weight,
70    mut budget: impl Budget<Stats>,
71) -> MapfResult {
72    assert!(
73        weight.numerator() >= weight.denominator(),
74        "the suboptimality factor must be at least 1"
75    );
76
77    let mut search = Search {
78        instance,
79        objective,
80        weight,
81        distances: distance_tables(instance.graph(), instance.agents()),
82        open: FocalList::new(weight),
83        stats: Stats::default(),
84    };
85    let outcome = search.run(&mut budget);
86
87    MapfResult {
88        outcome,
89        stats: search.stats,
90    }
91}
92
93/// One constraint-tree node.
94struct Node {
95    /// All constraints on the way from the root, on any agent.
96    constraints: Vec<Constraint>,
97    /// One path per agent, within `w` of its bound under its constraints.
98    paths: Vec<Path>,
99    /// A lower bound per agent on its cheapest path under its constraints.
100    lower_bounds: Vec<u32>,
101    /// The earliest conflict among [`Node::paths`]; `None` if they are a solution.
102    conflict: Option<Conflict>,
103    /// The number of agent pairs in conflict; the focal key.
104    conflicting_pairs: usize,
105}
106
107impl Node {
108    /// A node with `constraints`, `paths` and their bounds; finds its conflicts.
109    fn new(constraints: Vec<Constraint>, paths: Vec<Path>, lower_bounds: Vec<u32>) -> Self {
110        let found = conflicts(&paths);
111        let mut pairs: Vec<(AgentId, AgentId)> = found.iter().map(Conflict::agents).collect();
112        pairs.sort_unstable();
113        pairs.dedup();
114
115        Self {
116            constraints,
117            paths,
118            lower_bounds,
119            conflict: found.first().copied(),
120            conflicting_pairs: pairs.len(),
121        }
122    }
123}
124
125/// The state of one ECBS run.
126struct Search<'a, G> {
127    /// The instance being solved.
128    instance: &'a Instance<G>,
129    /// What the search bounds.
130    objective: Objective,
131    /// The suboptimality factor of both levels.
132    weight: Weight,
133    /// Distances to each agent's goal, indexed by agent.
134    distances: Vec<Vec<Option<u32>>>,
135    /// The open nodes: lower bound as `f`, objective value as value; focal key:
136    /// conflicting pairs, then the objective value.
137    open: FocalList<(usize, u32), Node>,
138    /// Counters reported in [`MapfResult::stats`].
139    stats: Stats,
140}
141
142impl<G: Graph> Search<'_, G> {
143    /// Runs the high-level search to its end.
144    fn run(&mut self, budget: &mut impl Budget<Stats>) -> Outcome {
145        let Some(root) = self.root() else {
146            return Outcome::Unsolvable;
147        };
148
149        self.push(root);
150        while let Some((node, _)) = self.open.pop() {
151            let Some(conflict) = node.conflict else {
152                return Outcome::Solved(Solution::new(node.paths));
153            };
154
155            if budget.exhausted(&self.stats) {
156                return Outcome::LimitReached;
157            }
158
159            self.stats.expanded += 1;
160            for constraint in Constraint::resolving(conflict) {
161                if let Some(child) = self.child(&node, constraint) {
162                    self.push(child);
163                }
164            }
165        }
166
167        Outcome::Unsolvable
168    }
169
170    /// The root: agents planned one after another, each avoiding the earlier ones' paths.
171    /// `None` if one of them has no path.
172    fn root(&self) -> Option<Node> {
173        let count = self.instance.agents().len();
174        let mut paths: Vec<Path> = Vec::with_capacity(count);
175        let mut lower_bounds = Vec::with_capacity(count);
176        for agent in 0..count {
177            let found = self.replan(agent, &[], &paths)?;
178            paths.push(found.path);
179            lower_bounds.push(found.lower_bound);
180        }
181
182        Some(Node::new(Vec::new(), paths, lower_bounds))
183    }
184
185    /// The child of `parent` with `constraint` added, or `None` if the constrained agent
186    /// then has no path.
187    fn child(&self, parent: &Node, constraint: Constraint) -> Option<Node> {
188        let mut constraints = parent.constraints.clone();
189        constraints.push(constraint);
190
191        let agent = constraint.agent();
192        let found = self.replan(agent, &constraints, &parent.paths)?;
193
194        let mut paths = parent.paths.clone();
195        paths[agent] = found.path;
196        // The parent's bound stays valid under more constraints and may be the tighter one.
197        let mut lower_bounds = parent.lower_bounds.clone();
198        lower_bounds[agent] = lower_bounds[agent].max(found.lower_bound);
199
200        Some(Node::new(constraints, paths, lower_bounds))
201    }
202
203    /// A focal path of `agent` under those of `constraints` that name it, avoiding the paths
204    /// of `others` (indexed by agent; may be a prefix, and may include `agent`) where cheap.
205    fn replan(
206        &self,
207        agent: AgentId,
208        constraints: &[Constraint],
209        others: &[Path],
210    ) -> Option<FocalPath> {
211        let set = ConstraintSet::for_agent(agent, constraints);
212        let table = ConflictTable::without(others, agent);
213        let problem = Problem {
214            graph: self.instance.graph(),
215            agent: self.instance.agents()[agent],
216            constraints: &set,
217            distances: &self.distances[agent],
218            table: &table,
219        };
220
221        focal_plan(&problem, self.weight)
222    }
223
224    /// Opens `node`.
225    fn push(&mut self, node: Node) {
226        let (lower_bound, cost) = match self.objective {
227            Objective::SumOfCosts => (node.lower_bounds.iter().sum(), sum_of_costs(&node.paths)),
228            Objective::Makespan => (
229                node.lower_bounds.iter().copied().max().unwrap_or(0),
230                makespan(&node.paths),
231            ),
232        };
233        debug_assert!(
234            node.paths
235                .iter()
236                .zip(&node.lower_bounds)
237                .all(|(p, &lb)| path_cost(p) >= lb),
238            "bounds are below path costs"
239        );
240
241        self.stats.generated += 1;
242        self.open
243            .push(lower_bound, cost, (node.conflicting_pairs, cost), node);
244    }
245}