crates/kleene-graph/src/graph.rs
use std::fmt;
use kleene_sparse::{Csr, SparseBackend, SparseError};
/// Why a graph could not be built or searched.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum GraphError {
/// The sparse layer refused an operand.
Sparse(SparseError),
/// An adjacency matrix that is not square.
NotSquare {
/// Rows.
rows: usize,
/// Columns.
cols: usize,
},
/// A source vertex at or past the vertex count.
SourceOutOfRange {
/// The source.
source: u32,
/// The vertex count.
vertices: usize,
},
/// A pull step asked of a graph built without its transpose.
NoTranspose,
/// A vertex mask of the wrong length.
MaskLength {
/// The mask's length.
mask: usize,
/// The vertex count.
vertices: usize,
},
/// Edge sets that do not fit their graph or sources.
Labels(String),
/// Shortest paths asked of a range they do not have, or more of them than allowed.
Paths(String),
/// Walk counts asked with no bound on the length, or a count past `u64`.
Counts(String),
/// Edge weights a kernel refuses (a spanning forest's NaN, too many edges).
Weights(String),
/// A flow asked of a source and target it cannot run between.
Flow(String),
/// A split's key or edge lists that do not fit its graph.
Split(String),
/// Machine weights, slices or their messages that do not fit (see [`crate::Slices`]).
Slices(String),
/// More vertices than a kernel takes.
TooManyVertices {
/// The vertex count.
vertices: usize,
/// The kernel's limit.
limit: usize,
},
}
impl fmt::Display for GraphError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
GraphError::Sparse(e) => write!(f, "{e}"),
GraphError::NotSquare { rows, cols } => {
write!(
f,
"an adjacency matrix must be square, this one is {rows}x{cols}"
)
}
GraphError::SourceOutOfRange { source, vertices } => {
write!(f, "source {source} is outside {vertices} vertices")
}
GraphError::NoTranspose => {
write!(
f,
"a pull step needs the graph's in-edges (build it with them)"
)
}
GraphError::MaskLength { mask, vertices } => {
write!(f, "a vertex mask of {mask} for {vertices} vertices")
}
GraphError::Labels(m) => write!(f, "edge sets: {m}"),
GraphError::Paths(m) => write!(f, "shortest paths: {m}"),
GraphError::Counts(m) => write!(f, "walk counts: {m}"),
GraphError::Weights(m) => write!(f, "edge weights: {m}"),
GraphError::Flow(m) => write!(f, "maximum flow: {m}"),
GraphError::Split(m) => write!(f, "split: {m}"),
GraphError::Slices(m) => write!(f, "slices: {m}"),
GraphError::TooManyVertices { vertices, limit } => {
write!(
f,
"{vertices} vertices, more than the {limit} this kernel takes"
)
}
}
}
}
impl std::error::Error for GraphError {}
impl From<SparseError> for GraphError {
fn from(e: SparseError) -> Self {
GraphError::Sparse(e)
}
}
/// A directed graph on a backend: its adjacency (row `i` lists the targets of `i`'s edges)
/// and, for pull steps, its transpose (row `j` lists the sources of the edges into `j`).
/// Entries are structural: the graph says only where edges are.
#[derive(Clone, Debug)]
pub struct Graph<B: SparseBackend> {
out: B::Matrix<u8>,
inn: Option<B::Matrix<u8>>,
vertices: usize,
}
impl<B: SparseBackend> Graph<B> {
fn check(a: &Csr<u8>) -> crate::Result<usize> {
if a.nrows() != a.ncols() {
return Err(GraphError::NotSquare {
rows: a.nrows(),
cols: a.ncols(),
});
}
Ok(a.nrows())
}
/// A graph from its adjacency; the transpose is computed for pull steps.
pub fn new(out: Csr<u8>, device: &B::Device) -> crate::Result<Self> {
let vertices = Self::check(&out)?;
let out = B::matrix(out, device);
let inn = Some(B::transpose(&out, device));
Ok(Graph { out, inn, vertices })
}
/// A graph from its adjacency and its transpose as stored (a graph kept both by source
/// and by destination hands both over with no copy). The two are not compared.
pub fn with_transpose(out: Csr<u8>, inn: Csr<u8>, device: &B::Device) -> crate::Result<Self> {
let vertices = Self::check(&out)?;
if Self::check(&inn)? != vertices {
return Err(GraphError::NotSquare {
rows: inn.nrows(),
cols: vertices,
});
}
Ok(Graph {
out: B::matrix(out, device),
inn: Some(B::matrix(inn, device)),
vertices,
})
}
/// A graph that only pushes: no transpose is kept.
pub fn push_only(out: Csr<u8>, device: &B::Device) -> crate::Result<Self> {
let vertices = Self::check(&out)?;
Ok(Graph {
out: B::matrix(out, device),
inn: None,
vertices,
})
}
/// The number of vertices.
pub fn vertices(&self) -> usize {
self.vertices
}
/// The number of edges.
pub fn edges(&self) -> usize {
B::nnz(&self.out)
}
/// The adjacency.
pub fn out(&self) -> &B::Matrix<u8> {
&self.out
}
/// The transpose, if kept.
pub fn inn(&self) -> Option<&B::Matrix<u8>> {
self.inn.as_ref()
}
}