mod osf;
use alloc::collections::{BTreeMap, BinaryHeap};
use alloc::vec::Vec;
use core::cmp::Reverse;
use heuristic_search::{Budget, Stats};
use self::osf::{Move, Operators};
use crate::graph::{Graph, Vertex};
use crate::instance::Instance;
use crate::low_level::{distance_tables, makespan_lower_bound};
use crate::path::{Objective, Path, Time, trim_trailing_waits};
use crate::solution::{MapfResult, Outcome, Solution, makespan_by_deadlines};
pub fn epea<G: Graph>(
instance: &Instance<G>,
objective: Objective,
mut budget: impl Budget<Stats>,
) -> MapfResult {
let mut run = Run {
instance,
distances: distance_tables(instance.graph(), instance.agents()),
stats: Stats::default(),
};
let outcome = match objective {
Objective::SumOfCosts => run.search(None, &mut budget),
Objective::Makespan => {
let lower_bound = makespan_lower_bound(instance.agents(), &run.distances);
makespan_by_deadlines(lower_bound, |deadline| run.search(deadline, &mut budget))
}
};
MapfResult {
outcome,
stats: run.stats,
}
}
struct Run<'a, G> {
instance: &'a Instance<G>,
distances: Vec<Vec<Option<u32>>>,
stats: Stats,
}
impl<G: Graph> Run<'_, G> {
fn search(&mut self, deadline: Option<Time>, budget: &mut impl Budget<Stats>) -> Outcome {
let mut search = Search {
instance: self.instance,
distances: &self.distances,
deadline,
nodes: Vec::new(),
index: BTreeMap::new(),
open: BinaryHeap::new(),
stats: self.stats,
};
let outcome = search.run(budget);
self.stats = search.stats;
outcome
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
struct Key {
time: Time,
agents: Vec<(Vertex, bool)>,
}
impl Key {
fn is_goal(&self) -> bool {
self.agents.iter().all(|&(_, finished)| finished)
}
}
struct Node {
key: Key,
g: u32,
h: u32,
rise: u32,
parent: Option<usize>,
}
type Entry = (u32, u32, usize, u32, u32);
struct Search<'a, G> {
instance: &'a Instance<G>,
distances: &'a [Vec<Option<u32>>],
deadline: Option<Time>,
nodes: Vec<Node>,
index: BTreeMap<Key, usize>,
open: BinaryHeap<Reverse<Entry>>,
stats: Stats,
}
impl<G: Graph> Search<'_, G> {
fn run(&mut self, budget: &mut impl Budget<Stats>) -> Outcome {
let start = Key {
time: 0,
agents: self
.instance
.agents()
.iter()
.map(|a| (a.start, false))
.collect(),
};
let Some(h) = self.heuristic(&start) else {
return Outcome::Unsolvable;
};
self.insert(start, 0, h, None);
while let Some(Reverse((_, _, id, rise, g))) = self.open.pop() {
let node = &self.nodes[id];
if node.rise != rise || node.g != g {
continue;
}
if rise == 0 && node.key.is_goal() {
return Outcome::Solved(Solution::new(self.paths(id)));
}
if budget.exhausted(&self.stats) {
return Outcome::LimitReached;
}
self.expand(id);
}
Outcome::Unsolvable
}
fn expand(&mut self, id: usize) {
self.stats.expanded += 1;
let operators = self.operators(&self.nodes[id].key);
let (g, rise) = (self.nodes[id].g, self.nodes[id].rise);
for joint in operators.with_rise(rise) {
self.generate(id, g, &joint);
}
if let Some(next) = operators.next_rise(rise) {
self.nodes[id].rise = next;
self.push(id);
}
}
fn generate(&mut self, parent: usize, g: u32, joint: &[Move]) {
let time = self.nodes[parent].key.time;
let key = Key {
time: if self.deadline.is_some() { time + 1 } else { 0 },
agents: joint.iter().map(|step| (step.to, step.finished)).collect(),
};
let g = g + joint.iter().map(|step| step.cost).sum::<u32>();
if key == self.nodes[parent].key {
return;
}
self.stats.generated += 1;
let h = self
.heuristic(&key)
.expect("moves keep every agent in time");
self.insert(key, g, h, Some(parent));
}
fn insert(&mut self, key: Key, g: u32, h: u32, parent: Option<usize>) {
if let Some(&id) = self.index.get(&key) {
let node = &mut self.nodes[id];
if node.g <= g {
return;
}
node.g = g;
node.rise = 0;
node.parent = parent;
self.stats.reopened += 1;
self.push(id);
return;
}
let id = self.nodes.len();
self.index.insert(key.clone(), id);
self.nodes.push(Node {
key,
g,
h,
rise: 0,
parent,
});
self.push(id);
}
fn push(&mut self, id: usize) {
let node = &self.nodes[id];
let f = node.g + node.h + node.rise;
self.open.push(Reverse((f, node.h, id, node.rise, node.g)));
}
fn operators(&self, key: &Key) -> Operators {
let moves = key
.agents
.iter()
.enumerate()
.map(|(agent, &position)| self.moves(agent, position, key.time))
.collect();
Operators::new(moves)
}
fn moves(&self, agent: usize, (here, finished): (Vertex, bool), time: Time) -> Vec<Move> {
let stay = Move {
from: here,
to: here,
finished: true,
cost: 0,
rise: 0,
};
if finished {
return Vec::from([stay]);
}
let distances = &self.distances[agent];
let current = distances[here].expect("agents stay where the goal is reachable");
let mut moves = Vec::new();
let mut consider = |next: Vertex| {
let Some(distance) = distances[next] else {
return;
};
if self
.deadline
.is_none_or(|deadline| time + 1 + distance <= deadline)
{
let rise = (1 + distance)
.checked_sub(current)
.expect("a step lowers the distance by at most 1");
moves.push(Move {
from: here,
to: next,
finished: false,
cost: 1,
rise,
});
}
};
consider(here);
self.instance.graph().neighbors(here, &mut consider);
if here == self.instance.agents()[agent].goal {
moves.push(stay);
}
moves
}
fn heuristic(&self, key: &Key) -> Option<u32> {
key.agents
.iter()
.zip(self.distances)
.filter(|((_, finished), _)| !finished)
.map(|(&(vertex, _), distances)| {
let distance = distances[vertex]?;
let late = self
.deadline
.is_some_and(|deadline| key.time + distance > deadline);
(!late).then_some(distance)
})
.sum()
}
fn paths(&self, id: usize) -> Vec<Path> {
let mut states = Vec::new();
let mut at = Some(id);
while let Some(id) = at {
states.push(&self.nodes[id].key);
at = self.nodes[id].parent;
}
states.reverse();
(0..self.instance.agents().len())
.map(|agent| {
let mut path: Path = states.iter().map(|state| state.agents[agent].0).collect();
trim_trailing_waits(&mut path);
path
})
.collect()
}
}