use std::fmt;
use anyhow::{Result, anyhow, bail, ensure};
use serde::de::{SeqAccess, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
type Index = u32;
const TARGET_BLOCK_BYTES: usize = 8 * 1024 * 1024;
const BLOCK_INDICES: usize = TARGET_BLOCK_BYTES / std::mem::size_of::<Index>();
#[inline]
#[must_use]
pub const fn bytes_per_row(nonzeros: usize) -> usize {
nonzeros * std::mem::size_of::<Index>()
}
#[inline]
fn binary_value(value: f32, index: usize) -> Result<bool> {
#[allow(clippy::float_cmp)]
let (is_zero, is_one) = (value == 0.0, value == 1.0);
if is_one {
Ok(true)
} else if is_zero {
Ok(false)
} else {
bail!(
"Value {value} at feature index {index} is not 0 or 1. A dataset row records \
whether each n-gram is present, so it cannot hold other values."
)
}
}
#[inline]
fn to_index(index: usize) -> Result<Index> {
Index::try_from(index)
.map_err(|_| anyhow!("Feature index {index} exceeds the limit of {}", Index::MAX))
}
#[derive(Copy, Clone, Debug)]
pub struct RowSlice<'a> {
indices: &'a [Index],
len: usize,
}
impl<'a> RowSlice<'a> {
#[inline]
#[must_use]
pub const fn len(&self) -> usize {
self.len
}
#[inline]
#[must_use]
pub const fn is_empty(&self) -> bool {
self.len == 0
}
#[inline]
#[must_use]
pub const fn indices(&self) -> &'a [Index] {
self.indices
}
#[must_use]
pub fn get(&self, index: usize) -> Option<f32> {
if index >= self.len {
return None;
}
let Ok(needle) = Index::try_from(index) else {
return Some(0.0);
};
Some(f32::from(self.indices.binary_search(&needle).is_ok()))
}
pub fn iter(self) -> impl Iterator<Item = f32> + 'a {
let indices = self.indices;
let mut cursor = 0usize;
(0..self.len).map(move |column| {
while cursor < indices.len() && (indices[cursor] as usize) < column {
cursor += 1;
}
f32::from(cursor < indices.len() && indices[cursor] as usize == column)
})
}
pub fn iter_nonzero(self) -> impl Iterator<Item = (usize, f32)> + 'a {
self.indices.iter().map(|index| (*index as usize, 1.0))
}
#[inline]
#[must_use]
pub const fn count_nonzero(&self) -> usize {
self.indices.len()
}
#[must_use]
#[allow(clippy::cast_precision_loss)]
pub fn sum(&self) -> f32 {
self.indices.len() as f32
}
#[must_use]
pub fn dot(&self, weights: &[f32]) -> f32 {
self.indices
.iter()
.filter_map(|index| weights.get(*index as usize))
.sum()
}
#[must_use]
pub fn retain_indices(&self, keep: &[usize]) -> DataRow {
let remap = Remap::new(self.len, keep);
DataRow {
indices: remap.apply(self.indices),
len: keep.len(),
}
}
}
impl PartialEq for RowSlice<'_> {
fn eq(&self, other: &Self) -> bool {
self.len == other.len && self.indices == other.indices
}
}
impl Serialize for RowSlice<'_> {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.collect_seq(self.iter())
}
}
struct Remap {
by_old: Vec<Index>,
}
impl Remap {
fn new(columns: usize, keep: &[usize]) -> Self {
let mut by_old = vec![Index::MAX; columns];
for (new_index, old_index) in keep.iter().enumerate() {
if let Some(slot) = by_old.get_mut(*old_index)
&& let Ok(new_index) = Index::try_from(new_index)
{
*slot = new_index;
}
}
Self { by_old }
}
fn apply(&self, indices: &[Index]) -> Vec<Index> {
indices
.iter()
.filter_map(|old| {
let new = *self.by_old.get(*old as usize)?;
(new != Index::MAX).then_some(new)
})
.collect()
}
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct DataRow {
indices: Vec<Index>,
len: usize,
}
impl DataRow {
#[must_use]
pub fn zeroed(len: usize) -> Self {
Self {
indices: Vec::new(),
len,
}
}
#[inline]
#[must_use]
pub fn as_slice(&self) -> RowSlice<'_> {
RowSlice {
indices: &self.indices,
len: self.len,
}
}
#[inline]
#[must_use]
pub const fn len(&self) -> usize {
self.len
}
#[inline]
#[must_use]
pub const fn is_empty(&self) -> bool {
self.len == 0
}
#[inline]
#[must_use]
pub fn get(&self, index: usize) -> Option<f32> {
self.as_slice().get(index)
}
pub fn set(&mut self, index: usize, value: f32) -> Result<()> {
ensure!(
index < self.len,
"Feature index {index} is out of bounds for a row of {} features",
self.len
);
let needle = to_index(index)?;
if binary_value(value, index)? {
if let Err(position) = self.indices.binary_search(&needle) {
self.indices.insert(position, needle);
}
} else if let Ok(position) = self.indices.binary_search(&needle) {
self.indices.remove(position);
}
Ok(())
}
pub fn iter(&self) -> impl Iterator<Item = f32> + '_ {
self.as_slice().iter()
}
pub fn iter_nonzero(&self) -> impl Iterator<Item = (usize, f32)> + '_ {
self.as_slice().iter_nonzero()
}
#[inline]
#[must_use]
pub const fn count_nonzero(&self) -> usize {
self.indices.len()
}
#[must_use]
pub fn sum(&self) -> f32 {
self.as_slice().sum()
}
#[must_use]
pub fn dot(&self, weights: &[f32]) -> f32 {
self.as_slice().dot(weights)
}
#[must_use]
pub fn retain_indices(&self, keep: &[usize]) -> Self {
self.as_slice().retain_indices(keep)
}
}
impl TryFrom<&[f32]> for DataRow {
type Error = anyhow::Error;
fn try_from(values: &[f32]) -> Result<Self> {
let mut indices = Vec::new();
for (index, value) in values.iter().enumerate() {
if binary_value(*value, index)? {
indices.push(to_index(index)?);
}
}
Ok(Self {
indices,
len: values.len(),
})
}
}
impl TryFrom<Vec<f32>> for DataRow {
type Error = anyhow::Error;
fn try_from(values: Vec<f32>) -> Result<Self> {
Self::try_from(values.as_slice())
}
}
impl Serialize for DataRow {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
self.as_slice().serialize(serializer)
}
}
impl<'de> Deserialize<'de> for DataRow {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let values = Vec::<f32>::deserialize(deserializer)?;
DataRow::try_from(values).map_err(serde::de::Error::custom)
}
}
pub struct RowAccumulator {
bits: Vec<u64>,
len: usize,
}
impl RowAccumulator {
#[must_use]
pub fn new(len: usize) -> Self {
Self {
bits: vec![0u64; len.div_ceil(u64::BITS as usize)],
len,
}
}
#[inline]
#[must_use]
pub const fn len(&self) -> usize {
self.len
}
#[inline]
#[must_use]
pub const fn is_empty(&self) -> bool {
self.len == 0
}
#[inline]
pub fn set(&mut self, index: usize) -> Result<()> {
ensure!(
index < self.len,
"Feature index {index} is out of bounds for a row of {} features",
self.len
);
self.bits[index / u64::BITS as usize] |= 1 << (index % u64::BITS as usize);
Ok(())
}
pub fn clear(&mut self) {
self.bits.fill(0);
}
#[must_use]
pub fn count(&self) -> usize {
self.bits
.iter()
.map(|word| word.count_ones() as usize)
.sum()
}
#[must_use]
pub fn build(&self) -> DataRow {
let mut indices = Vec::with_capacity(self.count());
for (word_index, word) in self.bits.iter().enumerate() {
let mut remaining = *word;
while remaining != 0 {
let bit = remaining.trailing_zeros() as usize;
remaining &= remaining - 1;
let index = word_index * u64::BITS as usize + bit;
if index >= self.len {
break;
}
if let Ok(index) = Index::try_from(index) {
indices.push(index);
}
}
}
DataRow {
indices,
len: self.len,
}
}
}
#[derive(Copy, Clone, Debug)]
struct RowRef {
block: u32,
offset: u32,
len: u32,
}
#[derive(Clone, Debug, Default)]
pub struct DataMatrix {
blocks: Vec<Vec<Index>>,
rows: Vec<RowRef>,
row_len: usize,
scratch: Vec<Index>,
}
impl DataMatrix {
#[must_use]
pub fn new(row_len: usize) -> Self {
Self {
blocks: Vec::new(),
rows: Vec::new(),
row_len,
scratch: Vec::new(),
}
}
#[inline]
#[must_use]
pub fn len(&self) -> usize {
self.rows.len()
}
#[inline]
#[must_use]
pub fn is_empty(&self) -> bool {
self.rows.is_empty()
}
#[inline]
#[must_use]
pub const fn row_len(&self) -> usize {
self.row_len
}
#[inline]
#[must_use]
pub fn blocks(&self) -> usize {
self.blocks.len()
}
#[must_use]
pub fn count_nonzero(&self) -> usize {
self.rows.iter().map(|row| row.len as usize).sum()
}
#[must_use]
pub fn allocated_bytes(&self) -> usize {
self.blocks
.iter()
.map(|block| block.capacity() * std::mem::size_of::<Index>())
.sum::<usize>()
+ self.rows.capacity() * std::mem::size_of::<RowRef>()
+ self.scratch.capacity() * std::mem::size_of::<Index>()
}
#[inline]
#[must_use]
pub fn row(&self, index: usize) -> Option<RowSlice<'_>> {
self.slice_of(self.rows.get(index)?)
}
#[inline]
fn slice_of(&self, row: &RowRef) -> Option<RowSlice<'_>> {
let start = row.offset as usize;
Some(RowSlice {
indices: self
.blocks
.get(row.block as usize)?
.get(start..start + row.len as usize)?,
len: self.row_len,
})
}
pub fn iter(&self) -> impl Iterator<Item = RowSlice<'_>> + '_ {
self.rows.iter().filter_map(|row| self.slice_of(row))
}
pub fn row_builder(&mut self) -> Result<RowBuilder<'_>> {
ensure!(
u32::try_from(self.rows.len()).is_ok(),
"A dataset cannot hold more than {} rows",
u32::MAX
);
self.scratch.clear();
Ok(RowBuilder {
matrix: self,
sorted: true,
})
}
pub fn push_row(&mut self, row: RowSlice<'_>) -> Result<()> {
ensure!(
row.len() == self.row_len,
"Row spans {} features, expected {}",
row.len(),
self.row_len
);
self.append(row.indices)
}
fn append(&mut self, indices: &[Index]) -> Result<()> {
let descriptor = self.reserve(indices.len())?;
let start = descriptor.offset as usize;
self.blocks[descriptor.block as usize][start..start + indices.len()]
.copy_from_slice(indices);
self.rows.push(descriptor);
Ok(())
}
fn reserve(&mut self, count: usize) -> Result<RowRef> {
let fits = self
.blocks
.last()
.is_some_and(|block| block.len() + count <= block.capacity());
if !fits {
self.blocks
.push(Vec::with_capacity(count.max(BLOCK_INDICES)));
}
let block_index = self.blocks.len() - 1;
let block = &mut self.blocks[block_index];
let offset = block.len();
block.resize(offset + count, 0);
Ok(RowRef {
block: u32::try_from(block_index).map_err(|_| anyhow!("Too many storage blocks"))?,
offset: u32::try_from(offset)
.map_err(|_| anyhow!("Block offset {offset} is too large"))?,
len: u32::try_from(count)
.map_err(|_| anyhow!("A row cannot hold more than {} features", u32::MAX))?,
})
}
pub fn permute(&mut self, permutation: &[usize]) -> Result<()> {
ensure!(
permutation.len() == self.rows.len(),
"Permutation has {} entries, expected {}",
permutation.len(),
self.rows.len()
);
self.rows = permutation.iter().map(|from| self.rows[*from]).collect();
Ok(())
}
pub fn split_off(&mut self, at: usize) -> Result<Self> {
ensure!(
at <= self.len(),
"Split index {at} is beyond the {} rows available",
self.len()
);
let mut tail = Self::new(self.row_len);
for index in at..self.len() {
if let Some(row) = self.row(index) {
tail.push_row(row)?;
}
}
self.rows.truncate(at);
Ok(tail)
}
pub fn retain_indices(&mut self, keep: &[usize]) -> Result<()> {
let remap = Remap::new(self.row_len, keep);
let mut rebuilt = Self::new(keep.len());
for index in 0..self.len() {
let Some(row) = self.row(index) else { continue };
rebuilt.append(&remap.apply(row.indices))?;
}
*self = rebuilt;
Ok(())
}
#[must_use]
pub fn column_sums(&self) -> Vec<f32> {
let mut sums = vec![0.0f32; self.row_len];
for row in self.iter() {
for index in row.indices {
if let Some(sum) = sums.get_mut(*index as usize) {
*sum += 1.0;
}
}
}
sums
}
}
impl PartialEq for DataMatrix {
fn eq(&self, other: &Self) -> bool {
self.row_len == other.row_len
&& self.len() == other.len()
&& self.iter().zip(other.iter()).all(|(a, b)| a == b)
}
}
impl FromIterator<DataRow> for DataMatrix {
fn from_iter<I: IntoIterator<Item = DataRow>>(iter: I) -> Self {
let mut rows = iter.into_iter();
let Some(first) = rows.next() else {
return Self::new(0);
};
let mut matrix = Self::new(first.len());
let _ = matrix.push_row(first.as_slice());
for row in rows {
let _ = matrix.push_row(row.as_slice());
}
matrix
}
}
pub struct RowBuilder<'a> {
matrix: &'a mut DataMatrix,
sorted: bool,
}
impl RowBuilder<'_> {
#[inline]
pub fn push(&mut self, index: usize, value: f32) -> Result<()> {
ensure!(
index < self.matrix.row_len,
"Feature index {index} is out of bounds for a dataset of {} features",
self.matrix.row_len
);
if !binary_value(value, index)? {
return Ok(());
}
let index = to_index(index)?;
if self.sorted
&& self
.matrix
.scratch
.last()
.is_some_and(|last| *last >= index)
{
self.sorted = false;
}
self.matrix.scratch.push(index);
Ok(())
}
pub fn finish(self) -> Result<()> {
let matrix = self.matrix;
if !self.sorted {
matrix.scratch.sort_unstable();
}
if let Some([duplicate, _]) = matrix
.scratch
.windows(2)
.find(|pair| pair[0] == pair[1])
.and_then(|pair| <&[Index; 2]>::try_from(pair).ok())
{
bail!("Feature index {duplicate} is listed more than once on the same row");
}
let count = matrix.scratch.len();
let descriptor = matrix.reserve(count)?;
let start = descriptor.offset as usize;
let block = &mut matrix.blocks[descriptor.block as usize];
block[start..start + count].copy_from_slice(&matrix.scratch);
matrix.rows.push(descriptor);
Ok(())
}
}
impl Serialize for DataMatrix {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.collect_seq(self.iter())
}
}
impl<'de> Deserialize<'de> for DataMatrix {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
struct MatrixVisitor;
impl<'de> Visitor<'de> for MatrixVisitor {
type Value = DataMatrix;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("a sequence of dataset rows")
}
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
use serde::de::Error;
let mut matrix: Option<DataMatrix> = None;
while let Some(row) = seq.next_element::<DataRow>()? {
let matrix = matrix.get_or_insert_with(|| DataMatrix::new(row.len()));
matrix.push_row(row.as_slice()).map_err(A::Error::custom)?;
}
Ok(matrix.unwrap_or_else(|| DataMatrix::new(0)))
}
}
deserializer.deserialize_seq(MatrixVisitor)
}
}
#[cfg(test)]
mod tests {
use super::{BLOCK_INDICES, DataMatrix, DataRow, RowAccumulator, RowRef, bytes_per_row};
#[test]
fn binary_round_trip() {
let values = [1.0f32, 0.0, 0.0, 1.0, 1.0, 0.0];
let row = DataRow::try_from(values.as_slice()).unwrap();
assert_eq!(row.len(), values.len());
assert!(!row.is_empty());
assert_eq!(row.iter().collect::<Vec<_>>(), values);
assert_eq!(row.count_nonzero(), 3);
assert!((row.sum() - 3.0).abs() < 1e-6);
assert_eq!(
row.iter_nonzero().collect::<Vec<_>>(),
vec![(0, 1.0), (3, 1.0), (4, 1.0)]
);
for (index, value) in values.iter().enumerate() {
assert_eq!(row.get(index), Some(*value));
}
assert_eq!(row.get(values.len()), None);
}
#[test]
fn dot_matches_naive() {
let values = [1.0f32, 0.0, 1.0, 0.0, 1.0];
let weights = [0.5f32, -2.0, 0.25, 7.0, -0.75];
let row = DataRow::try_from(values.as_slice()).unwrap();
let naive: f32 = values.iter().zip(&weights).map(|(v, w)| v * w).sum();
assert!((row.dot(&weights) - naive).abs() < 1e-6);
}
#[test]
fn set_keeps_indices_sorted_and_unique() {
let mut row = DataRow::zeroed(70);
assert_eq!(row.count_nonzero(), 0);
row.set(69, 1.0).unwrap();
row.set(0, 1.0).unwrap();
row.set(64, 1.0).unwrap();
assert_eq!(row.as_slice().indices(), &[0, 64, 69]);
row.set(64, 1.0).unwrap();
assert_eq!(row.count_nonzero(), 3);
row.set(64, 0.0).unwrap();
assert_eq!(row.as_slice().indices(), &[0, 69]);
row.set(5, 0.0).unwrap();
assert_eq!(row.count_nonzero(), 2);
assert!(
row.set(70, 1.0).is_err(),
"out of bounds index must be rejected"
);
}
#[test]
fn retain_indices_renumbers() {
let row = DataRow::try_from([1.0f32, 0.0, 1.0, 1.0, 0.0].as_slice()).unwrap();
let kept = row.retain_indices(&[1, 2, 4]);
assert_eq!(kept.len(), 3);
assert_eq!(kept.iter().collect::<Vec<_>>(), vec![0.0, 1.0, 0.0]);
assert_eq!(kept.as_slice().indices(), &[1]);
}
#[test]
fn serde_is_a_flat_sequence() {
let row = DataRow::try_from([1.0f32, 0.0, 1.0].as_slice()).unwrap();
let json = serde_json::to_string(&row).unwrap();
assert_eq!(json, "[1.0,0.0,1.0]");
let back: DataRow = serde_json::from_str(&json).unwrap();
assert_eq!(back, row);
}
#[test]
fn non_binary_values_are_rejected_not_rounded() {
let mut row = DataRow::zeroed(3);
let err = row.set(1, 0.5).unwrap_err().to_string();
assert!(err.contains("not 0 or 1"), "unexpected error: {err}");
assert!(DataRow::try_from([0.0f32, 0.5].as_slice()).is_err());
}
#[test]
fn accumulator_deduplicates_and_sorts() {
let mut acc = RowAccumulator::new(200);
assert!(!acc.is_empty());
assert_eq!(acc.len(), 200);
for index in [130usize, 1, 199, 64, 1, 130, 0, 65, 130] {
acc.set(index).unwrap();
}
assert!(acc.set(200).is_err());
assert_eq!(acc.count(), 6);
let row = acc.build();
assert_eq!(row.len(), 200);
assert_eq!(row.as_slice().indices(), &[0, 1, 64, 65, 130, 199]);
acc.clear();
assert_eq!(acc.count(), 0);
assert_eq!(acc.build().count_nonzero(), 0);
}
#[test]
fn accumulator_ignores_padding_bits() {
let mut acc = RowAccumulator::new(10);
for index in 0..10 {
acc.set(index).unwrap();
}
assert_eq!(acc.build().as_slice().indices().len(), 10);
assert!(acc.set(10).is_err());
}
#[test]
fn builder_accepts_unsorted_input() {
let mut matrix = DataMatrix::new(100);
let mut row = matrix.row_builder().unwrap();
for index in [90usize, 3, 50, 0] {
row.push(index, 1.0).unwrap();
}
row.finish().unwrap();
assert_eq!(
matrix.row(0).unwrap().indices(),
&[0, 3, 50, 90],
"indices must come out sorted"
);
}
#[test]
fn builder_rejects_duplicates() {
let mut matrix = DataMatrix::new(100);
let mut row = matrix.row_builder().unwrap();
row.push(7, 1.0).unwrap();
row.push(7, 1.0).unwrap();
let err = row.finish().unwrap_err().to_string();
assert!(err.contains("more than once"), "unexpected error: {err}");
}
#[test]
fn builder_skips_zeroes_and_bounds_checks() {
let mut matrix = DataMatrix::new(10);
let mut row = matrix.row_builder().unwrap();
for index in 0..10 {
row.push(index, f32::from(index % 3 == 0)).unwrap();
}
assert!(row.push(10, 1.0).is_err(), "out of bounds must be rejected");
row.finish().unwrap();
assert_eq!(matrix.row(0).unwrap().indices(), &[0, 3, 6, 9]);
assert_eq!(matrix.count_nonzero(), 4);
}
#[test]
fn dropped_builder_records_nothing() {
let mut matrix = DataMatrix::new(10);
{
let mut row = matrix.row_builder().unwrap();
row.push(3, 1.0).unwrap();
}
assert_eq!(matrix.len(), 0);
let mut row = matrix.row_builder().unwrap();
row.push(5, 1.0).unwrap();
row.finish().unwrap();
assert_eq!(matrix.len(), 1);
assert_eq!(matrix.row(0).unwrap().indices(), &[5]);
}
#[test]
fn matrix_spans_many_blocks() {
const FEATURES: usize = 1_000_000;
const PER_ROW: usize = 5000;
let rows = (BLOCK_INDICES / PER_ROW) * 3 + 5;
let mut matrix = DataMatrix::new(FEATURES);
for row_index in 0..rows {
let mut row = matrix.row_builder().unwrap();
for step in 0..PER_ROW {
row.push((row_index + step * 97) % FEATURES, 1.0).unwrap();
}
row.finish().unwrap();
}
assert_eq!(matrix.len(), rows);
assert!(
matrix.blocks() >= 4,
"expected several blocks, got {}",
matrix.blocks()
);
for row_index in 0..rows {
let row = matrix.row(row_index).unwrap();
assert_eq!(row.len(), FEATURES);
assert_eq!(row.count_nonzero(), PER_ROW, "row {row_index}");
let mut expected = (0..PER_ROW)
.map(|step| u32::try_from((row_index + step * 97) % FEATURES).unwrap())
.collect::<Vec<_>>();
expected.sort_unstable();
assert_eq!(row.indices(), expected.as_slice(), "row {row_index}");
}
assert_eq!(matrix.row(rows), None);
}
#[test]
fn matrix_handles_row_larger_than_a_block() {
let features = BLOCK_INDICES * 2;
let mut matrix = DataMatrix::new(features);
let mut row = matrix.row_builder().unwrap();
for index in (0..features).step_by(2) {
row.push(index, 1.0).unwrap();
}
row.finish().unwrap();
let stored = matrix.row(0).unwrap();
assert_eq!(stored.count_nonzero(), features / 2);
assert_eq!(stored.indices().first(), Some(&0));
assert_eq!(
stored.indices().last(),
Some(&u32::try_from(features - 2).unwrap())
);
}
#[test]
fn matrix_permute_reorders_without_copying_indices() {
let mut matrix = DataMatrix::new(8);
for row_index in 0..4 {
let mut row = matrix.row_builder().unwrap();
row.push(row_index, 1.0).unwrap();
row.finish().unwrap();
}
let before = matrix.allocated_bytes();
matrix.permute(&[3, 1, 0, 2]).unwrap();
assert_eq!(
matrix.allocated_bytes(),
before,
"permute must not allocate"
);
let seen = (0..4)
.map(|i| matrix.row(i).unwrap().indices()[0])
.collect::<Vec<_>>();
assert_eq!(seen, vec![3, 1, 0, 2]);
assert!(matrix.permute(&[0, 1]).is_err(), "length must be checked");
}
#[test]
fn matrix_split_off_and_retain() {
let mut matrix = DataMatrix::new(6);
for row_index in 0..10 {
let mut row = matrix.row_builder().unwrap();
row.push(row_index % 6, 1.0).unwrap();
row.finish().unwrap();
}
let tail = matrix.split_off(7).unwrap();
assert_eq!(matrix.len(), 7);
assert_eq!(tail.len(), 3);
assert_eq!(
tail.row(0).unwrap().indices(),
&[u32::try_from(7 % 6).unwrap()]
);
matrix.retain_indices(&[1, 3, 5]).unwrap();
assert_eq!(matrix.row_len(), 3);
assert_eq!(matrix.len(), 7);
assert_eq!(matrix.row(1).unwrap().indices(), &[0]);
assert_eq!(matrix.row(0).unwrap().count_nonzero(), 0);
}
#[test]
fn matrix_column_sums() {
let mut matrix = DataMatrix::new(4);
for pattern in [vec![0usize, 2], vec![2], vec![1, 2, 3]] {
let mut row = matrix.row_builder().unwrap();
for index in pattern {
row.push(index, 1.0).unwrap();
}
row.finish().unwrap();
}
assert_eq!(matrix.column_sums(), vec![1.0, 1.0, 3.0, 1.0]);
}
#[test]
fn matrix_serde_round_trip() {
let mut matrix = DataMatrix::new(4);
for row_index in 0..3 {
let mut row = matrix.row_builder().unwrap();
row.push(row_index, 1.0).unwrap();
row.finish().unwrap();
}
let json = serde_json::to_string(&matrix).unwrap();
let back: DataMatrix = serde_json::from_str(&json).unwrap();
assert_eq!(back, matrix);
}
#[test]
fn matrix_overhead_is_bounded() {
const FEATURES: usize = 1_000_000;
const PER_ROW: usize = 6900;
for rows in [1usize, 10, 400] {
let mut matrix = DataMatrix::new(FEATURES);
for row_index in 0..rows {
let mut row = matrix.row_builder().unwrap();
for step in 0..PER_ROW {
row.push((row_index + step * 101) % FEATURES, 1.0).unwrap();
}
row.finish().unwrap();
}
let payload = rows * bytes_per_row(PER_ROW);
let actual = matrix.allocated_bytes();
assert!(
actual >= payload,
"{rows} rows: {actual} < payload {payload}"
);
let slack = BLOCK_INDICES * std::mem::size_of::<u32>()
+ rows * std::mem::size_of::<RowRef>() * 2
+ bytes_per_row(PER_ROW) * 2;
assert!(
actual - payload <= slack,
"{rows} rows: overhead {} exceeds {slack}",
actual - payload
);
}
}
}