Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/kleene

crates/kleene-sparse/src/matrix.rs

use arrow_array::{Array, UInt32Array, UInt64Array};
use arrow_buffer::ScalarBuffer;

use crate::semiring::{Semiring, Value};
use crate::{Result, SparseError};

/// Where the entries of a sparse matrix are, with no values: offsets per row (or column)
/// and the index of each entry. A structural mask is a pattern.
#[derive(Clone, Debug)]
pub struct Pattern {
    major: usize,
    minor: usize,
    offsets: ScalarBuffer<u64>,
    indices: ScalarBuffer<u32>,
}

impl Pattern {
    /// Check and wrap `offsets` (`major + 1` values rising from 0 to the entry count) and
    /// `indices` (each below `minor`). Nothing is copied.
    pub fn new(
        major: usize,
        minor: usize,
        offsets: ScalarBuffer<u64>,
        indices: ScalarBuffer<u32>,
        what: &'static str,
    ) -> Result<Self> {
        if offsets.len() != major + 1 {
            return Err(SparseError::BadOffsets {
                what,
                why: format!("are {} values, {} wanted", offsets.len(), major + 1),
            });
        }
        if offsets[0] != 0 {
            return Err(SparseError::BadOffsets {
                what,
                why: "do not start at 0".into(),
            });
        }
        if offsets.windows(2).any(|w| w[0] > w[1]) {
            return Err(SparseError::BadOffsets {
                what,
                why: "fall".into(),
            });
        }
        if offsets[major] != indices.len() as u64 {
            return Err(SparseError::BadOffsets {
                what,
                why: format!(
                    "end at {}, there are {} entries",
                    offsets[major],
                    indices.len()
                ),
            });
        }
        if let Some(&i) = indices.iter().find(|&&i| i as usize >= minor) {
            return Err(SparseError::IndexOutOfRange {
                what,
                index: i as u64,
                dim: minor as u64,
            });
        }
        Ok(Pattern {
            major,
            minor,
            offsets,
            indices,
        })
    }

    /// Wrap buffers another reader has already checked (graph-ar checks every edge type
    /// it maps), skipping the scan of every index. Only the lengths are checked: offsets
    /// that fall or indices out of range give wrong answers or a panic later, never
    /// undefined behaviour.
    pub fn trusted(
        major: usize,
        minor: usize,
        offsets: ScalarBuffer<u64>,
        indices: ScalarBuffer<u32>,
        what: &'static str,
    ) -> Result<Self> {
        if offsets.len() != major + 1 || offsets[major] != indices.len() as u64 {
            return Err(SparseError::BadOffsets {
                what,
                why: format!(
                    "are {} values ending at {:?} for {major} rows and {} entries",
                    offsets.len(),
                    offsets.last(),
                    indices.len()
                ),
            });
        }
        Ok(Pattern {
            major,
            minor,
            offsets,
            indices,
        })
    }

    /// The number of rows (columns for a [`Csc`]).
    pub fn major(&self) -> usize {
        self.major
    }

    /// The number of columns (rows for a [`Csc`]).
    pub fn minor(&self) -> usize {
        self.minor
    }

    /// The number of entries.
    pub fn nnz(&self) -> usize {
        self.indices.len()
    }

    /// The offsets.
    pub fn offsets(&self) -> &ScalarBuffer<u64> {
        &self.offsets
    }

    /// The index of each entry.
    pub fn indices(&self) -> &ScalarBuffer<u32> {
        &self.indices
    }

    /// The entry range of row `i`.
    #[inline]
    pub fn range(&self, i: usize) -> std::ops::Range<usize> {
        self.offsets[i] as usize..self.offsets[i + 1] as usize
    }

    /// The indices of row `i`.
    #[inline]
    pub fn row(&self, i: usize) -> &[u32] {
        &self.indices[self.range(i)]
    }
}

/// A sparse matrix in compressed rows: row `i`'s entries are `indices[offsets[i]..offsets[i+1]]`
/// (their columns, rising within a row when built here) with `values` at the same places,
/// or no values (structural: every entry is the semiring's one).
#[derive(Clone, Debug)]
pub struct Csr<T: Value> {
    pattern: Pattern,
    values: Option<ScalarBuffer<T>>,
}

