mapf_search/lns2.rs
1//! MAPF-LNS2 ([`lns2`], Li et al. 2022): repairs a plan with collisions by large
2//! neighborhood search until it has none. Fast, neither optimal nor complete.
3//!
4//! The initial plan comes from prioritized planning in a random order, where each agent
5//! takes the path with the fewest collisions with the agents planned before it, so an
6//! agent that cannot avoid them all still gets a path. Then, as long as two paths collide,
7//! one iteration:
8//!
9//! 1. picks a *neighborhood* of agents with one of three methods (collision-based,
10//! failure-based or random; see [`neighborhood`]), chosen by adaptive LNS: each method
11//! has a weight, raised by the collisions it removes;
12//! 2. replans those agents one after another in a random order, each with the fewest
13//! collisions with every other current path, by SIPPS ([`sipps`](mod@sipps));
14//! 3. keeps the new paths if the number of colliding agent pairs did not grow, else
15//! restores the old ones.
16//!
17//! ```mermaid
18//! flowchart TD
19//! init[prioritized planning, fewest collisions] --> count{colliding pairs?}
20//! count -->|none| solved[Solved]
21//! count --> budget{budget exhausted?}
22//! budget -->|yes| limit[LimitReached]
23//! budget -->|no| pick[pick a method by weight, build a neighborhood]
24//! pick --> replan[replan its agents in random order]
25//! replan --> accept{more colliding pairs than before?}
26//! accept -->|no| keep[keep the new paths]
27//! accept -->|yes| restore[restore the old paths]
28//! keep --> weight[update the method's weight]
29//! restore --> weight
30//! weight --> count
31//! ```
32
33#[cfg(test)]
34mod low_level;
35mod neighborhood;
36mod sipps;
37
38use alloc::vec;
39use alloc::vec::Vec;
40
41use heuristic_search::{Budget, Stats};
42
43use self::neighborhood::Method;
44use self::sipps::{Obstacles, sipps};
45use crate::conflict::conflicts;
46use crate::graph::Graph;
47use crate::instance::{AgentId, Instance};
48use crate::low_level::distance_tables;
49use crate::path::Path;
50use crate::random::Random;
51use crate::solution::{MapfResult, Outcome, Solution};
52
53/// How fast the adaptive weights follow recent success: the paper's reaction factor `γ`.
54const REACTION: f64 = 0.1;
55
56/// The settings of [`lns2`].
57#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
58pub struct Lns2Config {
59 /// How many agents each iteration replans, the paper's `N`; at least 1, at most the
60 /// number of agents (larger values are capped). The default is the paper's 8.
61 pub neighborhood_size: usize,
62 /// The seed of every random choice: the same instance, configuration and budget give
63 /// the same result.
64 pub seed: u64,
65}
66
67impl Default for Lns2Config {
68 /// Neighborhoods of 8 agents, seed `0`.
69 fn default() -> Self {
70 Self {
71 neighborhood_size: 8,
72 seed: 0,
73 }
74 }
75}
76
77/// Finds a conflict-free plan with MAPF-LNS2: an initial plan that may have collisions,
78/// then large neighborhood search that replans a few agents at a time until no two paths
79/// collide.
80///
81/// The plan has no quality guarantee; LNS2 aims at a feasible plan fast. It is not
82/// complete either: on an unsolvable instance it runs until its budget, so always pass
83/// one. The result is [`Outcome::Unsolvable`] only if an agent cannot reach its goal even
84/// alone, and never [`Outcome::Exhausted`].
85///
86/// `budget` is asked before every repair iteration; [`MapfResult::stats`] counts
87/// iterations in [`Stats::expanded`] and single-agent searches, the initial ones
88/// included, in [`Stats::generated`].
89///
90/// # Panics
91///
92/// Panics if `config.neighborhood_size` is `0`.
93///
94/// # Examples
95///
96/// ```
97/// use mapf_search::{Agent, Grid, Instance, Limits, Lns2Config, first_conflict, lns2};
98///
99/// // Four agents cross a free 4x4 grid.
100/// let grid = Grid::new(4, 4);
101/// let agents = vec![
102/// Agent { start: 0, goal: 15 },
103/// Agent { start: 3, goal: 12 },
104/// Agent { start: 12, goal: 3 },
105/// Agent { start: 15, goal: 0 },
106/// ];
107/// let instance = Instance::new(grid, agents)?;
108///
109/// let result = lns2(&instance, Lns2Config::default(), Limits::expansions(1_000));
110/// let solution = result.solution().expect("LNS2 repairs every collision");
111/// assert_eq!(first_conflict(&solution.paths), None);
112/// # Ok::<(), mapf_search::InstanceError>(())
113/// ```
114pub fn lns2<G: Graph>(
115 instance: &Instance<G>,
116 config: Lns2Config,
117 mut budget: impl Budget<Stats>,
118) -> MapfResult {
119 assert!(config.neighborhood_size > 0, "a neighborhood has an agent");
120
121 let distances = distance_tables(instance.graph(), instance.agents());
122 let reachable = instance
123 .agents()
124 .iter()
125 .zip(&distances)
126 .all(|(agent, distances)| distances[agent.start].is_some());
127 if !reachable {
128 return MapfResult {
129 outcome: Outcome::Unsolvable,
130 stats: Stats::default(),
131 };
132 }
133
134 let mut repair = Repair {
135 instance,
136 distances,
137 size: config.neighborhood_size.min(instance.agents().len()),
138 random: Random::new(config.seed),
139 paths: vec![Vec::new(); instance.agents().len()],
140 weights: [1.0; Method::ALL.len()],
141 stats: Stats::default(),
142 };
143 let outcome = repair.run(&mut budget);
144
145 MapfResult {
146 outcome,
147 stats: repair.stats,
148 }
149}
150
151/// The state of one [`lns2`] run.
152struct Repair<'a, G> {
153 /// The instance being solved.
154 instance: &'a Instance<G>,
155 /// Distances to each agent's goal, indexed by agent; every start reaches its goal.
156 distances: Vec<Vec<Option<u32>>>,
157 /// The neighborhood size, between 1 and the number of agents.
158 size: usize,
159 /// The source of every random choice.
160 random: Random,
161 /// The current path of each agent; empty only before the agent is first planned.
162 paths: Vec<Path>,
163 /// The adaptive weight of each neighborhood method, indexed like [`Method::ALL`].
164 weights: [f64; Method::ALL.len()],
165 /// Counters reported in [`MapfResult::stats`].
166 stats: Stats,
167}
168
169impl<G: Graph> Repair<'_, G> {
170 /// Plans every agent, then repairs until no collision is left or the budget ends.
171 fn run(&mut self, budget: &mut impl Budget<Stats>) -> Outcome {
172 let mut order: Vec<AgentId> = (0..self.paths.len()).collect();
173 self.random.shuffle(&mut order);
174 self.replan(&order);
175
176 loop {
177 let collisions = Collisions::of(&self.paths);
178 if collisions.pairs == 0 {
179 return Outcome::Solved(Solution::new(self.paths.clone()));
180 }
181
182 if budget.exhausted(&self.stats) {
183 return Outcome::LimitReached;
184 }
185
186 self.iterate(&collisions);
187 }
188 }
189
190 /// One repair iteration on a plan with `collisions`: pick a method and a neighborhood,
191 /// replan it, keep or restore, and update the method's weight.
192 fn iterate(&mut self, collisions: &Collisions) {
193 self.stats.expanded += 1;
194
195 let index = self
196 .random
197 .weighted(&self.weights)
198 .unwrap_or_else(|| self.random.below(Method::ALL.len()));
199 let mut agents = self.neighborhood(Method::ALL[index], collisions);
200 self.random.shuffle(&mut agents);
201
202 let old: Vec<Path> = agents
203 .iter()
204 .map(|&agent| self.paths[agent].clone())
205 .collect();
206 self.replan(&agents);
207 let after = Collisions::of(&self.paths).pairs;
208 if after > collisions.pairs {
209 for (&agent, path) in agents.iter().zip(old) {
210 self.paths[agent] = path;
211 }
212 }
213
214 let gain =
215 f64::from(u32::try_from(collisions.pairs.saturating_sub(after)).unwrap_or(u32::MAX));
216 self.weights[index] = REACTION * gain + (1.0 - REACTION) * self.weights[index];
217 }
218
219 /// Replans `agents` in their order, each with the fewest collisions with every other
220 /// agent's path, the ones not yet replanned among `agents` left out.
221 fn replan(&mut self, agents: &[AgentId]) {
222 for (position, &agent) in agents.iter().enumerate() {
223 let pending = &agents[position..];
224 let others = self
225 .paths
226 .iter()
227 .enumerate()
228 .filter(|(other, path)| !path.is_empty() && !pending.contains(other))
229 .map(|(_, path)| path);
230 let obstacles = Obstacles::of(others);
231
232 self.stats.generated += 1;
233 self.paths[agent] = sipps(
234 self.instance.graph(),
235 self.instance.agents()[agent],
236 &self.distances[agent],
237 &obstacles,
238 )
239 .expect("every goal is reachable");
240 }
241 }
242}
243
244/// The collision graph of a plan: which agents' paths collide.
245struct Collisions {
246 /// The agents each agent collides with, indexed by agent; sorted, without duplicates.
247 neighbors: Vec<Vec<AgentId>>,
248 /// The number of colliding agent pairs, the paper's `CP`.
249 pairs: usize,
250}
251
252impl Collisions {
253 /// The collision graph of `paths`.
254 ///
255 /// shortcut: scans every pair of paths at every time step, `O(m^2 T)` for `m` agents;
256 /// fine at this crate's instance sizes, upgrade to an incremental table for hundreds.
257 fn of(paths: &[Path]) -> Self {
258 let mut neighbors = vec![Vec::new(); paths.len()];
259 for conflict in conflicts(paths) {
260 let (a, b) = conflict.agents();
261 neighbors[a].push(b);
262 neighbors[b].push(a);
263 }
264
265 for list in &mut neighbors {
266 list.sort_unstable();
267 list.dedup();
268 }
269
270 let pairs = neighbors.iter().map(Vec::len).sum::<usize>() / 2;
271
272 Self { neighbors, pairs }
273 }
274
275 /// The number of agents `agent` collides with.
276 fn degree(&self, agent: AgentId) -> usize {
277 self.neighbors[agent].len()
278 }
279}
280
281#[cfg(test)]
282mod tests {
283 //! Runs of LNS2 on small instances.
284
285 use super::*;
286
287 use heuristic_search::Limits;
288
289 use crate::conflict::first_conflict;
290 use crate::graph::Grid;
291 use crate::instance::Agent;
292
293 /// Twelve agents on a free 5x5 grid, from the first cells to the mirrored ones: the
294 /// initial plan collides for most seeds.
295 fn crowded() -> Instance<Grid> {
296 let agents = (0..12)
297 .map(|i| Agent {
298 start: i,
299 goal: 24 - i,
300 })
301 .collect();
302
303 Instance::new(Grid::new(5, 5), agents).expect("valid")
304 }
305
306 /// Every seed and neighborhood size repairs the crowded grid, some only after repair
307 /// iterations, and the same seed gives the same plan.
308 #[test]
309 fn repairs_deterministically() {
310 let instance = crowded();
311 let mut iterations = 0;
312 for seed in 0..4 {
313 for neighborhood_size in [2, 4, 8, 100] {
314 let config = Lns2Config {
315 neighborhood_size,
316 seed,
317 };
318 let first = lns2(&instance, config, Limits::expansions(10_000));
319 let second = lns2(&instance, config, Limits::expansions(10_000));
320 let solution = first.solution().expect("solvable");
321
322 assert_eq!(first, second);
323 assert_eq!(first_conflict(&solution.paths), None);
324 for (path, agent) in solution.paths.iter().zip(instance.agents()) {
325 assert_eq!(path.first(), Some(&agent.start));
326 assert_eq!(path.last(), Some(&agent.goal));
327 }
328
329 iterations += first.stats.expanded;
330 }
331 }
332
333 assert!(iterations > 0, "some initial plan had collisions");
334 }
335
336 /// The corridor swap is unsolvable; LNS2 stops at its budget.
337 #[test]
338 fn stops_at_the_budget_when_unsolvable() {
339 let grid = Grid::new(3, 1);
340 let agents = vec![Agent { start: 0, goal: 2 }, Agent { start: 2, goal: 0 }];
341 let instance = Instance::new(grid, agents).expect("valid");
342
343 let result = lns2(&instance, Lns2Config::default(), Limits::expansions(50));
344
345 assert_eq!(result.outcome, Outcome::LimitReached);
346 assert_eq!(result.stats.expanded, 50);
347 }
348
349 /// An unreachable goal is proven at once.
350 #[test]
351 fn proves_an_unreachable_goal() {
352 let grid = Grid::parse(&[".@."]);
353 let instance = Instance::new(grid, vec![Agent { start: 0, goal: 2 }]).expect("valid");
354
355 let result = lns2(&instance, Lns2Config::default(), Limits::NONE);
356
357 assert_eq!(result.outcome, Outcome::Unsolvable);
358 }
359}