use alloc::collections::BTreeMap;
use alloc::vec::Vec;
use heuristic_search::{FocalList, Weight};
use crate::conflict_table::ConflictTable;
use crate::constraint::ConstraintSet;
use crate::graph::{Graph, Vertex};
use crate::instance::Agent;
use crate::path::{Path, Time};
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct FocalPath {
pub(super) path: Path,
pub(super) lower_bound: u32,
}
#[derive(Debug, Clone)]
struct Node {
vertex: Vertex,
time: Time,
finished: bool,
conflicts: u32,
parent: Option<usize>,
}
pub(super) struct Problem<'a, G> {
pub(super) graph: &'a G,
pub(super) agent: Agent,
pub(super) constraints: &'a ConstraintSet,
pub(super) distances: &'a [Option<u32>],
pub(super) table: &'a ConflictTable,
}
pub(super) fn focal_plan<G: Graph>(problem: &Problem<'_, G>, weight: Weight) -> Option<FocalPath> {
let start = problem.agent.start;
if !problem.constraints.allows_vertex(start, 0) {
return None;
}
let bounds = Bounds::new(problem);
let mut search = Search {
nodes: Vec::new(),
index: BTreeMap::new(),
list: FocalList::new(weight),
};
let h = bounds.heuristic(problem, start, 0)?;
search.open((start, 0, false), 0, None, h);
while let Some(lower_bound) = search.list.min_f() {
let current = search.list.pop().expect("the list is not empty");
if search.nodes[current].finished {
return Some(FocalPath {
path: search.path(current),
lower_bound,
});
}
search.expand(problem, &bounds, current);
}
None
}
type Key = (Vertex, Time, bool);
struct Bounds {
earliest_finish: Time,
horizon: Time,
}
impl Bounds {
fn new<G: Graph>(problem: &Problem<'_, G>) -> Self {
let constraints = problem.constraints;
Self {
earliest_finish: constraints.earliest_finish(problem.agent.goal),
horizon: constraints.horizon(problem.graph.vertex_count()),
}
}
fn heuristic<G>(&self, problem: &Problem<'_, G>, vertex: Vertex, time: Time) -> Option<u32> {
let distance = problem.distances[vertex]?;
Some(distance.max(self.earliest_finish.saturating_sub(time)))
}
}
struct Search {
nodes: Vec<Node>,
index: BTreeMap<Key, usize>,
list: FocalList<u32, u32>,
}
impl Search {
fn expand<G: Graph>(&mut self, problem: &Problem<'_, G>, bounds: &Bounds, current: usize) {
let Node {
vertex,
time,
conflicts,
..
} = self.nodes[current];
if vertex == problem.agent.goal && time >= bounds.earliest_finish {
let staying = conflicts + problem.table.after(vertex, time);
self.relax((vertex, time, true), staying, current, 0);
}
if time >= bounds.horizon {
return;
}
let mut step = |next: Vertex| {
if !problem.constraints.allows(vertex, next, time) {
return;
}
if let Some(h) = bounds.heuristic(problem, next, time + 1) {
let conflicts = conflicts + problem.table.count(vertex, next, time);
self.relax((next, time + 1, false), conflicts, current, h);
}
};
step(vertex);
problem.graph.neighbors(vertex, step);
}
fn open(&mut self, key: Key, conflicts: u32, parent: Option<usize>, h: u32) {
let (vertex, time, finished) = key;
let id = self.nodes.len();
self.list.push(id, time + h, time, conflicts);
self.nodes.push(Node {
vertex,
time,
finished,
conflicts,
parent,
});
self.index.insert(key, id);
}
fn relax(&mut self, key: Key, conflicts: u32, parent: usize, h: u32) {
let Some(&id) = self.index.get(&key) else {
self.open(key, conflicts, Some(parent), h);
return;
};
let node = &mut self.nodes[id];
if !self.list.contains(id) || conflicts >= node.conflicts {
return;
}
node.conflicts = conflicts;
node.parent = Some(parent);
self.list.push(id, node.time + h, node.time, conflicts);
}
fn path(&self, last: usize) -> Path {
let mut path: Path = core::iter::successors(Some(last), |&id| self.nodes[id].parent)
.filter(|&id| !self.nodes[id].finished)
.map(|id| self.nodes[id].vertex)
.collect();
path.reverse();
path
}
}
#[cfg(test)]
mod tests {
use super::*;
use alloc::vec;
use crate::conflict::conflicts;
use crate::graph::{Grid, distances_to};
#[test]
fn counts_conflicts_after_finishing() {
let grid = Grid::new(4, 1);
let agent = Agent { start: 0, goal: 1 };
let passing = vec![3, 2, 1, 2, 3];
let table = ConflictTable::without(&[vec![0], passing.clone()], 0);
let distances = distances_to(&grid, agent.goal);
let problem = Problem {
graph: &grid,
agent,
constraints: &ConstraintSet::new(),
distances: &distances,
table: &table,
};
let tight = focal_plan(&problem, Weight::ONE).expect("reachable");
assert_eq!(tight.path, [0, 1], "no slack: the conflict stays");
let loose = focal_plan(&problem, Weight::integer(3)).expect("reachable");
assert_eq!(loose.lower_bound, 1);
assert!(loose.path.len() <= 4, "within the weight: {:?}", loose.path);
assert_eq!(conflicts(&[loose.path, passing]), []);
}
}