crates/kleene-graph/src/closure.rs
use std::borrow::Cow;
use kleene_sparse::{BoolOrAnd, Csr, MatrixMask, SparseBackend};
use crate::GraphError;
/// Where the closure's recursion sits.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Side {
/// `t = base · e*`: pairs grow at their far end (`t(X,Z) :- t(X,Y), e(Y,Z)`).
Right,
/// `t = e* · base`: pairs grow at their near end (`t(X,Z) :- e(X,Y), t(Y,Z)`).
Left,
}
/// A closure and how it went.
#[derive(Clone, Debug)]
pub struct Closure {
/// The pairs, as a structural matrix.
pub pairs: Csr<u8>,
/// Products until no new pair.
pub rounds: u32,
/// The new pairs of each product (the last is 0 when the closure ended by itself).
pub grown: Vec<usize>,
}
/// The pairs `base` grows to along `edges` (both square, the same size): semi-naive
/// boolean products, each masked by the complement of the pairs already known, so a round
/// computes only new pairs. Each pair is in the answer once, its rows' columns rising,
/// whatever repeats or order the operands' rows hold (parallel edges).
pub fn closure<B: SparseBackend>(
base: &Csr<u8>,
edges: &Csr<u8>,
side: Side,
device: &B::Device,
) -> crate::Result<Closure> {
let n = edges.nrows();
if edges.ncols() != n || base.nrows() != n || base.ncols() != n {
return Err(GraphError::NotSquare {
rows: base.nrows(),
cols: base.ncols(),
});
}
let s = BoolOrAnd;
let e = B::matrix(strictly_rising(edges)?.into_owned(), device);
let bm = B::matrix(strictly_rising(base)?.into_owned(), device);
let mut total = bm.clone();
let mut delta = bm;
let mut rounds = 0u32;
let mut grown = Vec::new();
while B::nnz(&delta) > 0 {
let known = MatrixMask::new(B::matrix_to_host(&total).pattern().clone()).complement();
let next = match side {
Side::Right => B::mxm(&delta, &e, Some(&known), s, device)?,
Side::Left => B::mxm(&e, &delta, Some(&known), s, device)?,
};
rounds += 1;
grown.push(B::nnz(&next));
if B::nnz(&next) == 0 {
break;
}
total = B::ewise_add_matrix(&total, &next, s, device)?;
delta = next;
}
Ok(Closure {
pairs: B::matrix_to_host(&total).pattern().to_structural(),
rounds,
grown,
})
}
/// `m` with each row's columns rising and each once: `m` itself when it already is, else
/// rebuilt from its entries (repeats folded with `or`).
pub(crate) fn strictly_rising(m: &Csr<u8>) -> crate::Result<Cow<'_, Csr<u8>>> {
if (0..m.nrows()).all(|i| m.row(i).windows(2).all(|w| w[0] < w[1])) {
return Ok(Cow::Borrowed(m));
}
let t = m.triples(BoolOrAnd);
let (src, dst): (Vec<u32>, Vec<u32>) = t.iter().map(|e| (e.0, e.1)).unzip();
let vals: Option<Vec<u8>> = m.values().map(|_| t.iter().map(|e| e.2).collect());
Ok(Cow::Owned(Csr::from_edges(
m.nrows(),
m.ncols(),
&src,
&dst,
vals.as_deref(),
BoolOrAnd,
)?))
}