impl<T: Value> Csr<T> {
    /// A matrix from its buffers (Arrow's shared buffers: nothing is copied).
    pub fn new(
        nrows: usize,
        ncols: usize,
        offsets: ScalarBuffer<u64>,
        indices: ScalarBuffer<u32>,
        values: Option<ScalarBuffer<T>>,
    ) -> Result<Self> {
        let pattern = Pattern::new(nrows, ncols, offsets, indices, "csr")?;
        Self::with_pattern(pattern, values)
    }

    /// A matrix on a pattern, with values at its entries or none.
    pub fn with_pattern(pattern: Pattern, values: Option<ScalarBuffer<T>>) -> Result<Self> {
        if let Some(v) = &values
            && v.len() != pattern.nnz()
        {
            return Err(SparseError::Length {
                what: "csr values",
                want: pattern.nnz(),
                got: v.len(),
            });
        }
        Ok(Csr { pattern, values })
    }

    /// A structural matrix from Arrow columns: `u64` offsets and `u32` column indices, read
    /// in place (the arrays' buffers are shared, not copied).
    pub fn from_arrow(
        nrows: usize,
        ncols: usize,
        offsets: &UInt64Array,
        indices: &UInt32Array,
    ) -> Result<Self> {
        if offsets.null_count() > 0 || indices.null_count() > 0 {
            return Err(SparseError::BadOffsets {
                what: "csr from arrow",
                why: "hold nulls".into(),
            });
        }
        Self::new(
            nrows,
            ncols,
            offsets.values().clone(),
            indices.values().clone(),
            None,
        )
    }

    /// A matrix from an edge list (`src[k]` to `dst[k]`, value `values[k]` or structural).
    /// Entries are grouped by row with a counting sort; within a row the columns rise and a
    /// repeated (row, column) pair keeps one entry, its values folded with `add`.
    pub fn from_edges<S: Semiring<T = T>>(
        nrows: usize,
        ncols: usize,
        src: &[u32],
        dst: &[u32],
        values: Option<&[T]>,
        s: S,
    ) -> Result<Self> {
        if src.len() != dst.len() {
            return Err(SparseError::Length {
                what: "edge list",
                want: src.len(),
                got: dst.len(),
            });
        }
        if let Some(v) = values
            && v.len() != src.len()
        {
            return Err(SparseError::Length {
                what: "edge values",
                want: src.len(),
                got: v.len(),
            });
        }
        for (list, dim, what) in [(src, nrows, "edge source"), (dst, ncols, "edge target")] {
            if let Some(&i) = list.iter().find(|&&i| i as usize >= dim) {
                return Err(SparseError::IndexOutOfRange {
                    what,
                    index: i as u64,
                    dim: dim as u64,
                });
            }
        }
        let mut counts = vec![0u64; nrows + 1];
        for &r in src {
            counts[r as usize + 1] += 1;
        }
        for i in 0..nrows {
            counts[i + 1] += counts[i];
        }
        let mut next = counts.clone();
        let mut idx = vec![0u32; src.len()];
        let mut val: Vec<T> = values
            .map(|_| vec![s.zero(); src.len()])
            .unwrap_or_default();
        for k in 0..src.len() {
            let p = &mut next[src[k] as usize];
            idx[*p as usize] = dst[k];
            if let Some(v) = values {
                val[*p as usize] = v[k];
            }
            *p += 1;
        }
        // Sort each row by column and fold repeats.
        let mut out_off = Vec::with_capacity(nrows + 1);
        out_off.push(0u64);
        let mut out_idx = Vec::with_capacity(idx.len());
        let mut out_val = Vec::with_capacity(val.len());
        let mut row: Vec<(u32, T)> = Vec::new();
        for i in 0..nrows {
            let (a, b) = (counts[i] as usize, counts[i + 1] as usize);
            row.clear();
            for k in a..b {
                row.push((idx[k], if values.is_some() { val[k] } else { s.one() }));
            }
            row.sort_unstable_by_key(|e| e.0);
            for &(c, v) in &row {
                match out_idx.last() {
                    Some(&last) if out_idx.len() as u64 > *out_off.last().unwrap() && last == c => {
                        if values.is_some() {
                            let l = out_val.len() - 1;
                            out_val[l] = s.add(out_val[l], v);
                        }
                    }
                    _ => {
                        out_idx.push(c);
                        if values.is_some() {
                            out_val.push(v);
                        }
                    }
                }
            }
            out_off.push(out_idx.len() as u64);
        }
        Self::new(
            nrows,
            ncols,
            ScalarBuffer::from(out_off),
            ScalarBuffer::from(out_idx),
            values.map(|_| ScalarBuffer::from(out_val)),
        )
    }

