Skip to main content

mapf_search/
cbs.rs

1//! Conflict-based search ([`cbs`], Sharon et al. 2015): optimal for sum of costs or for
2//! makespan ([`Objective`]), with the ICBS improvements (Boyarski et al. 2015), the CG,
3//! DG and WDG heuristics (Felner et al. 2018, Li et al. 2019), disjoint splitting (Li et al.
4//! 2019) and a conflict avoidance table (Sharon et al. 2015), each switchable in
5//! [`CbsConfig`].
6//!
7//! The high level is a best-first search over a constraint tree. Each node holds
8//! constraints and one path per agent that is optimal under them; the node with the lowest
9//! objective value (plus heuristic) is expanded by splitting one of its conflicts into two
10//! children, each of which forbids the conflict to one of the two agents and replans only
11//! that agent.
12//!
13//! ```mermaid
14//! flowchart TD
15//!     root[plan every agent alone] -->|an agent has no path| unsolvable[Unsolvable]
16//!     root --> pop[pop cheapest node]
17//!     pop -->|open list empty| unsolvable
18//!     pop --> conflict{chosen conflict?}
19//!     conflict -->|none| solved[Solved]
20//!     conflict --> budget{budget exhausted?}
21//!     budget -->|yes| limit[LimitReached]
22//!     budget -->|no| split[two children: constrain one agent each, replan it]
23//!     split -->|bypass: a child is as cheap, with fewer conflicts| adopt[adopt its paths, reopen the node]
24//!     split --> push[open both children]
25//!     adopt --> pop
26//!     push --> pop
27//! ```
28
29mod cardinal;
30mod cover;
31mod heuristic;
32mod pairs;
33mod ta;
34
35use alloc::collections::{BTreeMap, BinaryHeap};
36use alloc::rc::Rc;
37use alloc::vec;
38use alloc::vec::Vec;
39use core::cell::RefCell;
40use core::cmp::{Ordering, Reverse};
41
42use heuristic_search::{Budget, Stats};
43
44use self::cardinal::{Cardinality, cardinality, forced};
45use self::heuristic::PairKey;
46pub use self::ta::{cbs_ta, cbs_ta_with};
47use crate::assignment::{Assignment, Ranked};
48use crate::conflict::{Conflict, conflicts};
49use crate::conflict_table::ConflictTable;
50use crate::constraint::{Constraint, ConstraintSet};
51use crate::graph::{Graph, Vertex};
52use crate::instance::{Agent, AgentId, Instance};
53use crate::low_level::{distance_tables, plan, plan_avoiding};
54use crate::mdd::Mdd;
55use crate::path::{Objective, Path, makespan, path_cost, sum_of_costs};
56use crate::solution::{MapfResult, Outcome, Solution};
57
58/// What [`cbs_with`] optimizes and which improvements it uses.
59///
60/// None of the improvements changes the objective value of the result; they only reduce
61/// the number of constraint-tree nodes.
62#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
63pub struct CbsConfig {
64    /// What the search minimizes.
65    pub objective: Objective,
66    /// Split cardinal conflicts first, then semi-cardinal ones, then the rest (earliest
67    /// first within a class). Needs an MDD per conflicting agent and node.
68    pub prioritize_conflicts: bool,
69    /// Bypass (Boyarski et al. 2015): when a child is as cheap for its replanned agent as
70    /// the parent and has fewer conflicts, take over its paths instead of splitting.
71    pub bypass: bool,
72    /// How a conflict is split into two children.
73    pub splitting: Splitting,
74    /// The admissible high-level heuristic added to a node's sum of costs. Admissible for
75    /// [`Objective::SumOfCosts`] only; ignored for [`Objective::Makespan`].
76    pub heuristic: CbsHeuristic,
77    /// The conflict avoidance table (Sharon et al. 2015): among an agent's cheapest paths,
78    /// the low level returns one with the fewest conflicts with the other agents' current
79    /// paths. The root plans the agents one after another, each avoiding the earlier ones.
80    ///
81    /// ```
82    /// use mapf_search::{Agent, CbsConfig, Grid, Instance, Limits, Objective, cbs_with};
83    ///
84    /// // Four agents cross a free 4x4 grid; ties among cheapest paths decide how often
85    /// // they meet.
86    /// let grid = Grid::new(4, 4);
87    /// let agents = vec![
88    ///     Agent { start: 0, goal: 15 },
89    ///     Agent { start: 3, goal: 12 },
90    ///     Agent { start: 12, goal: 3 },
91    ///     Agent { start: 15, goal: 0 },
92    /// ];
93    /// let instance = Instance::new(grid, agents)?;
94    /// let plain = CbsConfig::plain(Objective::SumOfCosts);
95    /// let avoiding = CbsConfig { conflict_avoidance: true, ..plain };
96    ///
97    /// let without = cbs_with(&instance, plain, Limits::NONE);
98    /// let with = cbs_with(&instance, avoiding, Limits::NONE);
99    /// let cost = |result: &mapf_search::MapfResult| result.solution().map(|s| s.sum_of_costs);
100    /// assert_eq!(cost(&with), cost(&without));
101    /// assert!(with.stats.expanded <= without.stats.expanded);
102    /// # Ok::<(), mapf_search::InstanceError>(())
103    /// ```
104    pub conflict_avoidance: bool,
105}
106
107impl CbsConfig {
108    /// Plain CBS: earliest conflict first, no bypass, no heuristic.
109    #[must_use]
110    pub const fn plain(objective: Objective) -> Self {
111        Self {
112            objective,
113            prioritize_conflicts: false,
114            bypass: false,
115            splitting: Splitting::Standard,
116            heuristic: CbsHeuristic::None,
117            conflict_avoidance: false,
118        }
119    }
120
121    /// Every improvement switched on; what [`cbs`] uses.
122    #[must_use]
123    pub const fn improved(objective: Objective) -> Self {
124        Self {
125            objective,
126            prioritize_conflicts: true,
127            bypass: true,
128            splitting: Splitting::Disjoint,
129            heuristic: CbsHeuristic::Dg,
130            conflict_avoidance: true,
131        }
132    }
133
134    /// Returns `true` if nodes need the MDDs of their conflicting agents.
135    fn needs_mdds(self) -> bool {
136        self.prioritize_conflicts || self.uses_heuristic()
137    }
138
139    /// The heuristic in use: [`CbsConfig::heuristic`] for sum of costs, none for makespan.
140    fn effective_heuristic(self) -> CbsHeuristic {
141        match self.objective {
142            Objective::SumOfCosts => self.heuristic,
143            Objective::Makespan => CbsHeuristic::None,
144        }
145    }
146
147    /// Returns `true` if a heuristic is on and admissible for the objective.
148    fn uses_heuristic(self) -> bool {
149        self.effective_heuristic() != CbsHeuristic::None
150    }
151}
152
153/// How CBS splits a conflict between agents `a` and `b` ([`CbsConfig::splitting`]).
154///
155/// Both keep every solution in exactly one child or in both, so both are optimal.
156///
157/// # Examples
158///
159/// ```
160/// use mapf_search::{Agent, CbsConfig, Grid, Instance, Limits, Objective, Splitting, cbs_with};
161///
162/// let grid = Grid::parse(&["@.@", "...", ".@."]);
163/// let agents = vec![
164///     Agent { start: 1, goal: 3 },
165///     Agent { start: 6, goal: 5 },
166///     Agent { start: 4, goal: 1 },
167/// ];
168/// let instance = Instance::new(grid, agents)?;
169/// let run = |splitting| {
170///     let config = CbsConfig { splitting, ..CbsConfig::improved(Objective::SumOfCosts) };
171///     cbs_with(&instance, config, Limits::expansions(100_000))
172/// };
173///
174/// let (standard, disjoint) = (run(Splitting::Standard), run(Splitting::Disjoint));
175/// assert_eq!(standard.solution().map(|s| s.sum_of_costs), Some(19));
176/// assert_eq!(disjoint.solution().map(|s| s.sum_of_costs), Some(19));
177/// assert!(disjoint.stats.expanded < standard.stats.expanded);
178/// # Ok::<(), mapf_search::InstanceError>(())
179/// ```
180#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
181pub enum Splitting {
182    /// One child forbids the conflict to `a`, the other to `b` (Sharon et al. 2015). A
183    /// solution that avoids the conflict both ways lies below both children.
184    #[default]
185    Standard,
186    /// Disjoint splitting (Li et al. 2019): one child forbids the conflict to one agent,
187    /// the other requires it of that agent with a positive constraint, which forbids it to
188    /// every other agent. The two subtrees share no solution.
189    ///
190    /// The split agent is the one for whom the conflict is forced (every cheapest path takes
191    /// part in it) if only one is and its MDD is known, else the smaller id. Forcing it keeps
192    /// its cost in the positive child and raises it in the negative one.
193    Disjoint,
194}
195
196/// An admissible estimate of how much the sum of costs of a constraint-tree node must still
197/// rise ([`CbsConfig::heuristic`]).
198///
199/// Each one needs the MDDs of the node's conflicting agents. A stronger heuristic means
200/// fewer expansions; WDG pays for that with a small search per dependent pair.
201///
202/// # Examples
203///
204/// ```
205/// use mapf_search::{Agent, CbsConfig, CbsHeuristic, Grid, Instance, Limits, Objective, cbs_with};
206///
207/// let grid = Grid::parse(&["@.@", "...", ".@."]);
208/// let agents = vec![
209///     Agent { start: 1, goal: 3 },
210///     Agent { start: 6, goal: 5 },
211///     Agent { start: 4, goal: 1 },
212/// ];
213/// let instance = Instance::new(grid, agents)?;
214/// let run = |heuristic| {
215///     let config = CbsConfig { heuristic, ..CbsConfig::improved(Objective::SumOfCosts) };
216///     cbs_with(&instance, config, Limits::expansions(100_000))
217/// };
218///
219/// let (cg, wdg) = (run(CbsHeuristic::Cg), run(CbsHeuristic::Wdg));
220/// assert_eq!(cg.solution().map(|s| s.sum_of_costs), Some(19));
221/// assert_eq!(wdg.solution().map(|s| s.sum_of_costs), Some(19));
222/// assert!(wdg.stats.expanded < cg.stats.expanded);
223/// # Ok::<(), mapf_search::InstanceError>(())
224/// ```
225#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
226pub enum CbsHeuristic {
227    /// No heuristic: nodes are ordered by their sum of costs.
228    #[default]
229    None,
230    /// CG (Felner et al. 2018): a lower bound on the minimum vertex cover of the graph of
231    /// agents with cardinal conflicts.
232    Cg,
233    /// DG (Li et al. 2019): the same over the graph of *dependent* agents, whose MDDs have
234    /// no conflict-free combination. At least CG.
235    Dg,
236    /// WDG (Li et al. 2019): the DG graph with each edge weighted by how much the pair's
237    /// sum of costs must rise, found by a small CBS over the pair (capped at 64
238    /// expansions, then a lower bound), and an edge-weighted vertex cover. At least DG.
239    Wdg,
240}
241
242/// Finds a conflict-free plan that is optimal for `objective` with conflict-based search,
243/// with every improvement of [`CbsConfig::improved`].
244///
245/// See [`cbs_with`] for the budget and the tie-breaking.
246///
247/// # Examples
248///
249/// ```
250/// use mapf_search::{Agent, Grid, Instance, Limits, Objective, cbs};
251///
252/// // Two agents cross on a plus-shaped map; one has to wait.
253/// let grid = Grid::parse(&["@.@", "...", "@.@"]);
254/// let agents = vec![
255///     Agent { start: grid.vertex(0, 1), goal: grid.vertex(2, 1) },
256///     Agent { start: grid.vertex(1, 0), goal: grid.vertex(1, 2) },
257/// ];
258/// let instance = Instance::new(grid, agents)?;
259///
260/// let result = cbs(&instance, Objective::SumOfCosts, Limits::expansions(1_000));
261/// let solution = result.solution().expect("solvable");
262/// assert_eq!(solution.sum_of_costs, 5);
263/// assert_eq!(solution.makespan, 3);
264/// # Ok::<(), mapf_search::InstanceError>(())
265/// ```
266pub fn cbs<G: Graph>(
267    instance: &Instance<G>,
268    objective: Objective,
269    budget: impl Budget<Stats>,
270) -> MapfResult {
271    cbs_with(instance, CbsConfig::improved(objective), budget)
272}
273
274/// Finds a conflict-free plan that is optimal for `config.objective` with conflict-based
275/// search and the improvements `config` selects.
276///
277/// Constraint-tree nodes are ordered by the objective (plus the heuristic, if on), then
278/// by the other objective, then by the number of conflicts. For [`Objective::Makespan`],
279/// the solution has the optimal makespan; its sum of costs is low but not guaranteed
280/// minimal among all makespan-optimal plans, because each agent's path is still the
281/// cheapest one under its constraints.
282///
283/// `budget` is asked before every constraint-tree expansion; [`MapfResult::stats`] counts
284/// expanded nodes (bypasses included) in [`Stats::expanded`] and nodes with a path (the
285/// root included) in [`Stats::generated`]. Pass [`Limits::expansions`](crate::Limits::expansions)
286/// to bound the run. The low level runs to completion on every call.
287///
288/// # Examples
289///
290/// ```
291/// use mapf_search::{Agent, CbsConfig, Grid, Instance, Limits, Objective, cbs_with};
292///
293/// let grid = Grid::parse(&["...", "@.@"]);
294/// let agents = vec![
295///     Agent { start: grid.vertex(0, 0), goal: grid.vertex(2, 0) },
296///     Agent { start: grid.vertex(2, 0), goal: grid.vertex(0, 0) },
297/// ];
298/// let instance = Instance::new(grid, agents)?;
299///
300/// let plain = cbs_with(&instance, CbsConfig::plain(Objective::Makespan), Limits::NONE);
301/// assert_eq!(plain.solution().expect("solvable").makespan, 4);
302/// # Ok::<(), mapf_search::InstanceError>(())
303/// ```
304pub fn cbs_with<G: Graph>(
305    instance: &Instance<G>,
306    config: CbsConfig,
307    mut budget: impl Budget<Stats>,
308) -> MapfResult {
309    let mut search = Search::new(instance, config);
310    let outcome = search.run(&mut budget);
311
312    MapfResult {
313        outcome,
314        stats: search.stats,
315    }
316}
317
318/// One constraint-tree node.
319#[derive(Clone)]
320struct Node {
321    /// The constraint tree the node belongs to: an index into [`Search::trees`].
322    tree: usize,
323    /// All constraints on the way from the root, on any agent.
324    constraints: Vec<Constraint>,
325    /// One path per agent, optimal under its constraints.
326    paths: Vec<Path>,
327    /// The MDD of each agent at its current cost under its constraints, where computed:
328    /// only for conflicting agents, and only if the configuration needs them. Shared with
329    /// the parent where the agent was not replanned.
330    mdds: Vec<Option<Rc<Mdd>>>,
331    /// Sum of costs of [`Node::paths`].
332    sum_of_costs: u32,
333    /// Makespan of [`Node::paths`].
334    makespan: u32,
335    /// The conflict to split next; `None` if the paths are a solution.
336    conflict: Option<Conflict>,
337    /// The number of conflicts among [`Node::paths`]; a tie-breaker.
338    conflict_count: usize,
339    /// The heuristic value ([`CbsConfig::heuristic`]); `0` if off.
340    heuristic: u32,
341}
342
343/// An open-list entry: a node and its order key.
344struct Entry {
345    /// The order key: the objective plus heuristic, the other objective, the conflict
346    /// count, then creation order. Smallest first.
347    key: (u32, u32, usize, u64),
348    /// The node.
349    node: Node,
350}
351
352impl PartialEq for Entry {
353    fn eq(&self, other: &Self) -> bool {
354        self.key == other.key
355    }
356}
357
358impl Eq for Entry {}
359
360impl PartialOrd for Entry {
361    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
362        Some(self.cmp(other))
363    }
364}
365
366impl Ord for Entry {
367    /// Reversed, so that [`BinaryHeap`] pops the smallest key.
368    fn cmp(&self, other: &Self) -> Ordering {
369        Reverse(self.key).cmp(&Reverse(other.key))
370    }
371}
372
373/// The state of one CBS run: one constraint tree, or for CBS-TA a forest of them, one per
374/// agent-to-goal assignment.
375struct Search<'a, G> {
376    /// The graph the agents move on.
377    graph: &'a G,
378    /// The start of each agent, indexed by agent.
379    starts: Vec<Vertex>,
380    /// The candidate goals, indexed by goal; an assignment picks one per agent.
381    goals: Vec<Vertex>,
382    /// Distances to each goal, indexed by goal like [`Search::goals`].
383    distances: Vec<Vec<Option<u32>>>,
384    /// The assignment of each constraint tree opened so far, indexed by
385    /// [`Node::tree`]: the goal of each agent.
386    trees: Vec<Assignment>,
387    /// CBS-TA's assignments not yet opened as trees, cheapest first; `None` for CBS,
388    /// which has its single tree from the start.
389    ranked: Option<Ranked<'a>>,
390    /// What the search minimizes and how.
391    config: CbsConfig,
392    /// The open nodes.
393    open: BinaryHeap<Entry>,
394    /// WDG's pair weights by the pair's constraints; `None` for a pair without a joint plan.
395    pair_weights: RefCell<BTreeMap<PairKey, Option<u32>>>,
396    /// Counters reported in [`MapfResult::stats`].
397    stats: Stats,
398}
399
400impl<'a, G: Graph> Search<'a, G> {
401    /// Prepares a CBS run on `instance`: one tree, agent `i` assigned goal `i`.
402    fn new(instance: &'a Instance<G>, config: CbsConfig) -> Self {
403        let agents = instance.agents();
404        let mut search = Self::forest(
405            instance.graph(),
406            agents.iter().map(|agent| agent.start).collect(),
407            agents.iter().map(|agent| agent.goal).collect(),
408            distance_tables(instance.graph(), agents),
409            None,
410            config,
411        );
412        search.trees.push((0..agents.len()).collect());
413
414        search
415    }
416
417    /// Prepares a run without trees from `starts` to `goals`, with the `distances` to each
418    /// goal. Trees come from `ranked`, or must be added to [`Search::trees`].
419    fn forest(
420        graph: &'a G,
421        starts: Vec<Vertex>,
422        goals: Vec<Vertex>,
423        distances: Vec<Vec<Option<u32>>>,
424        ranked: Option<Ranked<'a>>,
425        config: CbsConfig,
426    ) -> Self {
427        Self {
428            graph,
429            starts,
430            distances,
431            goals,
432            trees: Vec::new(),
433            ranked,
434            config,
435            open: BinaryHeap::new(),
436            pair_weights: RefCell::new(BTreeMap::new()),
437            stats: Stats::default(),
438        }
439    }
440
441    /// Runs the high-level search to its end.
442    fn run(&mut self, budget: &mut impl Budget<Stats>) -> Outcome {
443        if self.ranked.is_none() {
444            let Some(root) = self.root(0) else {
445                return Outcome::Unsolvable;
446            };
447
448            self.push(root);
449        }
450
451        self.run_open(budget)
452    }
453
454    /// Pops and expands open nodes until a solution, the budget or an empty open list,
455    /// opening CBS-TA's trees as they become due.
456    fn run_open(&mut self, budget: &mut impl Budget<Stats>) -> Outcome {
457        loop {
458            self.open_due_trees();
459            let Some(Entry { node, .. }) = self.open.pop() else {
460                break;
461            };
462
463            let Some(conflict) = node.conflict else {
464                return Outcome::Solved(Solution::new(node.paths));
465            };
466
467            if budget.exhausted(&self.stats) {
468                return Outcome::LimitReached;
469            }
470
471            self.expand(node, conflict);
472        }
473
474        Outcome::Unsolvable
475    }
476
477    /// Opens the root of every ranked assignment that is cheaper, by the objective, than
478    /// the best open node, or every one while nothing is open.
479    ///
480    /// An assignment's cost is that of its root without heuristic, a lower bound on every
481    /// node of its tree, so the trees still closed cannot hold anything better than the
482    /// node popped next. This opens no more trees than CBS-TA's rule of opening the next
483    /// one whenever a root is expanded.
484    fn open_due_trees(&mut self) {
485        while let Some(cost) = self.ranked.as_ref().and_then(Ranked::peek) {
486            if self
487                .open
488                .peek()
489                .is_some_and(|best| u64::from(best.key.0) <= cost.0)
490            {
491                return;
492            }
493
494            let assignment = self.ranked.as_mut().and_then(Ranked::next).expect("peeked");
495            self.trees.push(assignment);
496            if let Some(root) = self.root(self.trees.len() - 1) {
497                self.push(root);
498            }
499        }
500    }
501
502    /// The root node of `tree`: every agent planned without constraints, avoiding the
503    /// earlier agents' paths if [`CbsConfig::conflict_avoidance`] is on. `None` if one of
504    /// them has no path.
505    fn root(&self, tree: usize) -> Option<Node> {
506        let agents = self.starts.len();
507        let mut paths = Vec::with_capacity(agents);
508        for agent in 0..agents {
509            let path = self.replan(tree, agent, &[], &paths)?;
510            paths.push(path);
511        }
512
513        self.node(tree, Vec::new(), paths, vec![None; agents])
514    }
515
516    /// The start and the assigned goal of `agent` in `tree`.
517    fn agent(&self, tree: usize, agent: AgentId) -> Agent {
518        Agent {
519            start: self.starts[agent],
520            goal: self.goals[self.trees[tree][agent]],
521        }
522    }
523
524    /// The distances to the assigned goal of `agent` in `tree`.
525    fn distances(&self, tree: usize, agent: AgentId) -> &[Option<u32>] {
526        &self.distances[self.trees[tree][agent]]
527    }
528
529    /// Splits `conflict` of `parent`: bypasses it if a child allows, else opens the
530    /// children that have a path.
531    fn expand(&mut self, parent: Node, conflict: Conflict) {
532        self.stats.expanded += 1;
533
534        let children: Vec<Child> = self
535            .split(&parent, conflict)
536            .into_iter()
537            .filter_map(|constraint| self.child(&parent, constraint))
538            .collect();
539
540        if self.config.bypass {
541            if let Some(child) = children.iter().find(|child| is_bypass(&parent, child)) {
542                if let Some(adopted) = self.adopt(parent, child) {
543                    self.push(adopted);
544                }
545
546                return;
547            }
548        }
549
550        for child in children {
551            self.push(child.node);
552        }
553    }
554
555    /// The constraints of the two children that split `conflict` of `parent`.
556    fn split(&self, parent: &Node, conflict: Conflict) -> [Constraint; 2] {
557        match self.config.splitting {
558            Splitting::Standard => Constraint::resolving(conflict),
559            Splitting::Disjoint => Constraint::disjoint(conflict, split_side(parent, &conflict)),
560        }
561    }
562
563    /// `parent` with the paths of the agents `child` replanned, which satisfy the parent's
564    /// constraints at the same costs, so their MDDs stay valid. `None` if the heuristic
565    /// proves that the node has no solution.
566    fn adopt(&self, parent: Node, child: &Child) -> Option<Node> {
567        let mut paths = parent.paths;
568        for &agent in &child.replanned {
569            paths[agent].clone_from(&child.node.paths[agent]);
570        }
571
572        self.node(parent.tree, parent.constraints, paths, parent.mdds)
573    }
574
575    /// The child of `parent` with `constraint` added, or `None` if an agent it replans has
576    /// no path.
577    ///
578    /// A negative constraint replans its agent. A positive one keeps its agent's path,
579    /// which takes part in the conflict and so meets it, and replans every other agent whose
580    /// path breaks what it implies for them.
581    fn child(&self, parent: &Node, constraint: Constraint) -> Option<Child> {
582        let mut constraints = parent.constraints.clone();
583        constraints.push(constraint);
584
585        let replanned = affected(constraint, &parent.paths);
586        let mut paths = parent.paths.clone();
587        let mut mdds = parent.mdds.clone();
588        for &agent in &replanned {
589            paths[agent] = self.replan(parent.tree, agent, &constraints, &paths)?;
590            mdds[agent] = None;
591        }
592
593        mdds[constraint.agent()] = None;
594        let node = self.node(parent.tree, constraints, paths, mdds)?;
595
596        Some(Child { node, replanned })
597    }
598
599    /// The cheapest path of `agent` in `tree` under those of `constraints` that name it;
600    /// with [`CbsConfig::conflict_avoidance`], one with the fewest conflicts with `paths`
601    /// (indexed by agent; may be a prefix, and may include `agent`) among the cheapest.
602    fn replan(
603        &self,
604        tree: usize,
605        agent: AgentId,
606        constraints: &[Constraint],
607        paths: &[Path],
608    ) -> Option<Path> {
609        let set = ConstraintSet::for_agent(agent, constraints);
610        let (graph, distances) = (self.graph, self.distances(tree, agent));
611        let start_and_goal = self.agent(tree, agent);
612
613        if self.config.conflict_avoidance {
614            let table = ConflictTable::without(paths, agent);
615            plan_avoiding(graph, start_and_goal, &set, distances, &table)
616        } else {
617            plan(graph, start_and_goal, &set, distances)
618        }
619    }
620
621    /// A node of `tree` with `constraints`, `paths` and the known `mdds`: computes its
622    /// costs, its conflicts, the missing MDDs it needs, the conflict to split and the
623    /// heuristic. `None` if the heuristic proves that the node has no solution.
624    fn node(
625        &self,
626        tree: usize,
627        constraints: Vec<Constraint>,
628        paths: Vec<Path>,
629        mut mdds: Vec<Option<Rc<Mdd>>>,
630    ) -> Option<Node> {
631        let found = conflicts(&paths);
632        let (conflict, heuristic) = if self.config.needs_mdds() {
633            self.fill_mdds(tree, &constraints, &paths, &mut mdds, &found);
634            let classes: Vec<Cardinality> = found.iter().map(|c| cardinality(c, &mdds)).collect();
635            let heuristic = self.heuristic(tree, &constraints, &paths, &found, &classes, &mdds)?;
636            (self.choose(&found, &classes), heuristic)
637        } else {
638            (found.first().copied(), 0)
639        };
640
641        Some(Node {
642            tree,
643            sum_of_costs: sum_of_costs(&paths),
644            makespan: makespan(&paths),
645            conflict,
646            conflict_count: found.len(),
647            heuristic,
648            constraints,
649            paths,
650            mdds,
651        })
652    }
653
654    /// Builds the missing MDDs of the agents in `found`, in `tree`.
655    fn fill_mdds(
656        &self,
657        tree: usize,
658        constraints: &[Constraint],
659        paths: &[Path],
660        mdds: &mut [Option<Rc<Mdd>>],
661        found: &[Conflict],
662    ) {
663        for conflict in found {
664            let (a, b) = conflict.agents();
665            for agent in [a, b] {
666                if mdds[agent].is_some() {
667                    continue;
668                }
669
670                let set = ConstraintSet::for_agent(agent, constraints);
671                let mdd = Mdd::build(
672                    self.graph,
673                    self.agent(tree, agent),
674                    &set,
675                    self.distances(tree, agent),
676                    path_cost(&paths[agent]),
677                )
678                .expect("the agent's own path is in its MDD");
679                mdds[agent] = Some(Rc::new(mdd));
680            }
681        }
682    }
683
684    /// The conflict to split among `found`, whose cardinalities are `classes`: the earliest
685    /// of the most cardinal class if prioritizing, else the earliest.
686    fn choose(&self, found: &[Conflict], classes: &[Cardinality]) -> Option<Conflict> {
687        if !self.config.prioritize_conflicts {
688            return found.first().copied();
689        }
690
691        let best = classes.iter().max()?;
692
693        found
694            .iter()
695            .zip(classes)
696            .find(|(_, class)| *class == best)
697            .map(|(conflict, _)| *conflict)
698    }
699
700    /// Opens `node`.
701    fn push(&mut self, node: Node) {
702        let (soc, makespan) = (node.sum_of_costs, node.makespan);
703        let (first, second) = match self.config.objective {
704            Objective::SumOfCosts => (soc + node.heuristic, makespan),
705            Objective::Makespan => (makespan, soc),
706        };
707        let key = (first, second, node.conflict_count, self.stats.generated);
708
709        self.stats.generated += 1;
710        self.open.push(Entry { key, node });
711    }
712}
713
714/// A child node and the agents it replanned.
715struct Child {
716    /// The node.
717    node: Node,
718    /// The agents whose paths were replanned for the child's new constraint.
719    replanned: Vec<AgentId>,
720}
721
722/// Returns `true` if `child` may lend its replanned paths to `parent`: each costs the same
723/// as the parent's, so it is still optimal under the parent's constraints, and there are
724/// strictly fewer conflicts.
725fn is_bypass(parent: &Node, child: &Child) -> bool {
726    let same_cost = child
727        .replanned
728        .iter()
729        .all(|&agent| path_cost(&child.node.paths[agent]) == path_cost(&parent.paths[agent]));
730
731    same_cost && child.node.conflict_count < parent.conflict_count
732}
733
734/// The agents whose paths in `paths` must be replanned once `constraint` is added: its own
735/// agent for a negative constraint, every other agent whose path breaks what a positive
736/// one implies for it.
737fn affected(constraint: Constraint, paths: &[Path]) -> Vec<AgentId> {
738    if !constraint.is_positive() {
739        return Vec::from([constraint.agent()]);
740    }
741
742    (0..paths.len())
743        .filter(|&agent| agent != constraint.agent())
744        .filter(|&agent| {
745            constraint
746                .implied_for(agent)
747                .iter()
748                .any(|implied| implied.is_violated_by(&paths[agent]))
749        })
750        .collect()
751}
752
753/// Which agent of `conflict` disjoint splitting constrains: `1` (the second) if only that
754/// one is forced through the conflict by its MDD, else `0`. Without both MDDs, `0`.
755fn split_side(parent: &Node, conflict: &Conflict) -> usize {
756    let (a, b) = conflict.agents();
757    if parent.mdds[a].is_none() || parent.mdds[b].is_none() {
758        return 0;
759    }
760
761    match forced(conflict, &parent.mdds) {
762        [false, true] => 1,
763        _ => 0,
764    }
765}
766
767#[cfg(test)]
768mod tests {
769    //! Unit tests for the CBS improvements on single nodes.
770
771    use super::*;
772    use crate::graph::Grid;
773    use crate::instance::Agent;
774
775    /// An agent's start and goal cell, as `(x, y)`.
776    type Route = ((usize, usize), (usize, usize));
777
778    /// An instance on `rows` with one agent per route.
779    fn instance(rows: &[&str], agents: &[Route]) -> Instance<Grid> {
780        let grid = Grid::parse(rows);
781        let agents = agents
782            .iter()
783            .map(|&((sx, sy), (gx, gy))| Agent {
784                start: grid.vertex(sx, sy),
785                goal: grid.vertex(gx, gy),
786            })
787            .collect();
788
789        Instance::new(grid, agents).expect("valid")
790    }
791
792    /// On a plus-shaped map both agents must cross the centre at time 1: one cardinal
793    /// conflict, so the CG heuristic is 1, and the node ranks one above its cost.
794    #[test]
795    fn crossing_on_a_plus_is_cardinal() {
796        let plus = instance(
797            &["@.@", "...", "@.@"],
798            &[((0, 1), (2, 1)), ((1, 0), (1, 2))],
799        );
800        let search = Search::new(&plus, CbsConfig::improved(Objective::SumOfCosts));
801        let root = search.root(0).expect("both reach their goals");
802
803        assert_eq!(root.heuristic, 1);
804        assert_eq!(root.sum_of_costs, 4);
805
806        let plain = Search::new(&plus, CbsConfig::plain(Objective::SumOfCosts));
807        assert_eq!(plain.root(0).expect("reachable").heuristic, 0);
808    }
809
810    /// Prioritizing picks a later cardinal conflict over an earlier non-cardinal one;
811    /// without it, the earliest conflict wins.
812    #[test]
813    fn prioritizing_prefers_cardinal_conflicts() {
814        // On a free 3x2 grid (`0 1 2` over `3 4 5`): agents 0 and 1 have two ways through
815        // time 1, agents 2 and 3 must be at vertex 1 at time 1.
816        let grid = Grid::new(3, 2);
817        let mdd = |start, goal, depth| {
818            let distances = crate::graph::distances_to(&grid, goal);
819            let agent = Agent { start, goal };
820            Mdd::build(&grid, agent, &ConstraintSet::new(), &distances, depth).map(Rc::new)
821        };
822        let mdds = [mdd(0, 5, 3), mdd(2, 3, 3), mdd(4, 1, 1), mdd(0, 2, 2)];
823        let at_one = |agents| Conflict::Vertex {
824            agents,
825            vertex: 1,
826            time: 1,
827        };
828        let (wide, forced) = (at_one((0, 1)), at_one((2, 3)));
829
830        let any = instance(&["..."], &[((0, 0), (2, 0))]);
831        let improved = Search::new(&any, CbsConfig::improved(Objective::SumOfCosts));
832        let plain = Search::new(&any, CbsConfig::plain(Objective::SumOfCosts));
833
834        let found = [wide, forced];
835        let classes = found.map(|conflict| cardinality(&conflict, &mdds));
836        let heuristic = |search: &Search<'_, Grid>| {
837            let (constraints, paths) = (Vec::new(), Vec::new());
838            search.heuristic(0, &constraints, &paths, &found, &classes, &mdds)
839        };
840
841        assert_eq!(improved.choose(&found, &classes), Some(forced));
842        assert_eq!(heuristic(&improved), Some(1));
843        assert_eq!(plain.choose(&found, &classes), Some(wide));
844        assert_eq!(heuristic(&plain), Some(0));
845    }
846
847    /// Bypass: on a free 3x3 grid, two agents crossing diagonally meet at a vertex both
848    /// can avoid at no cost; the expansion takes over a child's paths instead of splitting.
849    #[test]
850    fn bypass_adopts_an_equally_cheap_child() {
851        let open = instance(
852            &["...", "...", "..."],
853            &[((0, 0), (2, 2)), ((2, 0), (0, 2))],
854        );
855        let mut config = CbsConfig::plain(Objective::SumOfCosts);
856        config.bypass = true;
857        let mut search = Search::new(&open, config);
858        let root = search.root(0).expect("reachable");
859        let conflict = root.conflict.expect("the diagonal paths meet");
860
861        search.expand(root, conflict);
862        let Entry { node, .. } = search.open.pop().expect("the adopted node");
863
864        assert!(search.open.is_empty(), "no children were opened");
865        assert!(
866            node.constraints.is_empty(),
867            "the parent keeps its constraints"
868        );
869        assert_eq!((node.sum_of_costs, node.conflict_count), (8, 0));
870    }
871}