use alloc::collections::BinaryHeap;
use alloc::vec;
use alloc::vec::Vec;
use core::cell::{Cell, RefCell};
use core::cmp::Reverse;
use multiobjective_search::{Graph as MoGraph, Output, boa_star, heuristic_fn, namoa_star_dr};
use super::LowLevel;
use crate::constraint::ConstraintSet;
use crate::graph::{Graph, Vertex, reverse_adjacency};
use crate::instance::Agent;
use crate::path::{Path, Time};
type State = (Vertex, Time);
const INTERRUPT_EVERY: u64 = 256;
pub(super) type Interrupt<'a> = &'a mut dyn FnMut() -> bool;
pub(super) struct Heuristic<const N: usize> {
bounds: Vec<Option<[u32; N]>>,
}
impl<const N: usize> Heuristic<N> {
pub(super) fn new<G: Graph>(
graph: &G,
costs: &impl Fn(Vertex, Vertex) -> [u32; N],
goal: Vertex,
) -> Self {
let reverse = reverse_adjacency(graph);
let per_objective: Vec<Vec<Option<u32>>> = (0..N)
.map(|objective| dijkstra_to(&reverse, |u, v| costs(u, v)[objective], goal))
.collect();
let bounds = (0..graph.vertex_count())
.map(|vertex| {
let mut bound = [0; N];
for (slot, distances) in bound.iter_mut().zip(&per_objective) {
*slot = distances[vertex]?;
}
Some(bound)
})
.collect();
Self { bounds }
}
fn at(&self, vertex: Vertex) -> Option<[u32; N]> {
self.bounds[vertex]
}
}
fn dijkstra_to(
reverse: &[Vec<Vertex>],
cost: impl Fn(Vertex, Vertex) -> u32,
target: Vertex,
) -> Vec<Option<u32>> {
let mut distance = vec![None; reverse.len()];
let mut queue = BinaryHeap::from([Reverse((0_u32, target))]);
while let Some(Reverse((d, vertex))) = queue.pop() {
if distance[vertex].is_some() {
continue;
}
distance[vertex] = Some(d);
for &previous in &reverse[vertex] {
if distance[previous].is_none() {
queue.push(Reverse((d + cost(previous, vertex), previous)));
}
}
}
distance
}
pub(super) struct Problem<'a, G, F, const N: usize> {
pub(super) graph: &'a G,
pub(super) costs: &'a F,
pub(super) agent: Agent,
pub(super) heuristic: &'a Heuristic<N>,
pub(super) low_level: LowLevel,
}
pub(super) fn pareto_paths<G: Graph, F: Fn(Vertex, Vertex) -> [u32; N], const N: usize>(
problem: &Problem<'_, G, F, N>,
constraints: &ConstraintSet,
interrupt: Interrupt<'_>,
) -> Option<Vec<(Path, [u32; N])>> {
let Problem {
graph,
costs,
agent,
heuristic,
low_level,
} = *problem;
if !constraints.allows_vertex(agent.start, 0) {
return Some(Vec::new());
}
let space = SpaceTime::new(graph, costs, agent, constraints, interrupt);
let earliest_finish = space.earliest_finish;
let is_goal = |&(vertex, time): &State| vertex == agent.goal && time >= earliest_finish;
let start = (agent.start, 0);
let paths: Vec<(Vec<State>, [u32; N])> = if N == 2 && low_level == LowLevel::Auto {
let bound = |&(vertex, _): &State| heuristic.at(vertex).map(|b| narrow::<N, 2>(&b));
let output = boa_star(&Bi(&space), heuristic_fn(bound), start, is_goal);
unpack(output, |cost| narrow::<2, N>(&cost))
} else {
let bound = |&(vertex, _): &State| heuristic.at(vertex);
let output = namoa_star_dr(&space, heuristic_fn(bound), start, is_goal);
unpack(output, |cost| cost)
};
if space.stopped.get() {
return None;
}
let paths = paths
.into_iter()
.map(|(states, cost)| (states.into_iter().map(|(v, _)| v).collect(), cost))
.collect();
Some(paths)
}
fn unpack<const M: usize, const N: usize>(
output: Output<State, [u32; M]>,
widen: impl Fn([u32; M]) -> [u32; N],
) -> Vec<(Vec<State>, [u32; N])> {
output
.solutions
.into_iter()
.map(|solution| (solution.path, widen(solution.cost)))
.collect()
}
fn narrow<const N: usize, const M: usize>(vector: &[u32; N]) -> [u32; M] {
<[u32; M]>::try_from(&vector[..]).expect("only called when the lengths agree")
}
struct SpaceTime<'a, G, F> {
graph: &'a G,
costs: &'a F,
constraints: &'a ConstraintSet,
earliest_finish: Time,
horizon: Time,
interrupt: RefCell<Interrupt<'a>>,
expansions: Cell<u64>,
stopped: Cell<bool>,
}
impl<'a, G: Graph, F> SpaceTime<'a, G, F> {
fn new(
graph: &'a G,
costs: &'a F,
agent: Agent,
constraints: &'a ConstraintSet,
interrupt: Interrupt<'a>,
) -> Self {
Self {
interrupt: RefCell::new(interrupt),
expansions: Cell::new(0),
stopped: Cell::new(false),
graph,
costs,
constraints,
earliest_finish: constraints.earliest_finish(agent.goal),
horizon: constraints.horizon(graph.vertex_count()),
}
}
}
impl<G: Graph, F: Fn(Vertex, Vertex) -> [u32; N], const N: usize> MoGraph for SpaceTime<'_, G, F> {
type State = State;
type Weight = [u32; N];
fn successors(&self, &(vertex, time): &State, out: &mut Vec<(State, [u32; N])>) {
if time >= self.horizon || self.is_interrupted() {
return;
}
let mut step = |next: Vertex| {
if self.constraints.allows(vertex, next, time) {
out.push(((next, time + 1), (self.costs)(vertex, next)));
}
};
step(vertex);
self.graph.neighbors(vertex, step);
}
}
impl<G, F> SpaceTime<'_, G, F> {
fn is_interrupted(&self) -> bool {
if self.stopped.get() {
return true;
}
let count = self.expansions.get();
self.expansions.set(count + 1);
if count % INTERRUPT_EVERY == 0 && (self.interrupt.borrow_mut())() {
self.stopped.set(true);
}
self.stopped.get()
}
}
struct Bi<'a, T>(&'a T);
impl<T: MoGraph<State = State>> MoGraph for Bi<'_, T>
where
T::Weight: AsRef<[u32]>,
{
type State = State;
type Weight = [u32; 2];
fn successors(&self, state: &State, out: &mut Vec<(State, [u32; 2])>) {
let mut wide = Vec::new();
self.0.successors(state, &mut wide);
out.extend(wide.into_iter().map(|(next, cost)| {
let cost = <[u32; 2]>::try_from(cost.as_ref()).expect("BOA* runs only for N == 2");
(next, cost)
}));
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::constraint::Constraint;
use crate::graph::AdjacencyList;
fn diamond() -> (AdjacencyList, impl Fn(Vertex, Vertex) -> [u32; 2]) {
let graph = AdjacencyList::undirected(4, &[(0, 1), (0, 2), (1, 3), (2, 3)]);
let costs = |from: Vertex, to: Vertex| match (from.min(to), from.max(to)) {
(0, 1) | (1, 3) => [1, 3],
(0, 2) | (2, 3) => [3, 1],
_ => [1, 1],
};
(graph, costs)
}
#[test]
fn finds_both_routes_with_either_planner() {
let (graph, costs) = diamond();
let agent = Agent { start: 0, goal: 3 };
let heuristic = Heuristic::new(&graph, &costs, agent.goal);
for low_level in [LowLevel::Auto, LowLevel::NamoaDr] {
let problem = Problem {
graph: &graph,
costs: &costs,
agent,
heuristic: &heuristic,
low_level,
};
let paths = pareto_paths(&problem, &ConstraintSet::new(), &mut || false)
.expect("not interrupted");
assert_eq!(paths, [(vec![0, 1, 3], [2, 6]), (vec![0, 2, 3], [6, 2])]);
}
}
#[test]
fn respects_constraints_and_prices_waits() {
let (graph, costs) = diamond();
let agent = Agent { start: 0, goal: 3 };
let heuristic = Heuristic::new(&graph, &costs, agent.goal);
let mut constraints = ConstraintSet::new();
constraints.insert(&Constraint::Vertex {
agent: 0,
vertex: 1,
time: 1,
});
let problem = Problem {
graph: &graph,
costs: &costs,
agent,
heuristic: &heuristic,
low_level: LowLevel::Auto,
};
let paths = pareto_paths(&problem, &constraints, &mut || false).expect("not interrupted");
assert_eq!(paths, [(vec![0, 0, 1, 3], [3, 7]), (vec![0, 2, 3], [6, 2])]);
}
#[test]
fn interrupt_stops_the_search() {
let (graph, costs) = diamond();
let agent = Agent { start: 0, goal: 3 };
let heuristic = Heuristic::new(&graph, &costs, agent.goal);
let problem = Problem {
graph: &graph,
costs: &costs,
agent,
heuristic: &heuristic,
low_level: LowLevel::NamoaDr,
};
let mut asked = 0;
let paths = pareto_paths(&problem, &ConstraintSet::new(), &mut || {
asked += 1;
true
});
assert_eq!(paths, None);
assert_eq!(asked, 1);
}
}