    /// This structural matrix grown to `nrows` by `ncols` (at least its size) with the
    /// entries `src[k]`, `dst[k]` added: each row its old columns merged with its new ones
    /// (an entry already there, or repeated, kept once), so the old entries are copied
    /// once and only the new ones are sorted. Refused for a matrix with values.
    pub fn with_entries(
        &self,
        nrows: usize,
        ncols: usize,
        src: &[u32],
        dst: &[u32],
    ) -> Result<Self> {
        self.with_changes(nrows, ncols, (src, dst), (&[], &[]))
    }

    /// This structural matrix grown to `nrows` by `ncols` (at least its size) with the
    /// entries `add` (`add.0[k]`, `add.1[k]`) added and the entries `remove` taken out:
    /// each row its old columns merged with its new ones and its removed ones left out (an
    /// entry both added and removed is out; one removed that is not there changes nothing;
    /// a repeated one counts once), the old entries copied once and only the changed ones
    /// sorted. Refused for a matrix with values.
    pub fn with_changes(
        &self,
        nrows: usize,
        ncols: usize,
        add: (&[u32], &[u32]),
        remove: (&[u32], &[u32]),
    ) -> Result<Self> {
        if self.values.is_some() {
            return Err(SparseError::Length {
                what: "values of a matrix changed by entries (structural only)",
                want: 0,
                got: self.nnz(),
            });
        }
        if nrows < self.nrows() || ncols < self.ncols() {
            return Err(SparseError::Length {
                what: "rows and columns of a grown matrix",
                want: self.nrows().max(self.ncols()),
                got: nrows.min(ncols),
            });
        }
        let new = Self::sorted_rows(nrows, ncols, add.0, add.1)?;
        let gone = Self::sorted_rows(nrows, ncols, remove.0, remove.1)?;
        let mut off = Vec::with_capacity(nrows + 1);
        off.push(0u64);
        let mut out: Vec<u32> = Vec::with_capacity(self.nnz() + add.0.len());
        for i in 0..nrows {
            let old: &[u32] = if i < self.nrows() { self.row(i) } else { &[] };
            let (plus, minus) = (new.row(i), gone.row(i));
            let (mut a, mut b, mut m) = (0, 0, 0);
            let start = out.len();
            while a < old.len() || b < plus.len() {
                let c = match (old.get(a), plus.get(b)) {
                    (Some(&x), Some(&y)) if x <= y => {
                        a += 1;
                        if x == y {
                            b += 1;
                        }
                        x
                    }
                    (Some(_), Some(&y)) | (None, Some(&y)) => {
                        b += 1;
                        y
                    }
                    (Some(&x), None) => {
                        a += 1;
                        x
                    }
                    (None, None) => unreachable!("one row has more"),
                };
                while m < minus.len() && minus[m] < c {
                    m += 1;
                }
                if m < minus.len() && minus[m] == c {
                    continue;
                }
                if out.len() == start || out[out.len() - 1] != c {
                    out.push(c);
                }
            }
            off.push(out.len() as u64);
        }
        Self::new(
            nrows,
            ncols,
            ScalarBuffer::from(off),
            ScalarBuffer::from(out),
            None,
        )
    }

    /// The entries `src[k]`, `dst[k]` as a structural `nrows` by `ncols` matrix, each row's
    /// columns sorted (a repeated entry kept as often as given).
    fn sorted_rows(nrows: usize, ncols: usize, src: &[u32], dst: &[u32]) -> Result<Self> {
        if src.len() != dst.len() {
            return Err(SparseError::Length {
                what: "edge list",
                want: src.len(),
                got: dst.len(),
            });
        }
        for (list, dim, what) in [(src, nrows, "edge source"), (dst, ncols, "edge target")] {
            if let Some(&i) = list.iter().find(|&&i| i as usize >= dim) {
                return Err(SparseError::IndexOutOfRange {
                    what,
                    index: i as u64,
                    dim: dim as u64,
                });
            }
        }
        let (mut counts, mut idx) = (vec![0u64; nrows + 1], vec![0u32; src.len()]);
        for &r in src {
            counts[r as usize + 1] += 1;
        }
        for i in 0..nrows {
            counts[i + 1] += counts[i];
        }
        let mut next = counts.clone();
        for k in 0..src.len() {
            let p = &mut next[src[k] as usize];
            idx[*p as usize] = dst[k];
            *p += 1;
        }
        for i in 0..nrows {
            idx[counts[i] as usize..counts[i + 1] as usize].sort_unstable();
        }
        Ok(Csr {
            pattern: Pattern {
                major: nrows,
                minor: ncols,
                offsets: ScalarBuffer::from(counts),
                indices: ScalarBuffer::from(idx),
            },
            values: None,
        })
    }

