use alloc::collections::{BTreeSet, VecDeque};
use alloc::vec::Vec;
use search_core::Cost;
use crate::cost::{add, weakly_dominates};
use crate::graph::{EdgeGraph, Graph, ReverseGraph};
use crate::output::{Output, Solution, Stats};
use crate::pareto::Front;
#[derive(Debug, Clone)]
pub struct DynamicGraph<C, const N: usize> {
edges: Vec<Option<(u32, u32, [C; N])>>,
out: Vec<Vec<usize>>,
into: Vec<Vec<usize>>,
}
impl<C: Cost, const N: usize> DynamicGraph<C, N> {
#[must_use]
pub fn new(nodes: u32) -> Self {
let n = usize::try_from(nodes).expect("u32 fits in usize");
Self {
edges: Vec::new(),
out: alloc::vec![Vec::new(); n],
into: alloc::vec![Vec::new(); n],
}
}
pub fn add_edge(&mut self, from: u32, to: u32, cost: [C; N]) -> usize {
let id = self.edges.len();
self.edges.push(Some((from, to, cost)));
self.out[index(from)].push(id);
self.into[index(to)].push(id);
id
}
#[must_use]
pub fn edge(&self, id: usize) -> Option<(u32, u32, [C; N])> {
self.edges.get(id).copied().flatten()
}
#[must_use]
pub fn node_count(&self) -> usize {
self.out.len()
}
}
fn index(state: u32) -> usize {
usize::try_from(state).expect("u32 fits in usize")
}
impl<C: Cost, const N: usize> Graph for DynamicGraph<C, N> {
type State = u32;
type Weight = [C; N];
fn successors(&self, state: &u32, out: &mut Vec<(u32, [C; N])>) {
out.extend(
self.out[index(*state)]
.iter()
.filter_map(|&e| self.edges[e])
.map(|(_, to, c)| (to, c)),
);
}
}
impl<C: Cost, const N: usize> ReverseGraph for DynamicGraph<C, N> {
fn predecessors(&self, state: &u32, out: &mut Vec<(u32, [C; N])>) {
out.extend(
self.into[index(*state)]
.iter()
.filter_map(|&e| self.edges[e])
.map(|(from, _, c)| (from, c)),
);
}
}
impl<C: Cost, const N: usize> EdgeGraph for DynamicGraph<C, N> {
type Edge = usize;
fn edges(&self, state: &u32, out: &mut Vec<(usize, u32, [C; N])>) {
out.extend(
self.out[index(*state)]
.iter()
.filter_map(|&e| self.edges[e].map(|(_, to, c)| (e, to, c))),
);
}
}
#[derive(Debug, Clone)]
struct Label<C, const N: usize> {
state: u32,
cost: [C; N],
parent: Option<usize>,
alive: bool,
children: Vec<usize>,
}
pub struct DynamicSearch<C, P, const N: usize> {
graph: DynamicGraph<C, N>,
is_goal: P,
labels: Vec<Label<C, N>>,
sets: Vec<Vec<usize>>,
via: Vec<Vec<usize>>,
stats: Stats,
}
impl<C: Cost, P: Fn(&u32) -> bool, const N: usize> DynamicSearch<C, P, N> {
pub fn new(graph: DynamicGraph<C, N>, start: u32, is_goal: P) -> Self {
let mut search = Self {
sets: alloc::vec![Vec::new(); graph.node_count()],
via: alloc::vec![Vec::new(); graph.edges.len()],
graph,
is_goal,
labels: Vec::new(),
stats: Stats::default(),
};
let root = search
.insert(start, [C::ZERO; N], None, None)
.expect("the first label");
search.propagate(VecDeque::from([root]));
search
}
pub const fn graph(&self) -> &DynamicGraph<C, N> {
&self.graph
}
pub const fn stats(&self) -> Stats {
self.stats
}
pub fn set_cost(&mut self, id: usize, cost: [C; N]) {
let edge = self.graph.edges[id].as_mut().expect("an existing edge");
edge.2 = cost;
let head = edge.1;
self.repair(id, head);
}
pub fn remove_edge(&mut self, id: usize) {
let (_, head, _) = self.graph.edges[id].take().expect("an existing edge");
self.repair(id, head);
}
pub fn add_edge(&mut self, from: u32, to: u32, cost: [C; N]) -> usize {
let id = self.graph.add_edge(from, to, cost);
self.via.push(Vec::new());
self.repair(id, to);
id
}
#[must_use]
pub fn front(&self) -> Output<u32, [C; N]> {
let mut ends: Vec<usize> = (0..self.sets.len())
.filter(|&s| (self.is_goal)(&u32::try_from(s).expect("state index")))
.flat_map(|s| self.sets[s].iter().copied())
.collect();
ends.sort_by_key(|&l| self.labels[l].cost);
let mut front = Front::new();
Output {
solutions: ends
.into_iter()
.filter(|&l| front.insert(self.labels[l].cost))
.map(|l| self.solution(l))
.collect(),
stats: self.stats,
}
}
fn repair(&mut self, id: usize, head: u32) {
let mut affected = BTreeSet::from([head]);
for root in core::mem::take(&mut self.via[id]) {
self.kill(root, &mut affected);
}
let mut queue = VecDeque::new();
for &target in &affected {
for &e in &self.graph.into[index(target)].clone() {
let Some((from, to, w)) = self.graph.edges[e] else {
continue;
};
if (self.is_goal)(&from) {
continue;
}
for l in self.sets[index(from)].clone() {
let cost = add(self.labels[l].cost, w);
if let Some(new) = self.insert(to, cost, Some(l), Some(e)) {
queue.push_back(new);
}
}
}
}
self.propagate(queue);
}
fn kill(&mut self, root: usize, affected: &mut BTreeSet<u32>) {
let mut stack = alloc::vec![root];
while let Some(l) = stack.pop() {
let label = &mut self.labels[l];
if label.alive {
label.alive = false;
let state = label.state;
self.sets[index(state)].retain(|&k| k != l);
affected.insert(state);
}
stack.append(&mut self.labels[l].children);
}
}
fn insert(
&mut self,
state: u32,
cost: [C; N],
parent: Option<usize>,
via: Option<usize>,
) -> Option<usize> {
let set = &self.sets[index(state)];
if set
.iter()
.any(|&k| weakly_dominates(&self.labels[k].cost, &cost))
{
return None;
}
let labels = &mut self.labels;
self.sets[index(state)].retain(|&k| {
let dominated = weakly_dominates(&cost, &labels[k].cost);
if dominated {
labels[k].alive = false;
}
!dominated
});
let id = self.labels.len();
self.labels.push(Label {
state,
cost,
parent,
alive: true,
children: Vec::new(),
});
self.sets[index(state)].push(id);
if let Some(p) = parent {
self.labels[p].children.push(id);
}
if let Some(e) = via {
self.via[e].push(id);
}
self.stats.generated += 1;
Some(id)
}
fn propagate(&mut self, mut queue: VecDeque<usize>) {
while let Some(l) = queue.pop_front() {
let (state, cost) = (self.labels[l].state, self.labels[l].cost);
if !self.labels[l].alive || (self.is_goal)(&state) {
continue;
}
self.stats.expanded += 1;
for &e in &self.graph.out[index(state)].clone() {
let Some((_, to, w)) = self.graph.edges[e] else {
continue;
};
if let Some(new) = self.insert(to, add(cost, w), Some(l), Some(e)) {
queue.push_back(new);
}
}
}
}
fn solution(&self, l: usize) -> Solution<u32, [C; N]> {
let mut path = Vec::new();
let mut at = Some(l);
while let Some(i) = at {
path.push(self.labels[i].state);
at = self.labels[i].parent;
}
path.reverse();
Solution {
cost: self.labels[l].cost,
path,
}
}
}