use alloc::vec;
use alloc::vec::Vec;
use super::Stnu;
use crate::budget::Meter;
use crate::dispatch::{DispatchEdge, DispatchableNetwork, PointKind, Wait};
use crate::stn::steps;
use crate::{Budget, Error, Ticks, TimePoint};
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct Estnu {
pub(super) n: usize,
pub(super) k: usize,
pub(super) ordinary: Vec<Option<Ticks>>,
pub(super) waits: Vec<Option<Ticks>>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Kind {
Ordinary,
Lower(usize),
Upper(usize),
}
#[derive(Debug, Clone, Copy)]
struct InEdge {
from: usize,
weight: Ticks,
kind: Kind,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Status {
Unvisited,
Active,
Done,
}
struct Graph<'s, 'm> {
stnu: &'s Stnu,
incoming: Vec<Vec<InEdge>>,
negative: Vec<bool>,
status: Vec<Status>,
activates: Vec<Vec<usize>>,
out: Estnu,
meter: &'m mut Meter,
}
struct Search {
dist: Vec<Option<Ticks>>,
settled: Vec<bool>,
}
pub(super) fn run(stnu: &Stnu, budget: &Budget) -> Result<Option<Estnu>, Error> {
let mut meter = budget.meter();
let mut g = Graph::new(stnu, budget, &mut meter)?;
for x in 0..g.incoming.len() {
if g.negative[x] && !g.process(x)? {
return Ok(None);
}
}
Ok(Some(g.out))
}
impl<'s, 'm> Graph<'s, 'm> {
fn new(stnu: &'s Stnu, budget: &Budget, meter: &'m mut Meter) -> Result<Self, Error> {
let (points, links) = (stnu.time_point_count(), stnu.links.len());
let nn = points
.checked_mul(points)
.ok_or(Error::MemoryBudgetExceeded)?;
let nk = points
.checked_mul(links)
.ok_or(Error::MemoryBudgetExceeded)?;
budget.check_cells(nn.checked_add(nk).ok_or(Error::MemoryBudgetExceeded)?)?;
meter.spend(steps(nn)?.saturating_add(steps(nk)?))?;
let mut g = Self {
stnu,
incoming: vec![Vec::new(); points],
negative: vec![false; points],
status: vec![Status::Unvisited; points],
activates: vec![Vec::new(); points],
out: Estnu {
n: points,
k: links,
ordinary: vec![None; nn],
waits: vec![None; nk],
},
meter,
};
g.load_requirements()?;
g.load_links()?;
g.negative = g
.incoming
.iter()
.map(|edges| {
edges
.iter()
.any(|e| e.weight < Ticks::ZERO && !matches!(e.kind, Kind::Lower(_)))
})
.collect();
Ok(g)
}
fn load_requirements(&mut self) -> Result<(), Error> {
for c in self.stnu.requirements.constraints() {
if let Some(hi) = c.hi {
self.insert_ordinary(c.from.0, c.to.0, hi);
}
if let Some(lo) = c.lo {
let w = lo.checked_neg().ok_or(Error::Overflow)?;
self.insert_ordinary(c.to.0, c.from.0, w);
}
}
Ok(())
}
fn load_links(&mut self) -> Result<(), Error> {
for (i, link) in self.stnu.links.iter().enumerate() {
let (a, x) = (link.activation.0, link.contingent.0);
self.activates[a].push(i);
self.incoming[x].push(InEdge {
from: a,
weight: link.lo,
kind: Kind::Lower(i),
});
self.incoming[a].push(InEdge {
from: x,
weight: link.hi.checked_neg().ok_or(Error::Overflow)?,
kind: Kind::Upper(i),
});
}
Ok(())
}
fn process(&mut self, x: usize) -> Result<bool, Error> {
match self.status[x] {
Status::Active => return Ok(false),
Status::Done => return Ok(true),
Status::Unvisited => {}
}
self.status[x] = Status::Active;
for c in self.activates[x].clone() {
if !self.pass(x, Some(c))? {
return Ok(false);
}
}
if !self.pass(x, None)? {
return Ok(false);
}
self.status[x] = Status::Done;
Ok(true)
}
fn pass(&mut self, x: usize, label: Option<usize>) -> Result<bool, Error> {
let mut search = self.seed(x, label)?;
while let Some((u, d)) = search.pop(self.meter)? {
if d >= Ticks::ZERO {
self.insert_ordinary(u, x, d);
continue;
}
if self.negative[u] && !self.process(u)? {
return Ok(false);
}
if !self.record_negative(x, label, u, d) {
continue;
}
self.extend(&mut search, x, label, u, d)?;
}
Ok(true)
}
fn seed(&self, x: usize, label: Option<usize>) -> Result<Search, Error> {
let n = self.incoming.len();
let mut search = Search {
dist: vec![None; n],
settled: vec![false; n],
};
if let Some(c) = label {
let link = &self.stnu.links[c];
let w = link.hi.checked_neg().ok_or(Error::Overflow)?;
search.relax(link.contingent.0, w);
return Ok(search);
}
for e in &self.incoming[x] {
if e.kind == Kind::Ordinary && e.weight < Ticks::ZERO {
search.relax(e.from, e.weight);
}
}
Ok(search)
}
fn record_negative(&mut self, x: usize, label: Option<usize>, u: usize, d: Ticks) -> bool {
let Some(c) = label else {
if !self.is_contingent_of(u, x) {
self.insert_ordinary(u, x, d);
}
return true;
};
let link = self.stnu.links[c];
if u == link.contingent.0 {
return true;
}
if d.0 >= -link.lo.0 {
self.insert_ordinary(u, x, d);
return false;
}
lower(&mut self.out.waits[u * self.out.k + c], d);
true
}
fn extend(
&mut self,
search: &mut Search,
x: usize,
label: Option<usize>,
u: usize,
d: Ticks,
) -> Result<(), Error> {
self.meter.spend(steps(self.incoming[u].len())?)?;
for e in &self.incoming[u] {
let unsuitable = match e.kind {
Kind::Upper(_) => true,
Kind::Lower(c) => label == Some(c) && e.from == x,
Kind::Ordinary => false,
};
if unsuitable || e.weight < Ticks::ZERO {
continue;
}
search.relax(e.from, d.checked_add(e.weight).ok_or(Error::Overflow)?);
}
Ok(())
}
fn is_contingent_of(&self, u: usize, x: usize) -> bool {
self.activates[x]
.iter()
.any(|&c| self.stnu.links[c].contingent.0 == u)
}
fn insert_ordinary(&mut self, from: usize, to: usize, weight: Ticks) {
if from == to {
if weight < Ticks::ZERO {
self.incoming[to].push(InEdge {
from,
weight,
kind: Kind::Ordinary,
});
}
return;
}
let cell = &mut self.out.ordinary[from * self.out.n + to];
if cell.is_none_or(|w| weight < w) {
*cell = Some(weight);
self.incoming[to].push(InEdge {
from,
weight,
kind: Kind::Ordinary,
});
}
}
}
impl Search {
fn pop(&mut self, meter: &mut Meter) -> Result<Option<(usize, Ticks)>, Error> {
meter.spend(steps(self.dist.len())?)?;
let mut best: Option<(usize, Ticks)> = None;
for (u, (d, settled)) in self.dist.iter().zip(&self.settled).enumerate() {
if let (Some(d), false) = (*d, *settled) {
if best.is_none_or(|(_, b)| d < b) {
best = Some((u, d));
}
}
}
if let Some((u, _)) = best {
self.settled[u] = true;
}
Ok(best)
}
fn relax(&mut self, v: usize, d: Ticks) {
if !self.settled[v] && self.dist[v].is_none_or(|old| d < old) {
self.dist[v] = Some(d);
}
}
}
fn lower(cell: &mut Option<Ticks>, value: Ticks) {
if cell.is_none_or(|d| value < d) {
*cell = Some(value);
}
}
impl Estnu {
pub(super) fn into_network(self, stnu: &Stnu) -> Result<DispatchableNetwork, Error> {
let points = point_kinds(stnu)?;
let mut edges = Vec::new();
for (i, w) in self.ordinary.iter().enumerate() {
if let Some(weight) = *w {
edges.try_reserve(1).map_err(|_| Error::OutOfMemory)?;
edges.push(DispatchEdge {
from: TimePoint(i / self.n),
to: TimePoint(i % self.n),
weight,
});
}
}
let mut waits = Vec::new();
for (c, link) in stnu.links.iter().enumerate() {
let a = link.activation.0;
for u in (0..self.n).filter(|&u| points[u] == PointKind::Executable) {
let Some(d) = self.waits[u * self.k + c] else {
continue;
};
if self.ordinary[u * self.n + a].is_none_or(|w| d < w) {
waits.try_reserve(1).map_err(|_| Error::OutOfMemory)?;
waits.push(Wait {
waiter: TimePoint(u),
contingent: link.contingent,
delay: d.checked_neg().ok_or(Error::Overflow)?,
});
}
}
}
Ok(DispatchableNetwork::new(points, edges, waits))
}
}
pub(super) fn point_kinds(stnu: &Stnu) -> Result<Vec<PointKind>, Error> {
let mut points = Vec::new();
points
.try_reserve_exact(stnu.time_point_count())
.map_err(|_| Error::OutOfMemory)?;
points.resize(stnu.time_point_count(), PointKind::Executable);
for link in &stnu.links {
points[link.contingent.0] = PointKind::Contingent {
activation: link.activation,
lo: link.lo,
hi: link.hi,
};
}
Ok(points)
}