    /// An `n` by `n` matrix with one entry on each diagonal place in `diag`.
    pub fn diagonal(n: usize, diag: &[u32]) -> Result<Self> {
        let mut sorted: Vec<u32> = diag.to_vec();
        sorted.sort_unstable();
        sorted.dedup();
        let mut offsets = Vec::with_capacity(n + 1);
        offsets.push(0u64);
        let mut k = 0;
        for i in 0..n {
            while k < sorted.len() && sorted[k] as usize == i {
                k += 1;
            }
            offsets.push(k as u64);
        }
        Self::new(
            n,
            n,
            ScalarBuffer::from(offsets),
            ScalarBuffer::from(sorted),
            None,
        )
    }

    /// The number of rows.
    pub fn nrows(&self) -> usize {
        self.pattern.major
    }

    /// The number of columns.
    pub fn ncols(&self) -> usize {
        self.pattern.minor
    }

    /// The number of entries.
    pub fn nnz(&self) -> usize {
        self.pattern.nnz()
    }

    /// Where the entries are.
    pub fn pattern(&self) -> &Pattern {
        &self.pattern
    }

    /// The values, or none for a structural matrix.
    pub fn values(&self) -> Option<&ScalarBuffer<T>> {
        self.values.as_ref()
    }

    /// The columns of row `i`.
    #[inline]
    pub fn row(&self, i: usize) -> &[u32] {
        self.pattern.row(i)
    }

    /// The value at entry position `k` (the semiring's one when structural).
    #[inline]
    pub fn value_at<S: Semiring<T = T>>(&self, k: usize, s: S) -> T {
        match &self.values {
            Some(v) => v[k],
            None => s.one(),
        }
    }

    /// The entry at (`i`, `j`), if there is one (a binary search when the row's columns
    /// rise, a scan otherwise).
    pub fn get<S: Semiring<T = T>>(&self, i: usize, j: u32, s: S) -> Option<T> {
        let r = self.pattern.range(i);
        let cols = &self.pattern.indices[r.clone()];
        let pos = if cols.windows(2).all(|w| w[0] < w[1]) {
            cols.binary_search(&j).ok()
        } else {
            cols.iter().position(|&c| c == j)
        }?;
        Some(self.value_at(r.start + pos, s))
    }

    /// Every entry as (row, column, value), row by row.
    pub fn triples<S: Semiring<T = T>>(&self, s: S) -> Vec<(u32, u32, T)> {
        let mut out = Vec::with_capacity(self.nnz());
        for i in 0..self.nrows() {
            for k in self.pattern.range(i) {
                out.push((i as u32, self.pattern.indices[k], self.value_at(k, s)));
            }
        }
        out
    }

    /// The transpose, in compressed rows (a counting sort; the rows of the result rise).
    pub fn transpose(&self) -> Self {
        let (nr, nc) = (self.nrows(), self.ncols());
        let mut counts = vec![0u64; nc + 1];
        for &c in self.pattern.indices.iter() {
            counts[c as usize + 1] += 1;
        }
        for j in 0..nc {
            counts[j + 1] += counts[j];
        }
        let mut next = counts.clone();
        let mut idx = vec![0u32; self.nnz()];
        let mut val: Vec<T> = match &self.values {
            Some(v) if !v.is_empty() => vec![v[0]; self.nnz()],
            _ => Vec::new(),
        };
        for i in 0..nr {
            for k in self.pattern.range(i) {
                let c = self.pattern.indices[k] as usize;
                let p = next[c] as usize;
                idx[p] = i as u32;
                if let Some(v) = &self.values {
                    val[p] = v[k];
                }
                next[c] += 1;
            }
        }
        Csr {
            pattern: Pattern {
                major: nc,
                minor: nr,
                offsets: ScalarBuffer::from(counts),
                indices: ScalarBuffer::from(idx),
            },
            values: self.values.as_ref().map(|_| ScalarBuffer::from(val)),
        }
    }
}

/// A sparse matrix in compressed columns: the same layout as [`Csr`], read by column (it
/// holds the compressed rows of the transpose). A graph stored by destination is a CSC of
/// its adjacency with no copy.
#[derive(Clone, Debug)]
pub struct Csc<T: Value> {
    t: Csr<T>,
}

