crates/kleene-sparse/src/vector.rs
use std::borrow::Cow;
use arrow_array::UInt32Array;
use arrow_buffer::ScalarBuffer;
use crate::bitset::Bitset;
use crate::semiring::{Semiring, Value};
use crate::{Result, SparseError};
/// A sparse vector of length `len`: its entries as rising indices with a value each, or
/// densely as a value per place and a bitset of the places that hold an entry.
#[derive(Clone, Debug, PartialEq)]
pub struct Vector<T: Value> {
len: usize,
repr: Repr<T>,
}
#[derive(Clone, Debug, PartialEq)]
enum Repr<T: Value> {
Sparse { indices: Vec<u32>, values: Vec<T> },
Dense { values: Vec<T>, present: Bitset },
}
impl<T: Value> Vector<T> {
/// A vector with no entries.
pub fn empty(len: usize) -> Self {
Vector {
len,
repr: Repr::Sparse {
indices: Vec::new(),
values: Vec::new(),
},
}
}
/// A vector from strictly rising indices and their values.
pub fn sparse(len: usize, indices: Vec<u32>, values: Vec<T>) -> Result<Self> {
if indices.len() != values.len() {
return Err(SparseError::Length {
what: "vector values",
want: indices.len(),
got: values.len(),
});
}
if indices.windows(2).any(|w| w[0] >= w[1]) {
return Err(SparseError::NotSorted { what: "vector" });
}
if let Some(&i) = indices.last()
&& i as usize >= len
{
return Err(SparseError::IndexOutOfRange {
what: "vector",
index: i as u64,
dim: len as u64,
});
}
Ok(Vector {
len,
repr: Repr::Sparse { indices, values },
})
}
/// A vector from (index, value) pairs in any order; values at one index are folded
/// with the semiring's add.
pub fn from_pairs<S: Semiring<T = T>>(
len: usize,
mut pairs: Vec<(u32, T)>,
s: S,
) -> Result<Self> {
pairs.sort_unstable_by_key(|p| p.0);
let mut indices: Vec<u32> = Vec::with_capacity(pairs.len());
let mut values: Vec<T> = Vec::with_capacity(pairs.len());
for (i, v) in pairs {
if indices.last() == Some(&i) {
let l = values.len() - 1;
values[l] = s.add(values[l], v);
} else {
indices.push(i);
values.push(v);
}
}
Self::sparse(len, indices, values)
}
/// The same value at each of `indices` (any order, repeats kept once).
pub fn from_indices(len: usize, indices: &[u32], value: T) -> Result<Self> {
let mut idx = indices.to_vec();
idx.sort_unstable();
idx.dedup();
let n = idx.len();
Self::sparse(len, idx, vec![value; n])
}
/// A dense vector: a value per place, entries where `present` is set.
pub fn dense(values: Vec<T>, present: Bitset) -> Result<Self> {
if values.len() != present.len() {
return Err(SparseError::Length {
what: "dense vector",
want: present.len(),
got: values.len(),
});
}
Ok(Vector {
len: values.len(),
repr: Repr::Dense { values, present },
})
}
/// An entry at every place, each `value`.
pub fn full(len: usize, value: T) -> Self {
Vector {
len,
repr: Repr::Dense {
values: vec![value; len],
present: Bitset::full(len),
},
}
}
/// The length.
pub fn len(&self) -> usize {
self.len
}
/// True when the length is 0.
pub fn is_empty(&self) -> bool {
self.len == 0
}
/// The number of entries.
pub fn nvals(&self) -> usize {
match &self.repr {
Repr::Sparse { indices, .. } => indices.len(),
Repr::Dense { present, .. } => present.count(),
}
}
/// True when the vector is stored densely.
pub fn is_dense(&self) -> bool {
matches!(self.repr, Repr::Dense { .. })
}
/// The entry at `i`.
pub fn get(&self, i: usize) -> Option<T> {
match &self.repr {
Repr::Sparse { indices, values } => {
indices.binary_search(&(i as u32)).ok().map(|p| values[p])
}
Repr::Dense { values, present } => present.get(i).then(|| values[i]),
}
}
/// The entries, rising by index.
pub fn iter(&self) -> Box<dyn Iterator<Item = (u32, T)> + '_> {
match &self.repr {
Repr::Sparse { indices, values } => {
Box::new(indices.iter().copied().zip(values.iter().copied()))
}
Repr::Dense { values, present } => {
Box::new(present.iter().map(move |i| (i, values[i as usize])))
}
}
}
/// The indices of the entries, rising.
pub fn indices(&self) -> Vec<u32> {
match &self.repr {
Repr::Sparse { indices, .. } => indices.clone(),
Repr::Dense { present, .. } => {
let mut out = Vec::with_capacity(present.count());
out.extend(present.iter());
out
}
}
}
/// The places that hold an entry.
pub fn structure(&self) -> Bitset {
match &self.repr {
Repr::Sparse { indices, .. } => Bitset::from_indices(self.len, indices.iter().copied()),
Repr::Dense { present, .. } => present.clone(),
}
}
/// The same vector stored sparsely.
pub fn into_sparse(self) -> Self {
match self.repr {
Repr::Sparse { .. } => self,
Repr::Dense { values, present } => {
let indices: Vec<u32> = present.iter().collect();
let vals = indices.iter().map(|&i| values[i as usize]).collect();
Vector {
len: self.len,
repr: Repr::Sparse {
indices,
values: vals,
},
}
}
}
}
/// The same vector stored densely; `fill` is the value at places with no entry.
pub fn into_dense(self, fill: T) -> Self {
match self.repr {
Repr::Dense { .. } => self,
Repr::Sparse { indices, values } => {
let mut dense = vec![fill; self.len];
let mut present = Bitset::new(self.len);
for (i, v) in indices.into_iter().zip(values) {
dense[i as usize] = v;
present.set(i as usize);
}
Vector {
len: self.len,
repr: Repr::Dense {
values: dense,
present,
},
}
}
}
}
/// A dense view for lookups: a value per place (`fill` where there is no entry) and the
/// bitset of entries. A dense vector lends its own storage; a sparse one is expanded.
pub fn lookup(&self, fill: T) -> DenseView<'_, T> {
match &self.repr {
Repr::Dense { values, present } => DenseView {
values: Cow::Borrowed(values),
present: Cow::Borrowed(present),
},
Repr::Sparse { indices, values } => {
let mut dense = vec![fill; self.len];
let mut present = Bitset::new(self.len);
for (&i, &v) in indices.iter().zip(values) {
dense[i as usize] = v;
present.set(i as usize);
}
DenseView {
values: Cow::Owned(dense),
present: Cow::Owned(present),
}
}
}
}
/// The dense storage, given back to be reused (a value per place, the places present);
/// a sparse vector comes back unchanged.
pub fn into_dense_parts(self) -> std::result::Result<(Vec<T>, Bitset), Self> {
match self.repr {
Repr::Dense { values, present } => Ok((values, present)),
repr @ Repr::Sparse { .. } => Err(Vector {
len: self.len,
repr,
}),
}
}
/// Borrow the dense storage, if dense.
pub(crate) fn dense_parts(&self) -> Option<(&[T], &Bitset)> {
match &self.repr {
Repr::Dense { values, present } => Some((values, present)),
Repr::Sparse { .. } => None,
}
}
/// Borrow the sparse storage, if sparse.
pub(crate) fn sparse_parts(&self) -> Option<(&[u32], &[T])> {
match &self.repr {
Repr::Sparse { indices, values } => Some((indices, values)),
Repr::Dense { .. } => None,
}
}
/// Empty the vector and hand out its sparse storage to refill (capacity kept); the
/// caller must leave indices strictly rising, each with a value, all below the length.
pub(crate) fn refill(&mut self) -> (&mut Vec<u32>, &mut Vec<T>) {
if self.is_dense() {
self.repr = Repr::Sparse {
indices: Vec::new(),
values: Vec::new(),
};
}
match &mut self.repr {
Repr::Sparse { indices, values } => {
indices.clear();
values.clear();
(indices, values)
}
Repr::Dense { .. } => unreachable!("made sparse above"),
}
}
/// The dense storage to write in place (a sparse vector is made dense first, with
/// `fill` at places with no entry).
pub(crate) fn dense_parts_mut(&mut self, fill: T) -> (&mut [T], &mut Bitset) {
if !self.is_dense() {
let me = std::mem::replace(self, Vector::empty(0));
*self = me.into_dense(fill);
}
match &mut self.repr {
Repr::Dense { values, present } => (values, present),
Repr::Sparse { .. } => unreachable!("made dense above"),
}
}
/// The dense storage itself, to swap with other storage of the same length (a sparse
/// vector is made dense first, with `fill` at places with no entry).
pub(crate) fn dense_vecs_mut(&mut self, fill: T) -> (&mut Vec<T>, &mut Bitset) {
if !self.is_dense() {
let me = std::mem::replace(self, Vector::empty(0));
*self = me.into_dense(fill);
}
match &mut self.repr {
Repr::Dense { values, present } => (values, present),
Repr::Sparse { .. } => unreachable!("made dense above"),
}
}
/// Remove every entry, keeping the storage (a dense vector stays dense with no place
/// present; its values are left as they were and are never read).
pub fn clear(&mut self) {
match &mut self.repr {
Repr::Sparse { indices, values } => {
indices.clear();
values.clear();
}
Repr::Dense { present, .. } => present.clear(),
}
}
/// `value` at each of `indices` (any order, repeats kept once) and nothing else, stored
/// sparsely in the vector's own storage. Refused when an index is past the length.
pub fn load_indices(&mut self, indices: &[u32], value: T) -> Result<()> {
if let Some(&i) = indices.iter().find(|&&i| i as usize >= self.len) {
return Err(SparseError::IndexOutOfRange {
what: "vector",
index: i as u64,
dim: self.len as u64,
});
}
let (idx, val) = self.refill();
idx.extend_from_slice(indices);
idx.sort_unstable();
idx.dedup();
val.resize(idx.len(), value);
Ok(())
}
/// Set the entry at `i` (dense vectors only; a sparse one is made dense first, with
/// `fill` at places with no entry).
pub fn set(&mut self, i: usize, v: T, fill: T) {
if !self.is_dense() {
let me = std::mem::replace(self, Vector::empty(0));
*self = me.into_dense(fill);
}
if let Repr::Dense { values, present } = &mut self.repr {
values[i] = v;
present.set(i);
}
}
/// The indices as an Arrow array and the values as an Arrow buffer (moved, not copied).
pub fn into_arrow(self) -> (UInt32Array, ScalarBuffer<T>) {
match self.into_sparse().repr {
Repr::Sparse { indices, values } => {
(UInt32Array::from(indices), ScalarBuffer::from(values))
}
Repr::Dense { .. } => unreachable!("into_sparse made it sparse"),
}
}
}
/// A vector seen densely: a value per place and the places that hold an entry.
#[derive(Debug)]
pub struct DenseView<'a, T: Value> {
/// A value per place.
pub values: Cow<'a, [T]>,
/// The places that hold an entry.
pub present: Cow<'a, Bitset>,
}
impl<T: Value> DenseView<'_, T> {
/// The entry at `i`.
#[inline]
pub fn get(&self, i: usize) -> Option<T> {
self.present.get(i).then(|| self.values[i])
}
}
/// A structural mask over a vector: the set places of a bitset, or (complemented) the clear
/// ones.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Mask {
bits: Bitset,
complement: bool,
}
impl Mask {
/// The set places of `bits`.
pub fn new(bits: Bitset) -> Self {
Mask {
bits,
complement: false,
}
}
/// Allow every place (keeping the storage).
pub fn assign_all(&mut self) {
self.bits.clear();
self.complement = true;
}
/// Become a copy of `other`, keeping this mask's storage when the lengths agree.
pub fn assign(&mut self, other: &Mask) {
self.bits.copy_from(&other.bits);
self.complement = other.complement;
}
/// The places of `indices` in a vector of `len`.
pub fn from_indices(len: usize, indices: &[u32]) -> Self {
Mask::new(Bitset::from_indices(len, indices.iter().copied()))
}
/// The places where `v` has an entry.
pub fn from_vector<T: Value>(v: &Vector<T>) -> Self {
Mask::new(v.structure())
}
/// Every place.
pub fn all(len: usize) -> Self {
Mask::new(Bitset::new(len)).complement()
}
/// The other places.
pub fn complement(mut self) -> Self {
self.complement = !self.complement;
self
}
/// True when the mask is complemented.
pub fn is_complement(&self) -> bool {
self.complement
}
/// The bits (before the complement).
pub fn bits(&self) -> &Bitset {
&self.bits
}
/// Mutable bits (before the complement).
pub fn bits_mut(&mut self) -> &mut Bitset {
&mut self.bits
}
/// The length.
pub fn len(&self) -> usize {
self.bits.len()
}
/// True when the length is 0.
pub fn is_empty(&self) -> bool {
self.bits.is_empty()
}
/// Whether place `i` is allowed.
#[inline]
pub fn allows(&self, i: usize) -> bool {
self.bits.get(i) != self.complement
}
/// Close place `i`; returns whether it was allowed before.
#[inline]
pub fn close(&mut self, i: usize) -> bool {
if self.complement {
self.bits.set(i)
} else {
let was = self.bits.get(i);
self.bits.unset(i);
was
}
}
/// The number of places allowed.
pub fn count(&self) -> usize {
if self.complement {
self.bits.len() - self.bits.count()
} else {
self.bits.count()
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{MinPlus, PlusTimes};
#[test]
fn sparse_vectors_are_checked() {
assert!(Vector::<u32>::sparse(5, vec![1, 1], vec![0, 0]).is_err());
assert!(Vector::<u32>::sparse(5, vec![2, 1], vec![0, 0]).is_err());
assert!(Vector::<u32>::sparse(5, vec![5], vec![0]).is_err());
assert!(Vector::<u32>::sparse(5, vec![1], vec![]).is_err());
}
#[test]
fn pairs_fold_with_add_and_both_forms_agree() {
let v =
Vector::from_pairs(6, vec![(4, 7u32), (1, 3), (4, 2)], MinPlus::<u32>::new()).unwrap();
assert_eq!(v.iter().collect::<Vec<_>>(), vec![(1, 3), (4, 2)]);
let d = v.clone().into_dense(0);
assert!(d.is_dense());
assert_eq!(d.iter().collect::<Vec<_>>(), v.iter().collect::<Vec<_>>());
assert_eq!(d.get(4), Some(2));
assert_eq!(d.get(3), None);
assert_eq!(d.into_sparse(), v);
}
#[test]
fn masks_and_their_complement() {
let v = Vector::from_pairs(5, vec![(0, 1u64), (3, 1)], PlusTimes::<u64>::new()).unwrap();
let m = Mask::from_vector(&v);
assert!(m.allows(3) && !m.allows(2));
let c = m.complement();
assert!(!c.allows(3) && c.allows(2));
assert_eq!(c.count(), 3);
assert_eq!(Mask::all(4).count(), 4);
}
#[test]
fn arrow_out_moves_the_buffers() {
let v = Vector::from_indices(10, &[7, 2, 7], 1u8).unwrap();
let (idx, vals) = v.into_arrow();
assert_eq!(idx.values().as_ref(), &[2, 7]);
assert_eq!(vals.as_ref(), &[1, 1]);
}
}