#[cfg(test)]
mod low_level;
mod neighborhood;
mod random;
mod sipps;
use alloc::vec;
use alloc::vec::Vec;
use heuristic_search::{Budget, Stats};
use self::neighborhood::Method;
use self::random::Random;
use self::sipps::{Obstacles, sipps};
use crate::conflict::conflicts;
use crate::graph::Graph;
use crate::instance::{AgentId, Instance};
use crate::low_level::distance_tables;
use crate::path::Path;
use crate::solution::{MapfResult, Outcome, Solution};
const REACTION: f64 = 0.1;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Lns2Config {
pub neighborhood_size: usize,
pub seed: u64,
}
impl Default for Lns2Config {
fn default() -> Self {
Self {
neighborhood_size: 8,
seed: 0,
}
}
}
pub fn lns2<G: Graph>(
instance: &Instance<G>,
config: Lns2Config,
mut budget: impl Budget<Stats>,
) -> MapfResult {
assert!(config.neighborhood_size > 0, "a neighborhood has an agent");
let distances = distance_tables(instance.graph(), instance.agents());
let reachable = instance
.agents()
.iter()
.zip(&distances)
.all(|(agent, distances)| distances[agent.start].is_some());
if !reachable {
return MapfResult {
outcome: Outcome::Unsolvable,
stats: Stats::default(),
};
}
let mut repair = Repair {
instance,
distances,
size: config.neighborhood_size.min(instance.agents().len()),
random: Random::new(config.seed),
paths: vec![Vec::new(); instance.agents().len()],
weights: [1.0; Method::ALL.len()],
stats: Stats::default(),
};
let outcome = repair.run(&mut budget);
MapfResult {
outcome,
stats: repair.stats,
}
}
struct Repair<'a, G> {
instance: &'a Instance<G>,
distances: Vec<Vec<Option<u32>>>,
size: usize,
random: Random,
paths: Vec<Path>,
weights: [f64; Method::ALL.len()],
stats: Stats,
}
impl<G: Graph> Repair<'_, G> {
fn run(&mut self, budget: &mut impl Budget<Stats>) -> Outcome {
let mut order: Vec<AgentId> = (0..self.paths.len()).collect();
self.random.shuffle(&mut order);
self.replan(&order);
loop {
let collisions = Collisions::of(&self.paths);
if collisions.pairs == 0 {
return Outcome::Solved(Solution::new(self.paths.clone()));
}
if budget.exhausted(&self.stats) {
return Outcome::LimitReached;
}
self.iterate(&collisions);
}
}
fn iterate(&mut self, collisions: &Collisions) {
self.stats.expanded += 1;
let index = self
.random
.weighted(&self.weights)
.unwrap_or_else(|| self.random.below(Method::ALL.len()));
let mut agents = self.neighborhood(Method::ALL[index], collisions);
self.random.shuffle(&mut agents);
let old: Vec<Path> = agents
.iter()
.map(|&agent| self.paths[agent].clone())
.collect();
self.replan(&agents);
let after = Collisions::of(&self.paths).pairs;
if after > collisions.pairs {
for (&agent, path) in agents.iter().zip(old) {
self.paths[agent] = path;
}
}
let gain =
f64::from(u32::try_from(collisions.pairs.saturating_sub(after)).unwrap_or(u32::MAX));
self.weights[index] = REACTION * gain + (1.0 - REACTION) * self.weights[index];
}
fn replan(&mut self, agents: &[AgentId]) {
for (position, &agent) in agents.iter().enumerate() {
let pending = &agents[position..];
let others = self
.paths
.iter()
.enumerate()
.filter(|(other, path)| !path.is_empty() && !pending.contains(other))
.map(|(_, path)| path);
let obstacles = Obstacles::of(others);
self.stats.generated += 1;
self.paths[agent] = sipps(
self.instance.graph(),
self.instance.agents()[agent],
&self.distances[agent],
&obstacles,
)
.expect("every goal is reachable");
}
}
}
struct Collisions {
neighbors: Vec<Vec<AgentId>>,
pairs: usize,
}
impl Collisions {
fn of(paths: &[Path]) -> Self {
let mut neighbors = vec![Vec::new(); paths.len()];
for conflict in conflicts(paths) {
let (a, b) = conflict.agents();
neighbors[a].push(b);
neighbors[b].push(a);
}
for list in &mut neighbors {
list.sort_unstable();
list.dedup();
}
let pairs = neighbors.iter().map(Vec::len).sum::<usize>() / 2;
Self { neighbors, pairs }
}
fn degree(&self, agent: AgentId) -> usize {
self.neighbors[agent].len()
}
}
#[cfg(test)]
mod tests {
use super::*;
use heuristic_search::Limits;
use crate::conflict::first_conflict;
use crate::graph::Grid;
use crate::instance::Agent;
fn crowded() -> Instance<Grid> {
let agents = (0..12)
.map(|i| Agent {
start: i,
goal: 24 - i,
})
.collect();
Instance::new(Grid::new(5, 5), agents).expect("valid")
}
#[test]
fn repairs_deterministically() {
let instance = crowded();
let mut iterations = 0;
for seed in 0..4 {
for neighborhood_size in [2, 4, 8, 100] {
let config = Lns2Config {
neighborhood_size,
seed,
};
let first = lns2(&instance, config, Limits::expansions(10_000));
let second = lns2(&instance, config, Limits::expansions(10_000));
let solution = first.solution().expect("solvable");
assert_eq!(first, second);
assert_eq!(first_conflict(&solution.paths), None);
for (path, agent) in solution.paths.iter().zip(instance.agents()) {
assert_eq!(path.first(), Some(&agent.start));
assert_eq!(path.last(), Some(&agent.goal));
}
iterations += first.stats.expanded;
}
}
assert!(iterations > 0, "some initial plan had collisions");
}
#[test]
fn stops_at_the_budget_when_unsolvable() {
let grid = Grid::new(3, 1);
let agents = vec![Agent { start: 0, goal: 2 }, Agent { start: 2, goal: 0 }];
let instance = Instance::new(grid, agents).expect("valid");
let result = lns2(&instance, Lns2Config::default(), Limits::expansions(50));
assert_eq!(result.outcome, Outcome::LimitReached);
assert_eq!(result.stats.expanded, 50);
}
#[test]
fn proves_an_unreachable_goal() {
let grid = Grid::parse(&[".@."]);
let instance = Instance::new(grid, vec![Agent { start: 0, goal: 2 }]).expect("valid");
let result = lns2(&instance, Lns2Config::default(), Limits::NONE);
assert_eq!(result.outcome, Outcome::Unsolvable);
}
}