impl<T: Value> Csc<T> {
    /// A matrix from its column buffers: `offsets` over the columns, `indices` the rows.
    pub fn new(
        nrows: usize,
        ncols: usize,
        offsets: ScalarBuffer<u64>,
        indices: ScalarBuffer<u32>,
        values: Option<ScalarBuffer<T>>,
    ) -> Result<Self> {
        Ok(Csc {
            t: Csr::new(ncols, nrows, offsets, indices, values)?,
        })
    }

    /// The same matrix in compressed columns (a transpose of the storage).
    pub fn from_csr(a: &Csr<T>) -> Self {
        Csc { t: a.transpose() }
    }

    /// The same matrix in compressed rows.
    pub fn to_csr(&self) -> Csr<T> {
        self.t.transpose()
    }

    /// The compressed rows of the transpose (the storage itself; no copy).
    pub fn transposed(&self) -> &Csr<T> {
        &self.t
    }

    /// The number of rows.
    pub fn nrows(&self) -> usize {
        self.t.ncols()
    }

    /// The number of columns.
    pub fn ncols(&self) -> usize {
        self.t.nrows()
    }

    /// The rows of column `j`.
    pub fn col(&self, j: usize) -> &[u32] {
        self.t.row(j)
    }
}

/// A structural mask over a matrix: the entries of a pattern, or (complemented) every
/// place that is not one.
#[derive(Clone, Debug)]
pub struct MatrixMask {
    /// The pattern.
    pub pattern: Pattern,
    /// True to allow the places the pattern does not hold.
    pub complement: bool,
}

impl MatrixMask {
    /// The places of `pattern`.
    pub fn new(pattern: Pattern) -> Self {
        MatrixMask {
            pattern,
            complement: false,
        }
    }

    /// The other places.
    pub fn complement(mut self) -> Self {
        self.complement = !self.complement;
        self
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{BoolOrAnd, PlusTimes};

    #[test]
    fn from_edges_groups_rows_sorts_columns_and_folds_repeats() {
        let s = PlusTimes::<u32>::new();
        let a = Csr::from_edges(
            3,
            3,
            &[2, 0, 0, 2, 0],
            &[1, 2, 1, 1, 2],
            Some(&[1, 2, 3, 4, 5]),
            s,
        )
        .unwrap();
        assert_eq!(a.nnz(), 3);
        assert_eq!(a.row(0), &[1, 2]);
        assert_eq!(a.get(0, 2, s), Some(7));
        assert_eq!(a.get(2, 1, s), Some(5));
        assert_eq!(a.get(1, 0, s), None);
    }

    #[test]
    fn from_arrow_shares_the_buffers() {
        let off = UInt64Array::from(vec![0u64, 2, 2, 3]);
        let idx = UInt32Array::from(vec![1u32, 2, 0]);
        let a: Csr<u8> = Csr::from_arrow(3, 3, &off, &idx).unwrap();
        assert_eq!(a.pattern().indices().as_ptr(), idx.values().as_ptr());
        assert_eq!(a.get(2, 0, BoolOrAnd), Some(1));
    }

    #[test]
    fn bad_offsets_and_indices_are_refused() {
        let bad = |o: Vec<u64>, i: Vec<u32>| {
            Csr::<u8>::new(2, 2, ScalarBuffer::from(o), ScalarBuffer::from(i), None).is_err()
        };
        assert!(bad(vec![0, 1], vec![0]));
        assert!(bad(vec![1, 1, 1], vec![0]));
        assert!(bad(vec![0, 2, 1], vec![0, 1]));
        assert!(bad(vec![0, 1, 2], vec![0]));
        assert!(bad(vec![0, 1, 1], vec![5]));
    }

    #[test]
    fn transpose_and_csc_agree() {
        let s = PlusTimes::<u32>::new();
        let a = Csr::from_edges(2, 3, &[0, 0, 1], &[0, 2, 2], Some(&[1, 2, 3]), s).unwrap();
        let t = a.transpose();
        assert_eq!((t.nrows(), t.ncols()), (3, 2));
        assert_eq!(t.row(2), &[0, 1]);
        assert_eq!(t.get(2, 1, s), Some(3));
        let c = Csc::from_csr(&a);
        assert_eq!(c.col(2), &[0, 1]);
        assert_eq!(c.to_csr().triples(s), a.triples(s));
    }
}