Skip to main content

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