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/semiring.rs

use std::fmt::Debug;
use std::marker::PhantomData;

use arrow_buffer::ArrowNativeType;

/// A value a matrix or vector holds: any Arrow native type (so a column of values is an
/// Arrow buffer, shared with no copy).
pub trait Value: ArrowNativeType + PartialEq + Send + Sync + Debug + 'static {}

impl<T: ArrowNativeType + PartialEq + Send + Sync + Debug + 'static> Value for T {}

/// A semiring: the `add` and `mul` a sparse product folds with.
///
/// `zero` is `add`'s identity and annihilates `mul`; `one` is `mul`'s identity and the value
/// of every entry of a structural matrix (one that stores no values). An entry of a result
/// exists where at least one product was formed, whatever its value.
pub trait Semiring: Copy + Send + Sync + Debug + 'static {
    /// The values.
    type T: Value;
    /// The additive identity.
    fn zero(&self) -> Self::T;
    /// The multiplicative identity.
    fn one(&self) -> Self::T;
    /// Addition: associative and commutative.
    fn add(&self, a: Self::T, b: Self::T) -> Self::T;
    /// Multiplication: associative, distributes over `add`.
    fn mul(&self, a: Self::T, b: Self::T) -> Self::T;
    /// A value `add` never leaves (`add(t, x) == t` for every `x`), if there is one: a fold
    /// that reaches it may stop (or-and's true, a full bitset's union). None by default.
    fn terminal(&self) -> Option<Self::T> {
        None
    }
}

/// Booleans with `or` as add and `and` as mul, as Arrow's byte: 0 is false, anything else
/// is true; results are 0 or 1.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct BoolOrAnd;

impl Semiring for BoolOrAnd {
    type T = u8;
    #[inline]
    fn zero(&self) -> u8 {
        0
    }
    #[inline]
    fn one(&self) -> u8 {
        1
    }
    #[inline]
    fn add(&self, a: u8, b: u8) -> u8 {
        ((a != 0) | (b != 0)) as u8
    }
    #[inline]
    fn mul(&self, a: u8, b: u8) -> u8 {
        ((a != 0) & (b != 0)) as u8
    }
    #[inline]
    fn terminal(&self) -> Option<u8> {
        Some(1)
    }
}

/// Sets of up to 64 members as `u64` words: union as add, intersection as mul, so a
/// structural matrix (one = every bit) hands a bitset on unchanged (many sources at once).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct BitsetUnion;

impl Semiring for BitsetUnion {
    type T = u64;
    #[inline]
    fn zero(&self) -> u64 {
        0
    }
    #[inline]
    fn one(&self) -> u64 {
        u64::MAX
    }
    #[inline]
    fn add(&self, a: u64, b: u64) -> u64 {
        a | b
    }
    #[inline]
    fn mul(&self, a: u64, b: u64) -> u64 {
        a & b
    }
    #[inline]
    fn terminal(&self) -> Option<u64> {
        Some(u64::MAX)
    }
}

/// Numbers the tropical and arithmetic semirings are defined over.
pub trait Number: Value {
    /// The largest value: "no path" for min-plus.
    const MAX: Self;
    /// Zero.
    const ZERO: Self;
    /// One.
    const ONE: Self;
    /// Addition that stops at [`Number::MAX`].
    fn saturating(self, other: Self) -> Self;
    /// Addition (wrapping for integers).
    fn plus(self, other: Self) -> Self;
    /// Multiplication (wrapping for integers).
    fn times(self, other: Self) -> Self;
    /// The smaller of the two.
    fn least(self, other: Self) -> Self;
}

macro_rules! number_int {
    ($($t:ty),*) => {$(
        impl Number for $t {
            const MAX: Self = <$t>::MAX;
            const ZERO: Self = 0;
            const ONE: Self = 1;
            #[inline] fn saturating(self, o: Self) -> Self { self.saturating_add(o) }
            #[inline] fn plus(self, o: Self) -> Self { self.wrapping_add(o) }
            #[inline] fn times(self, o: Self) -> Self { self.wrapping_mul(o) }
            #[inline] fn least(self, o: Self) -> Self { self.min(o) }
        }
    )*};
}
number_int!(u8, u16, u32, u64, i32, i64);

