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

nordisk/kleene

crates/kleene-index/src/kinds.rs

//! Node kinds as bitmaps: for each distinct value of a vertex table's kind (or label)
//! column, one bit per vertex, set where the vertex has that kind. "Is v a K" is one load
//! and a shift; the vertices of a kind are its set bits, in rising order; a mask for a
//! graph walk is the kind's words as they are.

use arrow_buffer::ScalarBuffer;

use crate::error::{Result, bad};

/// One bitmap per kind over the vertices of a table.
#[derive(Clone, Debug)]
pub struct Kinds {
    /// The distinct kinds, rising.
    keys: ScalarBuffer<u64>,
    /// The vertices per kind, `words()` words each, kind after kind.
    bits: ScalarBuffer<u64>,
    /// The number of vertices.
    n: usize,
}

impl Kinds {
    /// The bitmaps of the kind column `kind` (one value per vertex, vertex `v` at row `v`).
    /// Refused when the kinds' bitmaps would take more than `max_bytes`.
    pub fn build(kind: &[u64], max_bytes: usize) -> Result<Self> {
        let n = kind.len();
        let mut keys: Vec<u64> = kind.to_vec();
        gatling::gatling_sort::gatling_sort_unstable_by(&mut keys, |a, b| a.cmp(b));
        keys.dedup();
        let w = n.div_ceil(64);
        if keys.len().saturating_mul(w).saturating_mul(8) > max_bytes {
            return Err(bad(format!(
                "{} kinds over {n} vertices take more than {max_bytes} bytes as bitmaps",
                keys.len()
            )));
        }
        let mut bits = vec![0u64; keys.len() * w];
        // each worker sets the bits of a run of 64-vertex words, so no two touch one word
        let pieces = w.div_ceil(1024);
        let parts = gatling::gatling_forkjoin::gatling_for_each(pieces, 0, |p| {
            let (lo, hi) = (p * 1024 * 64, ((p + 1) * 1024 * 64).min(n));
            let mut out: Vec<(usize, u64)> = Vec::new();
            let mut v = lo;
            while v < hi {
                let word = v / 64;
                let end = ((word + 1) * 64).min(hi);
                // the words of this 64-vertex run, one per kind it meets
                let start = out.len();
                for (u, &k) in kind.iter().enumerate().take(end).skip(v) {
                    let at = keys.partition_point(|&x| x < k) * w + word;
                    match out[start..].iter_mut().find(|(i, _)| *i == at) {
                        Some((_, b)) => *b |= 1 << (u % 64),
                        None => out.push((at, 1 << (u % 64))),
                    }
                }
                v = end;
            }
            out
        });
        for part in parts {
            for (i, b) in part {
                bits[i] |= b;
            }
        }
        Ok(Kinds {
            keys: keys.into(),
            bits: bits.into(),
            n,
        })
    }

    /// The bitmaps from their stored parts (as [`Kinds::parts`] gave them).
    pub fn from_parts(keys: ScalarBuffer<u64>, bits: ScalarBuffer<u64>, n: usize) -> Result<Self> {
        if keys.windows(2).any(|k| k[0] >= k[1]) || bits.len() != keys.len() * n.div_ceil(64) {
            return Err(bad("stored kinds do not fit together"));
        }
        Ok(Kinds { keys, bits, n })
    }

    /// The kinds and the bitmaps, for storing.
    pub fn parts(&self) -> (&ScalarBuffer<u64>, &ScalarBuffer<u64>) {
        (&self.keys, &self.bits)
    }

    /// The distinct kinds, rising.
    pub fn kinds(&self) -> &[u64] {
        &self.keys
    }

    /// The number of vertices.
    pub fn vertices(&self) -> usize {
        self.n
    }

    /// Words per bitmap.
    pub fn words(&self) -> usize {
        self.n.div_ceil(64)
    }

    /// The bitmap of `kind` (vertex `v` at bit `v % 64` of word `v / 64`); `None` for a
    /// kind no vertex has.
    #[inline]
    pub fn bits(&self, kind: u64) -> Option<&[u64]> {
        let i = self.keys.binary_search(&kind).ok()?;
        let w = self.words();
        Some(&self.bits[i * w..(i + 1) * w])
    }

    /// Whether vertex `v` has `kind`.
    #[inline]
    pub fn has(&self, kind: u64, v: u32) -> bool {
        let v = v as usize;
        v < self.n
            && self
                .bits(kind)
                .is_some_and(|b| b[v / 64] >> (v % 64) & 1 == 1)
    }

    /// The number of vertices of `kind`.
    pub fn count(&self, kind: u64) -> usize {
        self.bits(kind)
            .map_or(0, |b| kleene_sparse::Simd::detect().popcount(b))
    }

    /// The vertices of `kind`, rising.
    pub fn ids(&self, kind: u64) -> impl Iterator<Item = u32> + '_ {
        self.bits(kind)
            .unwrap_or(&[])
            .iter()
            .enumerate()
            .flat_map(|(i, &w)| {
                let mut w = w;
                std::iter::from_fn(move || {
                    (w != 0).then(|| {
                        let b = w.trailing_zeros();
                        w &= w - 1;
                        (i * 64) as u32 + b
                    })
                })
            })
    }
}