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