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