macro_rules! number_float {
    ($($t:ty),*) => {$(
        impl Number for $t {
            const MAX: Self = <$t>::INFINITY;
            const ZERO: Self = 0.0;
            const ONE: Self = 1.0;
            #[inline] fn saturating(self, o: Self) -> Self { self + o }
            #[inline] fn plus(self, o: Self) -> Self { self + o }
            #[inline] fn times(self, o: Self) -> Self { self * o }
            #[inline] fn least(self, o: Self) -> Self { self.min(o) }
        }
    )*};
}
number_float!(f32, f64);

/// The tropical semiring: `min` as add, `+` as mul (shortest paths). Zero is the largest
/// value (infinity for floats), one is 0.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct MinPlus<T>(PhantomData<T>);

impl<T> MinPlus<T> {
    /// The semiring.
    pub const fn new() -> Self {
        MinPlus(PhantomData)
    }
}

impl<T: Number> Semiring for MinPlus<T> {
    type T = T;
    #[inline]
    fn zero(&self) -> T {
        T::MAX
    }
    #[inline]
    fn one(&self) -> T {
        T::ZERO
    }
    #[inline]
    fn add(&self, a: T, b: T) -> T {
        a.least(b)
    }
    #[inline]
    fn mul(&self, a: T, b: T) -> T {
        a.saturating(b)
    }
}

/// The arithmetic semiring: `+` as add, `*` as mul (counting, linear algebra).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct PlusTimes<T>(PhantomData<T>);

impl<T> PlusTimes<T> {
    /// The semiring.
    pub const fn new() -> Self {
        PlusTimes(PhantomData)
    }
}

impl<T: Number> Semiring for PlusTimes<T> {
    type T = T;
    #[inline]
    fn zero(&self) -> T {
        T::ZERO
    }
    #[inline]
    fn one(&self) -> T {
        T::ONE
    }
    #[inline]
    fn add(&self, a: T, b: T) -> T {
        a.plus(b)
    }
    #[inline]
    fn mul(&self, a: T, b: T) -> T {
        a.times(b)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn laws<S: Semiring>(s: S, xs: &[S::T]) {
        if let Some(t) = s.terminal() {
            for &a in xs {
                assert_eq!(s.add(t, a), t, "add never leaves the terminal");
                assert_eq!(s.add(a, t), t, "add never leaves the terminal");
            }
        }
        for &a in xs {
            assert_eq!(s.add(a, s.zero()), a, "zero is add's identity");
            assert_eq!(s.mul(a, s.one()), a, "one is mul's identity");
            assert_eq!(s.mul(a, s.zero()), s.zero(), "zero annihilates");
            for &b in xs {
                assert_eq!(s.add(a, b), s.add(b, a));
                for &c in xs {
                    assert_eq!(s.mul(a, s.add(b, c)), s.add(s.mul(a, b), s.mul(a, c)));
                }
            }
        }
    }

    #[test]
    fn the_four_semirings_keep_the_laws() {
        laws(BoolOrAnd, &[0, 1]);
        laws(BitsetUnion, &[0, 1, 6, u64::MAX]);
        laws(MinPlus::<u64>::new(), &[0, 1, 5, 9]);
        laws(MinPlus::<f64>::new(), &[0.0, 1.5, 4.0]);
        laws(PlusTimes::<i64>::new(), &[0, 1, -2, 7]);
    }

    #[test]
    fn or_and_and_union_stop_at_their_terminal() {
        assert_eq!(BoolOrAnd.terminal(), Some(1));
        assert_eq!(BitsetUnion.terminal(), Some(u64::MAX));
        assert_eq!(MinPlus::<u32>::new().terminal(), None);
        assert_eq!(PlusTimes::<f64>::new().terminal(), None);
    }

    #[test]
    fn min_plus_stops_at_no_path() {
        let s = MinPlus::<u32>::new();
        assert_eq!(s.mul(u32::MAX, 3), u32::MAX);
        assert_eq!(s.add(4, 9), 4);
    }
}