crates/kleene-graph/src/propagate.rs
use kleene_sparse::{Semiring, SparseBackend};
/// The result of a propagation.
#[derive(Clone, Debug)]
pub struct Propagation<B: SparseBackend, T: kleene_sparse::Value> {
/// The value at every place reached.
pub values: B::Vector<T>,
/// Rounds until nothing changed (or the cap).
pub rounds: u32,
}
/// Propagate `init` along the rows of `a` until nothing changes: each round every place
/// that changed sends `v_i ⊗ a_ij` to its targets, and `v_j ⊕=` what arrives. Only changed
/// places are sent (semi-naive), so the rounds cost the edges of what changed. `⊕` must be
/// idempotent (or, min, union) for this to end; `max_rounds` caps it otherwise.
pub fn propagate<B: SparseBackend, S: Semiring>(
a: &B::Matrix<S::T>,
init: B::Vector<S::T>,
s: S,
max_rounds: Option<u32>,
device: &B::Device,
) -> crate::Result<Propagation<B, S::T>> {
propagate_with::<B, S, _>(a, init, s, max_rounds, |_, x| x, device)
}
/// [`propagate`] with each sent value first passed through `relabel(place, value)`: a
/// value can carry where it came from (shortest paths send `(distance, self)` and keep
/// `(distance, parent)`).
pub fn propagate_with<B: SparseBackend, S: Semiring, F>(
a: &B::Matrix<S::T>,
init: B::Vector<S::T>,
s: S,
max_rounds: Option<u32>,
relabel: F,
device: &B::Device,
) -> crate::Result<Propagation<B, S::T>>
where
F: Fn(u32, S::T) -> S::T + Sync,
{
let mut values = init.clone();
let mut frontier = B::apply_indexed(&init, &relabel);
let mut rounds = 0u32;
while B::nvals(&frontier) > 0 && max_rounds.is_none_or(|m| rounds < m) {
let arrived = B::vxm(&frontier, a, None, s, device)?;
let changed = B::accumulate(&mut values, &arrived, s)?;
frontier = B::apply_indexed(&changed, &relabel);
rounds += 1;
}
Ok(Propagation { values, rounds })
}