mapf_search/mo_cbs.rs
1//! Multi-objective conflict-based search ([`mo_cbs`], Ren, Rathinam and Choset 2021,
2//! arXiv:2101.03805): every cost-unique Pareto-optimal joint plan when each move and wait
3//! costs a vector of `N` objectives.
4//!
5//! MO-CBS generalizes [`cbs`](crate::cbs()). The low level ([`low_level`]) returns all
6//! cost-unique Pareto-optimal paths of one agent under its constraints, not one cheapest
7//! path. The roots are every combination of the agents' unconstrained Pareto-optimal paths,
8//! so the constraint tree becomes a forest. The high level pops nodes in lexicographic cost
9//! order, which pops a node that no other open node dominates, and keeps the set `C` of
10//! solution costs found so far. A node whose cost some element of `C` weakly dominates is
11//! filtered. A conflict-free node adds its cost to `C`, which then drops what the new cost
12//! dominates. The search ends only when the open list is empty; `C` is then the
13//! Pareto-optimal front.
14//!
15//! ```mermaid
16//! flowchart TD
17//! check{feasibility check proves no plan?} -->|yes| unsolvable[Unsolvable]
18//! check -->|no, or off| init[Pareto paths of every agent alone]
19//! init -->|an agent has none| unsolvable
20//! init --> roots[root nodes: all combinations, or one tree at a time]
21//! roots --> pop[pop the lexicographically cheapest node]
22//! pop -->|open list empty, next tree| roots
23//! pop -->|weakly dominated by a solution| pop
24//! pop --> conflict{chosen conflict?}
25//! conflict -->|none| record[add to the front, drop what it dominates]
26//! record --> pop
27//! conflict --> budget{budget exhausted?}
28//! budget -->|yes| limit[LimitReached]
29//! budget -->|no| split[two constraints; one child per combination of Pareto paths]
30//! split -->|bypass: same costs, fewer conflicts| pop
31//! split --> pop
32//! pop -->|all trees done| complete[Complete]
33//! ```
34//!
35//! The paper's variants map onto [`MoCbsConfig`]: [`MoCbsConfig::tree_by_tree`] is the
36//! `-t` variant, and [`LowLevel`] picks BOA*-st (`-b`, two objectives) or NAMOA*dr-st
37//! (`-n`, any number). [`MoCbsConfig::improved`] adds the paper's feasibility check and,
38//! beyond the paper, ICBS-style conflict prioritization, bypass and disjoint splitting
39//! ([`split`]); none of them changes the front.
40//!
41//! Costs follow goal-stay, as everywhere in the crate: an agent pays for every move and
42//! wait until its final arrival at its goal and nothing afterwards. With one objective and
43//! unit costs, the front is the single optimal sum of costs.
44
45mod low_level;
46mod node;
47mod split;
48
49use alloc::collections::BTreeMap;
50use alloc::rc::Rc;
51use alloc::vec::Vec;
52use core::cell::RefCell;
53
54use heuristic_search::{Budget, Stats};
55use multiobjective_search::{Dominates, weakly_dominates};
56
57use self::low_level::{Heuristic, Problem, pareto_paths};
58use self::node::{Combinations, Node, ParetoSet};
59use crate::cbs::Splitting;
60use crate::conflict::Conflict;
61use crate::constraint::{Constraint, ConstraintSet};
62use crate::graph::{Graph, Vertex};
63use crate::instance::{AgentId, Instance};
64use crate::mstar::{MStarConfig, mstar_with};
65use crate::path::{Objective, Path};
66use crate::solution::Outcome;
67
68/// Which multi-objective search the low level runs.
69#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
70pub enum LowLevel {
71 /// BOA*-st for two objectives (the paper's MO-CBS-b), NAMOA*dr-st otherwise.
72 #[default]
73 Auto,
74 /// NAMOA*dr-st for any number of objectives (the paper's MO-CBS-n).
75 NamoaDr,
76}
77
78/// How [`mo_cbs_with`] orders the high-level search, which low level it uses and which
79/// improvements it applies.
80///
81/// Every configuration returns the same front; they differ in effort. The default is
82/// [`MoCbsConfig::improved`], what [`mo_cbs`] uses.
83///
84/// ```
85/// use mapf_search::{Agent, Grid, Instance, Limits, MoCbsConfig, ParetoOutcome, mo_cbs_with};
86///
87/// // Two agents swap the ends of a corridor: no plan exists.
88/// let grid = Grid::new(3, 1);
89/// let agents = vec![Agent { start: 0, goal: 2 }, Agent { start: 2, goal: 0 }];
90/// let instance = Instance::new(grid, agents)?;
91/// let costs = |_: usize, _: usize| [1, 1];
92///
93/// // The paper's MO-CBS only stops at its budget; the feasibility check proves it.
94/// let plain = mo_cbs_with(&instance, &costs, MoCbsConfig::plain(), Limits::expansions(100));
95/// let improved = mo_cbs_with(&instance, &costs, MoCbsConfig::improved(), Limits::NONE);
96///
97/// assert_eq!(plain.outcome, ParetoOutcome::LimitReached);
98/// assert_eq!(improved.outcome, ParetoOutcome::Unsolvable);
99/// # Ok::<(), mapf_search::InstanceError>(())
100/// ```
101#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
102#[expect(
103 clippy::struct_excessive_bools,
104 reason = "independent on-off switches, each documented, as in CbsConfig"
105)]
106pub struct MoCbsConfig {
107 /// Tree-by-tree expansion (MO-CBS-t): generate one root at a time and exhaust its tree
108 /// before the next. Plain MO-CBS generates every root up front, which is the product
109 /// of the agents' Pareto set sizes, and expands across all trees.
110 pub tree_by_tree: bool,
111 /// The single-agent multi-objective planner.
112 pub low_level: LowLevel,
113 /// Before the search, prove infeasible instances [`ParetoOutcome::Unsolvable`] (paper,
114 /// Sec. VII-B): feasibility does not depend on the costs, so recursive M* with unit
115 /// costs decides it, under the same budget with M*'s counters. If that budget runs out,
116 /// the search goes on without the proof.
117 pub feasibility_check: bool,
118 /// Split cardinal conflicts first, then semi-cardinal ones, then the rest (earliest
119 /// first within a class). A conflict is cardinal for an agent if every path of the
120 /// agent's current Pareto set takes part in it.
121 pub prioritize_conflicts: bool,
122 /// Bypass: when a child's replanned agents each have a path of the parent's cost that
123 /// leaves fewer conflicts, take those paths over instead of splitting.
124 pub bypass: bool,
125 /// How a conflict is split into children. [`Splitting::Disjoint`] constrains the agent
126 /// for which the conflict is cardinal if only one is, else the conflict's first agent.
127 pub splitting: Splitting,
128}
129
130impl MoCbsConfig {
131 /// Plain MO-CBS, Alg. 1 of the paper: all roots up front, BOA* for two objectives, no
132 /// improvements.
133 #[must_use]
134 pub const fn plain() -> Self {
135 Self {
136 tree_by_tree: false,
137 low_level: LowLevel::Auto,
138 feasibility_check: false,
139 prioritize_conflicts: false,
140 bypass: false,
141 splitting: Splitting::Standard,
142 }
143 }
144
145 /// MO-CBS-t, as in the paper: one tree at a time, BOA* for two objectives, no
146 /// improvements.
147 #[must_use]
148 pub const fn tree_by_tree() -> Self {
149 Self {
150 tree_by_tree: true,
151 ..Self::plain()
152 }
153 }
154
155 /// MO-CBS-t with the feasibility check, conflict prioritization, bypass and disjoint
156 /// splitting. What [`mo_cbs`] uses.
157 #[must_use]
158 pub const fn improved() -> Self {
159 Self {
160 tree_by_tree: true,
161 low_level: LowLevel::Auto,
162 feasibility_check: true,
163 prioritize_conflicts: true,
164 bypass: true,
165 splitting: Splitting::Disjoint,
166 }
167 }
168}
169
170impl Default for MoCbsConfig {
171 fn default() -> Self {
172 Self::improved()
173 }
174}
175
176/// One Pareto-optimal joint plan.
177#[derive(Debug, Clone, PartialEq, Eq)]
178pub struct ParetoSolution<const N: usize> {
179 /// The conflict-free path of each agent, indexed by [`AgentId`], from its start to its
180 /// goal, where it stays.
181 pub paths: Vec<Path>,
182 /// The sum over agents of the cost vectors of their moves and waits up to their final
183 /// arrival.
184 pub cost: [u32; N],
185}
186
187/// How an [`mo_cbs`] run ended.
188#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
189pub enum ParetoOutcome {
190 /// The front is the complete Pareto-optimal front: one plan per Pareto-optimal cost
191 /// vector.
192 Complete,
193 /// Proven unsolvable: by the feasibility check, because an agent cannot reach its goal
194 /// even alone, or because the search ran out of nodes without a solution.
195 Unsolvable,
196 /// The [`Budget`] stopped the search. The front holds the conflict-free plans found so
197 /// far, mutually non-dominated, but a later plan might have dominated some of them, and
198 /// cost vectors may be missing. Without the feasibility check, some unsolvable instances
199 /// only ever end this way.
200 LimitReached,
201}
202
203/// The result of an [`mo_cbs`] run.
204#[derive(Debug, Clone, PartialEq, Eq)]
205pub struct ParetoResult<const N: usize> {
206 /// How the run ended.
207 pub outcome: ParetoOutcome,
208 /// The plans found, sorted lexicographically by cost, at most one per cost vector.
209 /// Empty unless a solution was found.
210 pub front: Vec<ParetoSolution<N>>,
211 /// High-level counters: expanded (split) nodes, bypasses included, in
212 /// [`Stats::expanded`], and created nodes (roots and children, filtered or not) in
213 /// [`Stats::generated`]. The feasibility check's counters are not included.
214 pub stats: Stats,
215}
216
217/// [`mo_cbs_with`] with [`MoCbsConfig::improved`]: every Pareto-optimal plan of
218/// `instance`.
219///
220/// `costs(from, to)` is the cost vector of a move along the edge `from -> to`, and
221/// `costs(v, v)` the cost of waiting at `v`. See [`mo_cbs_with`] for the requirements.
222///
223/// # Examples
224///
225/// ```
226/// use mapf_search::{Agent, Grid, Instance, Limits, ParetoOutcome, first_conflict, mo_cbs};
227///
228/// // Time and risk: every step takes 1 time unit; entering the middle row is risky.
229/// let grid = Grid::new(3, 3);
230/// let risk = |to: usize| if grid.cell(to).1 == 1 { 5 } else { 1 };
231/// let costs = |_from: usize, to: usize| [1, risk(to)];
232/// let agents = vec![Agent { start: grid.vertex(0, 1), goal: grid.vertex(2, 1) }];
233/// let instance = Instance::new(grid.clone(), agents)?;
234///
235/// let result = mo_cbs(&instance, &costs, Limits::expansions(1_000));
236///
237/// assert_eq!(result.outcome, ParetoOutcome::Complete);
238/// let costs: Vec<_> = result.front.iter().map(|plan| plan.cost).collect();
239/// assert_eq!(costs, [[2, 10], [4, 8]]); // straight through, or around the risky row
240/// assert!(result.front.iter().all(|plan| first_conflict(&plan.paths).is_none()));
241/// # Ok::<(), mapf_search::InstanceError>(())
242/// ```
243pub fn mo_cbs<G: Graph, const N: usize>(
244 instance: &Instance<G>,
245 costs: &impl Fn(Vertex, Vertex) -> [u32; N],
246 budget: impl Budget<Stats>,
247) -> ParetoResult<N> {
248 mo_cbs_with(instance, costs, MoCbsConfig::improved(), budget)
249}
250
251/// Multi-objective CBS: every cost-unique Pareto-optimal plan of `instance` under the
252/// vector costs `costs`, shared by all agents (see [`mo_cbs`]), searched as `config` says.
253///
254/// Every cost component should be positive, waits included, as the paper requires: the
255/// search then terminates on every solvable instance. With zero components a returned
256/// [`ParetoOutcome::Complete`] front is still exact, but the search may not end on its
257/// own. Sums must fit in `u32`.
258///
259/// `budget` is asked before every high-level expansion, before every root of plain
260/// MO-CBS, and inside the low level, before its first expansion and every 256 after; a
261/// stop there ends the run with [`ParetoOutcome::LimitReached`]. The low level sees the
262/// counters of the completed high-level expansions, so a [`Limits`](crate::Limits) budget
263/// never stops it early, and `Limits::expansions(n)` lets a run of `n` expansions
264/// complete, while a deadline or a cancellation flag in a closure stops it at once. With
265/// [`MoCbsConfig::feasibility_check`], the check gets the budget first, with M*'s
266/// counters.
267///
268/// # Examples
269///
270/// ```
271/// use mapf_search::{Agent, Grid, Instance, Limits, MoCbsConfig, cbs, mo_cbs_with, Objective};
272///
273/// // With one objective and unit costs MO-CBS is CBS.
274/// let grid = Grid::parse(&["...", "@.@"]);
275/// let agents = vec![
276/// Agent { start: grid.vertex(0, 0), goal: grid.vertex(2, 0) },
277/// Agent { start: grid.vertex(2, 0), goal: grid.vertex(0, 0) },
278/// ];
279/// let instance = Instance::new(grid, agents)?;
280///
281/// let unit = |_: usize, _: usize| [1];
282/// let front = mo_cbs_with(&instance, &unit, MoCbsConfig::plain(), Limits::NONE).front;
283/// let optimum = cbs(&instance, Objective::SumOfCosts, Limits::NONE);
284///
285/// assert_eq!(front.len(), 1);
286/// assert_eq!(front[0].cost, [optimum.solution().expect("solvable").sum_of_costs]);
287/// # Ok::<(), mapf_search::InstanceError>(())
288/// ```
289pub fn mo_cbs_with<G: Graph, const N: usize>(
290 instance: &Instance<G>,
291 costs: &impl Fn(Vertex, Vertex) -> [u32; N],
292 config: MoCbsConfig,
293 budget: impl Budget<Stats>,
294) -> ParetoResult<N> {
295 mo_cbs_per_agent(instance, &|_, from, to| costs(from, to), config, budget)
296}
297
298/// [`mo_cbs_with`] with one cost function per agent: `costs(agent, from, to)` is what the
299/// move (or, if `from == to`, the wait) costs `agent`.
300///
301/// # Examples
302///
303/// ```
304/// use mapf_search::{AdjacencyList, Agent, Instance, Limits, MoCbsConfig, mo_cbs_per_agent};
305///
306/// // A diamond with an upper and a lower route: agent 0 finds the upper one cheap, any
307/// // other agent the lower one.
308/// let graph = AdjacencyList::undirected(4, &[(0, 1), (1, 3), (0, 2), (2, 3)]);
309/// let agents = vec![Agent { start: 0, goal: 3 }];
310/// let instance = Instance::new(graph, agents)?;
311/// let costs = |agent: usize, from: usize, to: usize| {
312/// let upper = from == 1 || to == 1;
313/// if upper == (agent == 0) { [1, 1] } else { [2, 2] }
314/// };
315///
316/// let result = mo_cbs_per_agent(&instance, &costs, MoCbsConfig::improved(), Limits::NONE);
317/// assert_eq!(result.front[0].paths[0], [0, 1, 3]);
318/// assert_eq!(result.front[0].cost, [2, 2]);
319/// # Ok::<(), mapf_search::InstanceError>(())
320/// ```
321pub fn mo_cbs_per_agent<G: Graph, const N: usize>(
322 instance: &Instance<G>,
323 costs: &impl Fn(AgentId, Vertex, Vertex) -> [u32; N],
324 config: MoCbsConfig,
325 mut budget: impl Budget<Stats>,
326) -> ParetoResult<N> {
327 let mut search = Search::new(instance, costs, config, &mut budget);
328 let outcome = search.run();
329 let mut front = search.front;
330 front.sort_by_key(|plan| plan.cost);
331
332 ParetoResult {
333 outcome,
334 front,
335 stats: search.stats,
336 }
337}
338
339/// The low level was interrupted by the budget.
340struct Interrupted;
341
342/// A child of a split, before its nodes are built: its constraints and the new Pareto set
343/// of each agent it replans.
344struct Child<const N: usize> {
345 /// The parent's constraints plus the new one.
346 constraints: Vec<Constraint>,
347 /// The replanned agents with their Pareto sets under [`Child::constraints`]; none
348 /// empty.
349 replanned: Vec<(AgentId, ParetoSet<N>)>,
350}
351
352/// The state of one MO-CBS run.
353struct Search<'a, G, F, const N: usize> {
354 /// The instance being solved.
355 instance: &'a Instance<G>,
356 /// The cost vector of each move and wait, per agent.
357 costs: &'a F,
358 /// Expansion order, low level and improvements.
359 config: MoCbsConfig,
360 /// The low-level heuristic of each agent.
361 heuristics: Vec<Heuristic<N>>,
362 /// The caller's budget, shared with the low level's interrupt hook.
363 budget: RefCell<&'a mut dyn Budget<Stats>>,
364 /// The open nodes by cost, then creation order: lexicographically smallest first.
365 open: BTreeMap<([u32; N], u64), Node<N>>,
366 /// The solutions found so far (the paper's `C`), mutually non-dominated, at most one
367 /// per cost vector.
368 front: Vec<ParetoSolution<N>>,
369 /// Counters reported in [`ParetoResult::stats`].
370 stats: Stats,
371}
372
373impl<'a, G: Graph, F: Fn(AgentId, Vertex, Vertex) -> [u32; N], const N: usize> Search<'a, G, F, N> {
374 /// Prepares a run: computes the heuristic tables.
375 fn new(
376 instance: &'a Instance<G>,
377 costs: &'a F,
378 config: MoCbsConfig,
379 budget: &'a mut dyn Budget<Stats>,
380 ) -> Self {
381 let graph = instance.graph();
382 let heuristics = instance
383 .agents()
384 .iter()
385 .enumerate()
386 .map(|(id, agent)| Heuristic::new(graph, &|u, v| costs(id, u, v), agent.goal))
387 .collect();
388
389 Self {
390 instance,
391 costs,
392 config,
393 heuristics,
394 budget: RefCell::new(budget),
395 open: BTreeMap::new(),
396 front: Vec::new(),
397 stats: Stats::default(),
398 }
399 }
400
401 /// Runs the search to its end (Alg. 1 of the paper).
402 fn run(&mut self) -> ParetoOutcome {
403 if self.config.feasibility_check && self.is_proven_infeasible() {
404 return ParetoOutcome::Unsolvable;
405 }
406
407 let mut roots = match self.roots() {
408 Ok(Some(roots)) => roots,
409 Ok(None) => return ParetoOutcome::Unsolvable,
410 Err(Interrupted) => return ParetoOutcome::LimitReached,
411 };
412
413 if !self.config.tree_by_tree {
414 for root in roots.by_ref() {
415 if self.is_exhausted() {
416 return ParetoOutcome::LimitReached;
417 }
418
419 self.push(root);
420 }
421 }
422
423 loop {
424 if self.run_open().is_err() {
425 return ParetoOutcome::LimitReached;
426 }
427
428 let Some(root) = roots.next() else { break };
429 self.push(root);
430 }
431
432 if self.front.is_empty() {
433 ParetoOutcome::Unsolvable
434 } else {
435 ParetoOutcome::Complete
436 }
437 }
438
439 /// Returns `true` if recursive M* proves that no conflict-free plan exists. M* gets
440 /// the budget with its own counters.
441 fn is_proven_infeasible(&self) -> bool {
442 let config = MStarConfig::recursive(Objective::SumOfCosts);
443 let budget = |stats: &Stats| self.budget.borrow_mut().exhausted(stats);
444
445 mstar_with(self.instance, config, budget).outcome == Outcome::Unsolvable
446 }
447
448 /// Returns `true` if the budget says stop, given the high-level counters.
449 fn is_exhausted(&self) -> bool {
450 self.budget.borrow_mut().exhausted(&self.stats)
451 }
452
453 /// The root nodes; `None` if an agent has no path even alone.
454 fn roots(&self) -> Result<Option<Combinations<N>>, Interrupted> {
455 let mut sets = Vec::new();
456 for agent in 0..self.instance.agents().len() {
457 let set = self.replan(agent, &[])?;
458 if set.is_empty() {
459 return Ok(None);
460 }
461
462 sets.push(set);
463 }
464
465 Ok(Some(Combinations::roots(sets)))
466 }
467
468 /// Pops and handles open nodes until the open list is empty.
469 fn run_open(&mut self) -> Result<(), Interrupted> {
470 while let Some((_, node)) = self.open.pop_first() {
471 if self.is_filtered(&node.cost) {
472 continue;
473 }
474
475 let Some(conflict) = split::choose(&node, self.config.prioritize_conflicts) else {
476 self.record(&node);
477 continue;
478 };
479
480 if self.is_exhausted() {
481 return Err(Interrupted);
482 }
483
484 self.expand(&node, conflict)?;
485 }
486
487 Ok(())
488 }
489
490 /// Returns `true` if a solution found so far weakly dominates `cost` (the paper's
491 /// Filter): such a node cannot lead to a new Pareto-optimal cost vector.
492 fn is_filtered(&self, cost: &[u32; N]) -> bool {
493 self.front
494 .iter()
495 .any(|plan| weakly_dominates(&plan.cost, cost))
496 }
497
498 /// Adds the conflict-free `node` to the front and drops the solutions its cost
499 /// dominates (the paper's Update).
500 fn record(&mut self, node: &Node<N>) {
501 self.front.retain(|plan| !node.cost.dominates(&plan.cost));
502 self.front.push(ParetoSolution {
503 paths: node.paths.iter().map(|path| path.to_vec()).collect(),
504 cost: node.cost,
505 });
506 }
507
508 /// Splits `conflict` of `node` and opens the children: one node per combination of
509 /// the replanned agents' Pareto paths, or, with bypass, `node` with better paths.
510 fn expand(&mut self, node: &Node<N>, conflict: Conflict) -> Result<(), Interrupted> {
511 let mut children = Vec::new();
512 for constraint in split::constraints(node, conflict, self.config.splitting) {
513 if let Some(child) = self.child(node, constraint)? {
514 children.push(child);
515 }
516 }
517
518 // Counted only now, so that the low level's budget checks see completed expansions.
519 self.stats.expanded += 1;
520
521 if self.config.bypass {
522 if let Some(adopted) = children.iter().find_map(|child| split::bypass(node, child)) {
523 self.push(adopted);
524 return Ok(());
525 }
526 }
527
528 for child in children {
529 for grandchild in Combinations::children(node, child) {
530 self.push(grandchild);
531 }
532 }
533
534 Ok(())
535 }
536
537 /// The child of `node` with `constraint` added; `None` if an agent it replans has no
538 /// path.
539 ///
540 /// A negative constraint replans its agent. A positive one keeps its agent's path,
541 /// which takes part in the conflict and so meets it, and replans every other agent
542 /// whose path breaks what it implies for them.
543 fn child(
544 &self,
545 node: &Node<N>,
546 constraint: Constraint,
547 ) -> Result<Option<Child<N>>, Interrupted> {
548 let mut constraints = node.constraints.clone();
549 constraints.push(constraint);
550
551 let mut replanned = Vec::new();
552 for agent in split::affected(constraint, &node.paths) {
553 let set = self.replan(agent, &constraints)?;
554 if set.is_empty() {
555 return Ok(None);
556 }
557
558 replanned.push((agent, set));
559 }
560
561 Ok(Some(Child {
562 constraints,
563 replanned,
564 }))
565 }
566
567 /// The Pareto-optimal paths of `agent` under `constraints`.
568 fn replan(
569 &self,
570 agent: AgentId,
571 constraints: &[Constraint],
572 ) -> Result<ParetoSet<N>, Interrupted> {
573 let costs = |from, to| (self.costs)(agent, from, to);
574 let problem = Problem {
575 graph: self.instance.graph(),
576 costs: &costs,
577 agent: self.instance.agents()[agent],
578 heuristic: &self.heuristics[agent],
579 low_level: self.config.low_level,
580 };
581 let set = ConstraintSet::for_agent(agent, constraints);
582 let paths = pareto_paths(&problem, &set, &mut || self.is_exhausted()).ok_or(Interrupted)?;
583
584 Ok(paths
585 .into_iter()
586 .map(|(path, cost)| (Rc::from(path), cost))
587 .collect())
588 }
589
590 /// Opens `node` unless it is filtered.
591 fn push(&mut self, node: Node<N>) {
592 let order = self.stats.generated;
593 self.stats.generated += 1;
594
595 if !self.is_filtered(&node.cost) {
596 self.open.insert((node.cost, order), node);
597 }
598 }
599}
600
601#[cfg(test)]
602mod tests {
603 //! Unit tests for the front's Filter and Update.
604
605 use super::*;
606 use crate::graph::AdjacencyList;
607 use crate::instance::Agent;
608
609 /// Update drops a recorded solution that a later one dominates, and Filter then drops
610 /// nodes the new solution weakly dominates. The random properties rarely reach this:
611 /// in lexicographic pop order a dominating solution is usually found first.
612 #[test]
613 fn record_drops_dominated_solutions() {
614 let graph = AdjacencyList::undirected(2, &[(0, 1)]);
615 let instance =
616 Instance::new(graph, alloc::vec![Agent { start: 0, goal: 1 }]).expect("valid");
617 let costs = |_: AgentId, _: Vertex, _: Vertex| [1, 1];
618 let mut budget = |_: &Stats| false;
619 let mut search = Search::new(&instance, &costs, MoCbsConfig::default(), &mut budget);
620 let node = |cost: [u32; 2]| {
621 let path: Rc<[Vertex]> = Rc::from(alloc::vec![0, 1]);
622 Node::new(Vec::new(), alloc::vec![path], alloc::vec![cost], Vec::new())
623 };
624
625 search.record(&node([3, 3]));
626 search.record(&node([1, 5]));
627 search.record(&node([2, 2]));
628
629 let front: Vec<_> = search.front.iter().map(|plan| plan.cost).collect();
630 assert_eq!(front, [[1, 5], [2, 2]]);
631 assert!(search.is_filtered(&[2, 2]));
632 assert!(search.is_filtered(&[3, 4]));
633 assert!(!search.is_filtered(&[1, 4]));
634 }
635}