mapf_search/icts.rs
1//! Increasing cost tree search ([`icts`], Sharon et al. 2013): optimal for sum of costs or
2//! makespan ([`Objective`]).
3//!
4//! The high level searches cost vectors `(c_1, ..., c_k)`, one cost per agent, in order of
5//! their sum, starting at every agent's individual optimum; a vector's children raise one
6//! agent's cost by 1. For each vector, the low level builds the MDD of every agent at its
7//! cost and looks for one conflict-free combination of MDD paths. Simple pairwise pruning
8//! first checks every pair of agents on its own, which rules out most vectors cheaply.
9//!
10//! For makespan the tree is a chain: the vector `(m, ..., m)` for `m` from the largest
11//! individual optimum on. An MDD of depth `m` holds every path that arrives by `m` and waits
12//! at the goal, so the first `m` with a conflict-free combination is the optimal makespan.
13//!
14//! ```mermaid
15//! flowchart TD
16//! root[individual optimal costs] -->|an agent cannot reach its goal| unsolvable[Unsolvable]
17//! root --> pop[pop the cheapest unvisited vector]
18//! pop --> budget{budget exhausted?}
19//! budget -->|yes| limit[LimitReached]
20//! budget -->|no| pairs{every pair has a joint path?}
21//! pairs -->|no| grow[queue the vectors with one cost raised]
22//! pairs -->|yes| all{all agents have one?}
23//! all -->|yes| solved[Solved]
24//! all -->|no| grow
25//! grow --> pop
26//! ```
27
28use alloc::collections::{BTreeMap, BTreeSet};
29use alloc::rc::Rc;
30use alloc::vec::Vec;
31
32use heuristic_search::{Budget, Stats};
33
34use crate::constraint::ConstraintSet;
35use crate::graph::Graph;
36use crate::instance::{AgentId, Instance};
37use crate::low_level::distance_tables;
38use crate::mdd::{Mdd, joint_paths};
39use crate::path::{Objective, Path, Time};
40use crate::solution::{MapfResult, Outcome, Solution};
41
42/// Finds a conflict-free plan with the optimal `objective` value by increasing cost tree
43/// search.
44///
45/// `budget` is asked before evaluating each cost vector; [`MapfResult::stats`] counts
46/// evaluated vectors in [`Stats::expanded`] and queued vectors (the root included) in
47/// [`Stats::generated`]. ICTS proves unsolvability only when an agent cannot reach its
48/// goal even alone; on other unsolvable instances the tree is infinite and the run ends at
49/// the budget. For makespan, the `m`-th vector searches MDDs about `m` levels deep, so such
50/// a run costs roughly the cube of the budget; keep makespan budgets small (a few hundred
51/// vectors take seconds).
52///
53/// For [`Objective::Makespan`] the plan's sum of costs is low but not guaranteed minimal
54/// among the makespan-optimal plans: the joint MDD search returns the first combination it
55/// finds. The search is exponential in the number of agents whose costs must rise, so ICTS
56/// suits instances where few agents interact strongly.
57///
58/// # Examples
59///
60/// ```
61/// use mapf_search::{Agent, Grid, Instance, Limits, Objective, icts};
62///
63/// // Two agents swap the ends of a corridor with one side pocket.
64/// let grid = Grid::parse(&["...", "@.@"]);
65/// let agents = vec![
66/// Agent { start: grid.vertex(0, 0), goal: grid.vertex(2, 0) },
67/// Agent { start: grid.vertex(2, 0), goal: grid.vertex(0, 0) },
68/// ];
69/// let instance = Instance::new(grid, agents)?;
70///
71/// let result = icts(&instance, Objective::SumOfCosts, Limits::expansions(1_000));
72/// assert_eq!(result.solution().expect("solvable").sum_of_costs, 7);
73/// # Ok::<(), mapf_search::InstanceError>(())
74/// ```
75pub fn icts<G: Graph>(
76 instance: &Instance<G>,
77 objective: Objective,
78 mut budget: impl Budget<Stats>,
79) -> MapfResult {
80 let mut search = Search {
81 instance,
82 objective,
83 distances: distance_tables(instance.graph(), instance.agents()),
84 mdds: BTreeMap::new(),
85 stats: Stats::default(),
86 };
87 let outcome = search.run(&mut budget);
88
89 MapfResult {
90 outcome,
91 stats: search.stats,
92 }
93}
94
95/// The state of one ICTS run.
96struct Search<'a, G> {
97 /// The instance being solved.
98 instance: &'a Instance<G>,
99 /// What the search minimizes; decides the children of a cost vector.
100 objective: Objective,
101 /// Distances to each agent's goal, indexed by agent.
102 distances: Vec<Vec<Option<u32>>>,
103 /// The MDD of each `(agent, cost)` built so far.
104 mdds: BTreeMap<(AgentId, Time), Rc<Mdd>>,
105 /// Counters reported in [`MapfResult::stats`].
106 stats: Stats,
107}
108
109impl<G: Graph> Search<'_, G> {
110 /// Runs the high-level search to its end.
111 fn run(&mut self, budget: &mut impl Budget<Stats>) -> Outcome {
112 let Some(root) = self.root() else {
113 return Outcome::Unsolvable;
114 };
115
116 let mut open = BTreeSet::from([(root.iter().sum::<u32>(), root.clone())]);
117 let mut seen = BTreeSet::from([root]);
118 self.stats.generated += 1;
119 while let Some((_, costs)) = open.pop_first() {
120 if budget.exhausted(&self.stats) {
121 return Outcome::LimitReached;
122 }
123
124 self.stats.expanded += 1;
125 if let Some(paths) = self.evaluate(&costs) {
126 return Outcome::Solved(Solution::new(paths));
127 }
128
129 for child in self.children(&costs) {
130 if seen.insert(child.clone()) {
131 self.stats.generated += 1;
132 open.insert((child.iter().sum(), child));
133 }
134 }
135 }
136
137 unreachable!("the cost tree is infinite")
138 }
139
140 /// The children of the cost vector `costs`: one agent's cost raised by 1 for sum of
141 /// costs, every cost raised by 1 for makespan.
142 fn children(&self, costs: &[Time]) -> Vec<Vec<Time>> {
143 match self.objective {
144 Objective::SumOfCosts => (0..costs.len())
145 .map(|agent| {
146 let mut child = costs.to_vec();
147 child[agent] += 1;
148 child
149 })
150 .collect(),
151 Objective::Makespan => Vec::from([costs.iter().map(|cost| cost + 1).collect()]),
152 }
153 }
154
155 /// The first cost vector: every agent's cost alone for sum of costs, their maximum for
156 /// every agent for makespan. `None` if an agent cannot reach its goal.
157 fn root(&self) -> Option<Vec<Time>> {
158 let alone = self.individual_costs()?;
159
160 Some(match self.objective {
161 Objective::SumOfCosts => alone,
162 Objective::Makespan => {
163 let makespan = alone.iter().copied().max().unwrap_or(0);
164 alloc::vec![makespan; alone.len()]
165 }
166 })
167 }
168
169 /// Every agent's cost alone; `None` if one cannot reach its goal.
170 fn individual_costs(&self) -> Option<Vec<Time>> {
171 self.instance
172 .agents()
173 .iter()
174 .zip(&self.distances)
175 .map(|(agent, distances)| distances[agent.start])
176 .collect()
177 }
178
179 /// A conflict-free plan in which every agent arrives at exactly its cost in `costs`
180 /// (or earlier, then waits), or `None` if there is none.
181 fn evaluate(&mut self, costs: &[Time]) -> Option<Vec<Path>> {
182 let mdds: Vec<Rc<Mdd>> = (0..costs.len())
183 .map(|agent| self.mdd(agent, costs[agent]))
184 .collect();
185
186 for (i, a) in mdds.iter().enumerate() {
187 for b in &mdds[i + 1..] {
188 joint_paths(&[a, b])?;
189 }
190 }
191
192 let all: Vec<&Mdd> = mdds.iter().map(Rc::as_ref).collect();
193
194 joint_paths(&all)
195 }
196
197 /// The MDD of `agent` at `cost`, built once.
198 fn mdd(&mut self, agent: AgentId, cost: Time) -> Rc<Mdd> {
199 let (instance, distances) = (self.instance, &self.distances);
200
201 Rc::clone(self.mdds.entry((agent, cost)).or_insert_with(|| {
202 let mdd = Mdd::build(
203 instance.graph(),
204 instance.agents()[agent],
205 &ConstraintSet::new(),
206 &distances[agent],
207 cost,
208 )
209 .expect("every cost from the individual optimum on has paths");
210
211 Rc::new(mdd)
212 }))
213 }
214}