1use std::fmt;
20
21use anyhow::{Result, anyhow, bail, ensure};
22use serde::de::{SeqAccess, Visitor};
23use serde::{Deserialize, Deserializer, Serialize, Serializer};
24
25type Index = u32;
30
31const TARGET_BLOCK_BYTES: usize = 8 * 1024 * 1024;
36
37const BLOCK_INDICES: usize = TARGET_BLOCK_BYTES / std::mem::size_of::<Index>();
39
40#[inline]
45#[must_use]
46pub const fn bytes_per_row(nonzeros: usize) -> usize {
47 nonzeros * std::mem::size_of::<Index>()
48}
49
50#[inline]
56fn binary_value(value: f32, index: usize) -> Result<bool> {
57 #[allow(clippy::float_cmp)]
60 let (is_zero, is_one) = (value == 0.0, value == 1.0);
61
62 if is_one {
63 Ok(true)
64 } else if is_zero {
65 Ok(false)
66 } else {
67 bail!(
68 "Value {value} at feature index {index} is not 0 or 1. A dataset row records \
69 whether each n-gram is present, so it cannot hold other values."
70 )
71 }
72}
73
74#[inline]
76fn to_index(index: usize) -> Result<Index> {
77 Index::try_from(index)
78 .map_err(|_| anyhow!("Feature index {index} exceeds the limit of {}", Index::MAX))
79}
80
81#[derive(Copy, Clone, Debug)]
86pub struct RowSlice<'a> {
87 indices: &'a [Index],
89
90 len: usize,
92}
93
94impl<'a> RowSlice<'a> {
95 #[inline]
97 #[must_use]
98 pub const fn len(&self) -> usize {
99 self.len
100 }
101
102 #[inline]
104 #[must_use]
105 pub const fn is_empty(&self) -> bool {
106 self.len == 0
107 }
108
109 #[inline]
111 #[must_use]
112 pub const fn indices(&self) -> &'a [Index] {
113 self.indices
114 }
115
116 #[must_use]
121 pub fn get(&self, index: usize) -> Option<f32> {
122 if index >= self.len {
123 return None;
124 }
125
126 let Ok(needle) = Index::try_from(index) else {
127 return Some(0.0);
128 };
129 Some(f32::from(self.indices.binary_search(&needle).is_ok()))
130 }
131
132 pub fn iter(self) -> impl Iterator<Item = f32> + 'a {
137 let indices = self.indices;
138 let mut cursor = 0usize;
139
140 (0..self.len).map(move |column| {
141 while cursor < indices.len() && (indices[cursor] as usize) < column {
142 cursor += 1;
143 }
144 f32::from(cursor < indices.len() && indices[cursor] as usize == column)
145 })
146 }
147
148 pub fn iter_nonzero(self) -> impl Iterator<Item = (usize, f32)> + 'a {
152 self.indices.iter().map(|index| (*index as usize, 1.0))
153 }
154
155 #[inline]
157 #[must_use]
158 pub const fn count_nonzero(&self) -> usize {
159 self.indices.len()
160 }
161
162 #[must_use]
164 #[allow(clippy::cast_precision_loss)]
165 pub fn sum(&self) -> f32 {
166 self.indices.len() as f32
167 }
168
169 #[must_use]
174 pub fn dot(&self, weights: &[f32]) -> f32 {
175 self.indices
176 .iter()
177 .filter_map(|index| weights.get(*index as usize))
178 .sum()
179 }
180
181 #[must_use]
187 pub fn retain_indices(&self, keep: &[usize]) -> DataRow {
188 let remap = Remap::new(self.len, keep);
189 DataRow {
190 indices: remap.apply(self.indices),
191 len: keep.len(),
192 }
193 }
194}
195
196impl PartialEq for RowSlice<'_> {
197 fn eq(&self, other: &Self) -> bool {
198 self.len == other.len && self.indices == other.indices
199 }
200}
201
202impl Serialize for RowSlice<'_> {
205 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
206 serializer.collect_seq(self.iter())
207 }
208}
209
210struct Remap {
212 by_old: Vec<Index>,
214}
215
216impl Remap {
217 fn new(columns: usize, keep: &[usize]) -> Self {
219 let mut by_old = vec![Index::MAX; columns];
220 for (new_index, old_index) in keep.iter().enumerate() {
221 if let Some(slot) = by_old.get_mut(*old_index)
222 && let Ok(new_index) = Index::try_from(new_index)
223 {
224 *slot = new_index;
225 }
226 }
227 Self { by_old }
228 }
229
230 fn apply(&self, indices: &[Index]) -> Vec<Index> {
235 indices
236 .iter()
237 .filter_map(|old| {
238 let new = *self.by_old.get(*old as usize)?;
239 (new != Index::MAX).then_some(new)
240 })
241 .collect()
242 }
243}
244
245#[derive(Clone, Debug, Default, PartialEq)]
250pub struct DataRow {
251 indices: Vec<Index>,
253
254 len: usize,
256}
257
258impl DataRow {
259 #[must_use]
261 pub fn zeroed(len: usize) -> Self {
262 Self {
263 indices: Vec::new(),
264 len,
265 }
266 }
267
268 #[inline]
270 #[must_use]
271 pub fn as_slice(&self) -> RowSlice<'_> {
272 RowSlice {
273 indices: &self.indices,
274 len: self.len,
275 }
276 }
277
278 #[inline]
280 #[must_use]
281 pub const fn len(&self) -> usize {
282 self.len
283 }
284
285 #[inline]
287 #[must_use]
288 pub const fn is_empty(&self) -> bool {
289 self.len == 0
290 }
291
292 #[inline]
294 #[must_use]
295 pub fn get(&self, index: usize) -> Option<f32> {
296 self.as_slice().get(index)
297 }
298
299 pub fn set(&mut self, index: usize, value: f32) -> Result<()> {
309 ensure!(
310 index < self.len,
311 "Feature index {index} is out of bounds for a row of {} features",
312 self.len
313 );
314 let needle = to_index(index)?;
315
316 if binary_value(value, index)? {
317 if let Err(position) = self.indices.binary_search(&needle) {
318 self.indices.insert(position, needle);
319 }
320 } else if let Ok(position) = self.indices.binary_search(&needle) {
321 self.indices.remove(position);
322 }
323
324 Ok(())
325 }
326
327 pub fn iter(&self) -> impl Iterator<Item = f32> + '_ {
329 self.as_slice().iter()
330 }
331
332 pub fn iter_nonzero(&self) -> impl Iterator<Item = (usize, f32)> + '_ {
334 self.as_slice().iter_nonzero()
335 }
336
337 #[inline]
339 #[must_use]
340 pub const fn count_nonzero(&self) -> usize {
341 self.indices.len()
342 }
343
344 #[must_use]
346 pub fn sum(&self) -> f32 {
347 self.as_slice().sum()
348 }
349
350 #[must_use]
352 pub fn dot(&self, weights: &[f32]) -> f32 {
353 self.as_slice().dot(weights)
354 }
355
356 #[must_use]
358 pub fn retain_indices(&self, keep: &[usize]) -> Self {
359 self.as_slice().retain_indices(keep)
360 }
361}
362
363impl TryFrom<&[f32]> for DataRow {
364 type Error = anyhow::Error;
365
366 fn try_from(values: &[f32]) -> Result<Self> {
367 let mut indices = Vec::new();
368 for (index, value) in values.iter().enumerate() {
369 if binary_value(*value, index)? {
370 indices.push(to_index(index)?);
371 }
372 }
373
374 Ok(Self {
375 indices,
376 len: values.len(),
377 })
378 }
379}
380
381impl TryFrom<Vec<f32>> for DataRow {
382 type Error = anyhow::Error;
383
384 fn try_from(values: Vec<f32>) -> Result<Self> {
385 Self::try_from(values.as_slice())
386 }
387}
388
389impl Serialize for DataRow {
390 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
391 self.as_slice().serialize(serializer)
392 }
393}
394
395impl<'de> Deserialize<'de> for DataRow {
396 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
397 let values = Vec::<f32>::deserialize(deserializer)?;
398 DataRow::try_from(values).map_err(serde::de::Error::custom)
399 }
400}
401
402pub struct RowAccumulator {
411 bits: Vec<u64>,
413
414 len: usize,
416}
417
418impl RowAccumulator {
419 #[must_use]
421 pub fn new(len: usize) -> Self {
422 Self {
423 bits: vec![0u64; len.div_ceil(u64::BITS as usize)],
424 len,
425 }
426 }
427
428 #[inline]
430 #[must_use]
431 pub const fn len(&self) -> usize {
432 self.len
433 }
434
435 #[inline]
437 #[must_use]
438 pub const fn is_empty(&self) -> bool {
439 self.len == 0
440 }
441
442 #[inline]
448 pub fn set(&mut self, index: usize) -> Result<()> {
449 ensure!(
450 index < self.len,
451 "Feature index {index} is out of bounds for a row of {} features",
452 self.len
453 );
454 self.bits[index / u64::BITS as usize] |= 1 << (index % u64::BITS as usize);
455 Ok(())
456 }
457
458 pub fn clear(&mut self) {
460 self.bits.fill(0);
461 }
462
463 #[must_use]
465 pub fn count(&self) -> usize {
466 self.bits
467 .iter()
468 .map(|word| word.count_ones() as usize)
469 .sum()
470 }
471
472 #[must_use]
474 pub fn build(&self) -> DataRow {
475 let mut indices = Vec::with_capacity(self.count());
476 for (word_index, word) in self.bits.iter().enumerate() {
477 let mut remaining = *word;
478 while remaining != 0 {
479 let bit = remaining.trailing_zeros() as usize;
480 remaining &= remaining - 1;
481 let index = word_index * u64::BITS as usize + bit;
482 if index >= self.len {
484 break;
485 }
486 if let Ok(index) = Index::try_from(index) {
487 indices.push(index);
488 }
489 }
490 }
491
492 DataRow {
493 indices,
494 len: self.len,
495 }
496 }
497}
498
499#[derive(Copy, Clone, Debug)]
501struct RowRef {
502 block: u32,
504
505 offset: u32,
507
508 len: u32,
510}
511
512#[derive(Clone, Debug, Default)]
518pub struct DataMatrix {
519 blocks: Vec<Vec<Index>>,
521
522 rows: Vec<RowRef>,
524
525 row_len: usize,
527
528 scratch: Vec<Index>,
530}
531
532impl DataMatrix {
533 #[must_use]
535 pub fn new(row_len: usize) -> Self {
536 Self {
537 blocks: Vec::new(),
538 rows: Vec::new(),
539 row_len,
540 scratch: Vec::new(),
541 }
542 }
543
544 #[inline]
546 #[must_use]
547 pub fn len(&self) -> usize {
548 self.rows.len()
549 }
550
551 #[inline]
553 #[must_use]
554 pub fn is_empty(&self) -> bool {
555 self.rows.is_empty()
556 }
557
558 #[inline]
560 #[must_use]
561 pub const fn row_len(&self) -> usize {
562 self.row_len
563 }
564
565 #[inline]
567 #[must_use]
568 pub fn blocks(&self) -> usize {
569 self.blocks.len()
570 }
571
572 #[must_use]
574 pub fn count_nonzero(&self) -> usize {
575 self.rows.iter().map(|row| row.len as usize).sum()
576 }
577
578 #[must_use]
580 pub fn allocated_bytes(&self) -> usize {
581 self.blocks
582 .iter()
583 .map(|block| block.capacity() * std::mem::size_of::<Index>())
584 .sum::<usize>()
585 + self.rows.capacity() * std::mem::size_of::<RowRef>()
586 + self.scratch.capacity() * std::mem::size_of::<Index>()
587 }
588
589 #[inline]
591 #[must_use]
592 pub fn row(&self, index: usize) -> Option<RowSlice<'_>> {
593 self.slice_of(self.rows.get(index)?)
594 }
595
596 #[inline]
598 fn slice_of(&self, row: &RowRef) -> Option<RowSlice<'_>> {
599 let start = row.offset as usize;
600 Some(RowSlice {
601 indices: self
602 .blocks
603 .get(row.block as usize)?
604 .get(start..start + row.len as usize)?,
605 len: self.row_len,
606 })
607 }
608
609 pub fn iter(&self) -> impl Iterator<Item = RowSlice<'_>> + '_ {
611 self.rows.iter().filter_map(|row| self.slice_of(row))
612 }
613
614 pub fn row_builder(&mut self) -> Result<RowBuilder<'_>> {
620 ensure!(
621 u32::try_from(self.rows.len()).is_ok(),
622 "A dataset cannot hold more than {} rows",
623 u32::MAX
624 );
625
626 self.scratch.clear();
627 Ok(RowBuilder {
628 matrix: self,
629 sorted: true,
630 })
631 }
632
633 pub fn push_row(&mut self, row: RowSlice<'_>) -> Result<()> {
640 ensure!(
641 row.len() == self.row_len,
642 "Row spans {} features, expected {}",
643 row.len(),
644 self.row_len
645 );
646
647 self.append(row.indices)
649 }
650
651 fn append(&mut self, indices: &[Index]) -> Result<()> {
653 let descriptor = self.reserve(indices.len())?;
654 let start = descriptor.offset as usize;
655 self.blocks[descriptor.block as usize][start..start + indices.len()]
656 .copy_from_slice(indices);
657 self.rows.push(descriptor);
658 Ok(())
659 }
660
661 fn reserve(&mut self, count: usize) -> Result<RowRef> {
666 let fits = self
667 .blocks
668 .last()
669 .is_some_and(|block| block.len() + count <= block.capacity());
670
671 if !fits {
672 self.blocks
674 .push(Vec::with_capacity(count.max(BLOCK_INDICES)));
675 }
676
677 let block_index = self.blocks.len() - 1;
678 let block = &mut self.blocks[block_index];
679 let offset = block.len();
680 block.resize(offset + count, 0);
681
682 Ok(RowRef {
683 block: u32::try_from(block_index).map_err(|_| anyhow!("Too many storage blocks"))?,
684 offset: u32::try_from(offset)
685 .map_err(|_| anyhow!("Block offset {offset} is too large"))?,
686 len: u32::try_from(count)
687 .map_err(|_| anyhow!("A row cannot hold more than {} features", u32::MAX))?,
688 })
689 }
690
691 pub fn permute(&mut self, permutation: &[usize]) -> Result<()> {
699 ensure!(
700 permutation.len() == self.rows.len(),
701 "Permutation has {} entries, expected {}",
702 permutation.len(),
703 self.rows.len()
704 );
705
706 self.rows = permutation.iter().map(|from| self.rows[*from]).collect();
707 Ok(())
708 }
709
710 pub fn split_off(&mut self, at: usize) -> Result<Self> {
719 ensure!(
720 at <= self.len(),
721 "Split index {at} is beyond the {} rows available",
722 self.len()
723 );
724
725 let mut tail = Self::new(self.row_len);
726 for index in at..self.len() {
727 if let Some(row) = self.row(index) {
728 tail.push_row(row)?;
729 }
730 }
731 self.rows.truncate(at);
732 Ok(tail)
733 }
734
735 pub fn retain_indices(&mut self, keep: &[usize]) -> Result<()> {
745 let remap = Remap::new(self.row_len, keep);
746 let mut rebuilt = Self::new(keep.len());
747
748 for index in 0..self.len() {
749 let Some(row) = self.row(index) else { continue };
750 rebuilt.append(&remap.apply(row.indices))?;
751 }
752
753 *self = rebuilt;
754 Ok(())
755 }
756
757 #[must_use]
761 pub fn column_sums(&self) -> Vec<f32> {
762 let mut sums = vec![0.0f32; self.row_len];
763 for row in self.iter() {
764 for index in row.indices {
765 if let Some(sum) = sums.get_mut(*index as usize) {
766 *sum += 1.0;
767 }
768 }
769 }
770 sums
771 }
772}
773
774impl PartialEq for DataMatrix {
775 fn eq(&self, other: &Self) -> bool {
776 self.row_len == other.row_len
777 && self.len() == other.len()
778 && self.iter().zip(other.iter()).all(|(a, b)| a == b)
779 }
780}
781
782impl FromIterator<DataRow> for DataMatrix {
787 fn from_iter<I: IntoIterator<Item = DataRow>>(iter: I) -> Self {
788 let mut rows = iter.into_iter();
789 let Some(first) = rows.next() else {
790 return Self::new(0);
791 };
792
793 let mut matrix = Self::new(first.len());
794 let _ = matrix.push_row(first.as_slice());
795 for row in rows {
796 let _ = matrix.push_row(row.as_slice());
797 }
798 matrix
799 }
800}
801
802pub struct RowBuilder<'a> {
808 matrix: &'a mut DataMatrix,
810
811 sorted: bool,
813}
814
815impl RowBuilder<'_> {
816 #[inline]
824 pub fn push(&mut self, index: usize, value: f32) -> Result<()> {
825 ensure!(
826 index < self.matrix.row_len,
827 "Feature index {index} is out of bounds for a dataset of {} features",
828 self.matrix.row_len
829 );
830
831 if !binary_value(value, index)? {
832 return Ok(());
833 }
834
835 let index = to_index(index)?;
836 if self.sorted
837 && self
838 .matrix
839 .scratch
840 .last()
841 .is_some_and(|last| *last >= index)
842 {
843 self.sorted = false;
844 }
845 self.matrix.scratch.push(index);
846 Ok(())
847 }
848
849 pub fn finish(self) -> Result<()> {
855 let matrix = self.matrix;
856
857 if !self.sorted {
859 matrix.scratch.sort_unstable();
860 }
861
862 if let Some([duplicate, _]) = matrix
864 .scratch
865 .windows(2)
866 .find(|pair| pair[0] == pair[1])
867 .and_then(|pair| <&[Index; 2]>::try_from(pair).ok())
868 {
869 bail!("Feature index {duplicate} is listed more than once on the same row");
870 }
871
872 let count = matrix.scratch.len();
873 let descriptor = matrix.reserve(count)?;
874 let start = descriptor.offset as usize;
875 let block = &mut matrix.blocks[descriptor.block as usize];
877 block[start..start + count].copy_from_slice(&matrix.scratch);
878 matrix.rows.push(descriptor);
879 Ok(())
880 }
881}
882
883impl Serialize for DataMatrix {
884 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
885 serializer.collect_seq(self.iter())
886 }
887}
888
889impl<'de> Deserialize<'de> for DataMatrix {
890 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
891 struct MatrixVisitor;
892
893 impl<'de> Visitor<'de> for MatrixVisitor {
894 type Value = DataMatrix;
895
896 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
897 f.write_str("a sequence of dataset rows")
898 }
899
900 fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
901 use serde::de::Error;
902
903 let mut matrix: Option<DataMatrix> = None;
904 while let Some(row) = seq.next_element::<DataRow>()? {
905 let matrix = matrix.get_or_insert_with(|| DataMatrix::new(row.len()));
906 matrix.push_row(row.as_slice()).map_err(A::Error::custom)?;
907 }
908
909 Ok(matrix.unwrap_or_else(|| DataMatrix::new(0)))
910 }
911 }
912
913 deserializer.deserialize_seq(MatrixVisitor)
914 }
915}
916
917#[cfg(test)]
918mod tests {
919 use super::{BLOCK_INDICES, DataMatrix, DataRow, RowAccumulator, RowRef, bytes_per_row};
920
921 #[test]
922 fn binary_round_trip() {
923 let values = [1.0f32, 0.0, 0.0, 1.0, 1.0, 0.0];
924 let row = DataRow::try_from(values.as_slice()).unwrap();
925
926 assert_eq!(row.len(), values.len());
927 assert!(!row.is_empty());
928 assert_eq!(row.iter().collect::<Vec<_>>(), values);
929 assert_eq!(row.count_nonzero(), 3);
930 assert!((row.sum() - 3.0).abs() < 1e-6);
931 assert_eq!(
932 row.iter_nonzero().collect::<Vec<_>>(),
933 vec![(0, 1.0), (3, 1.0), (4, 1.0)]
934 );
935
936 for (index, value) in values.iter().enumerate() {
937 assert_eq!(row.get(index), Some(*value));
938 }
939 assert_eq!(row.get(values.len()), None);
940 }
941
942 #[test]
943 fn dot_matches_naive() {
944 let values = [1.0f32, 0.0, 1.0, 0.0, 1.0];
945 let weights = [0.5f32, -2.0, 0.25, 7.0, -0.75];
946 let row = DataRow::try_from(values.as_slice()).unwrap();
947
948 let naive: f32 = values.iter().zip(&weights).map(|(v, w)| v * w).sum();
949 assert!((row.dot(&weights) - naive).abs() < 1e-6);
950 }
951
952 #[test]
953 fn set_keeps_indices_sorted_and_unique() {
954 let mut row = DataRow::zeroed(70);
955 assert_eq!(row.count_nonzero(), 0);
956
957 row.set(69, 1.0).unwrap();
959 row.set(0, 1.0).unwrap();
960 row.set(64, 1.0).unwrap();
961 assert_eq!(row.as_slice().indices(), &[0, 64, 69]);
962
963 row.set(64, 1.0).unwrap();
965 assert_eq!(row.count_nonzero(), 3);
966
967 row.set(64, 0.0).unwrap();
968 assert_eq!(row.as_slice().indices(), &[0, 69]);
969
970 row.set(5, 0.0).unwrap();
972 assert_eq!(row.count_nonzero(), 2);
973
974 assert!(
975 row.set(70, 1.0).is_err(),
976 "out of bounds index must be rejected"
977 );
978 }
979
980 #[test]
981 fn retain_indices_renumbers() {
982 let row = DataRow::try_from([1.0f32, 0.0, 1.0, 1.0, 0.0].as_slice()).unwrap();
983 let kept = row.retain_indices(&[1, 2, 4]);
984
985 assert_eq!(kept.len(), 3);
986 assert_eq!(kept.iter().collect::<Vec<_>>(), vec![0.0, 1.0, 0.0]);
987 assert_eq!(kept.as_slice().indices(), &[1]);
988 }
989
990 #[test]
991 fn serde_is_a_flat_sequence() {
992 let row = DataRow::try_from([1.0f32, 0.0, 1.0].as_slice()).unwrap();
995 let json = serde_json::to_string(&row).unwrap();
996 assert_eq!(json, "[1.0,0.0,1.0]");
997
998 let back: DataRow = serde_json::from_str(&json).unwrap();
999 assert_eq!(back, row);
1000 }
1001
1002 #[test]
1003 fn non_binary_values_are_rejected_not_rounded() {
1004 let mut row = DataRow::zeroed(3);
1005 let err = row.set(1, 0.5).unwrap_err().to_string();
1006 assert!(err.contains("not 0 or 1"), "unexpected error: {err}");
1007
1008 assert!(DataRow::try_from([0.0f32, 0.5].as_slice()).is_err());
1009 }
1010
1011 #[test]
1012 fn accumulator_deduplicates_and_sorts() {
1013 let mut acc = RowAccumulator::new(200);
1014 assert!(!acc.is_empty());
1015 assert_eq!(acc.len(), 200);
1016
1017 for index in [130usize, 1, 199, 64, 1, 130, 0, 65, 130] {
1019 acc.set(index).unwrap();
1020 }
1021 assert!(acc.set(200).is_err());
1022 assert_eq!(acc.count(), 6);
1023
1024 let row = acc.build();
1025 assert_eq!(row.len(), 200);
1026 assert_eq!(row.as_slice().indices(), &[0, 1, 64, 65, 130, 199]);
1027
1028 acc.clear();
1029 assert_eq!(acc.count(), 0);
1030 assert_eq!(acc.build().count_nonzero(), 0);
1031 }
1032
1033 #[test]
1034 fn accumulator_ignores_padding_bits() {
1035 let mut acc = RowAccumulator::new(10);
1037 for index in 0..10 {
1038 acc.set(index).unwrap();
1039 }
1040 assert_eq!(acc.build().as_slice().indices().len(), 10);
1041 assert!(acc.set(10).is_err());
1042 }
1043
1044 #[test]
1045 fn builder_accepts_unsorted_input() {
1046 let mut matrix = DataMatrix::new(100);
1047 let mut row = matrix.row_builder().unwrap();
1048 for index in [90usize, 3, 50, 0] {
1049 row.push(index, 1.0).unwrap();
1050 }
1051 row.finish().unwrap();
1052
1053 assert_eq!(
1054 matrix.row(0).unwrap().indices(),
1055 &[0, 3, 50, 90],
1056 "indices must come out sorted"
1057 );
1058 }
1059
1060 #[test]
1061 fn builder_rejects_duplicates() {
1062 let mut matrix = DataMatrix::new(100);
1063 let mut row = matrix.row_builder().unwrap();
1064 row.push(7, 1.0).unwrap();
1065 row.push(7, 1.0).unwrap();
1066
1067 let err = row.finish().unwrap_err().to_string();
1068 assert!(err.contains("more than once"), "unexpected error: {err}");
1069 }
1070
1071 #[test]
1072 fn builder_skips_zeroes_and_bounds_checks() {
1073 let mut matrix = DataMatrix::new(10);
1074 let mut row = matrix.row_builder().unwrap();
1075 for index in 0..10 {
1076 row.push(index, f32::from(index % 3 == 0)).unwrap();
1077 }
1078 assert!(row.push(10, 1.0).is_err(), "out of bounds must be rejected");
1079 row.finish().unwrap();
1080
1081 assert_eq!(matrix.row(0).unwrap().indices(), &[0, 3, 6, 9]);
1082 assert_eq!(matrix.count_nonzero(), 4);
1083 }
1084
1085 #[test]
1087 fn dropped_builder_records_nothing() {
1088 let mut matrix = DataMatrix::new(10);
1089 {
1090 let mut row = matrix.row_builder().unwrap();
1091 row.push(3, 1.0).unwrap();
1092 }
1093 assert_eq!(matrix.len(), 0);
1094
1095 let mut row = matrix.row_builder().unwrap();
1096 row.push(5, 1.0).unwrap();
1097 row.finish().unwrap();
1098 assert_eq!(matrix.len(), 1);
1099 assert_eq!(matrix.row(0).unwrap().indices(), &[5]);
1100 }
1101
1102 #[test]
1105 fn matrix_spans_many_blocks() {
1106 const FEATURES: usize = 1_000_000;
1107 const PER_ROW: usize = 5000;
1108
1109 let rows = (BLOCK_INDICES / PER_ROW) * 3 + 5;
1110 let mut matrix = DataMatrix::new(FEATURES);
1111
1112 for row_index in 0..rows {
1113 let mut row = matrix.row_builder().unwrap();
1114 for step in 0..PER_ROW {
1115 row.push((row_index + step * 97) % FEATURES, 1.0).unwrap();
1116 }
1117 row.finish().unwrap();
1118 }
1119
1120 assert_eq!(matrix.len(), rows);
1121 assert!(
1122 matrix.blocks() >= 4,
1123 "expected several blocks, got {}",
1124 matrix.blocks()
1125 );
1126
1127 for row_index in 0..rows {
1128 let row = matrix.row(row_index).unwrap();
1129 assert_eq!(row.len(), FEATURES);
1130 assert_eq!(row.count_nonzero(), PER_ROW, "row {row_index}");
1131
1132 let mut expected = (0..PER_ROW)
1133 .map(|step| u32::try_from((row_index + step * 97) % FEATURES).unwrap())
1134 .collect::<Vec<_>>();
1135 expected.sort_unstable();
1136 assert_eq!(row.indices(), expected.as_slice(), "row {row_index}");
1137 }
1138
1139 assert_eq!(matrix.row(rows), None);
1140 }
1141
1142 #[test]
1144 fn matrix_handles_row_larger_than_a_block() {
1145 let features = BLOCK_INDICES * 2;
1146 let mut matrix = DataMatrix::new(features);
1147
1148 let mut row = matrix.row_builder().unwrap();
1149 for index in (0..features).step_by(2) {
1150 row.push(index, 1.0).unwrap();
1151 }
1152 row.finish().unwrap();
1153
1154 let stored = matrix.row(0).unwrap();
1155 assert_eq!(stored.count_nonzero(), features / 2);
1156 assert_eq!(stored.indices().first(), Some(&0));
1157 assert_eq!(
1158 stored.indices().last(),
1159 Some(&u32::try_from(features - 2).unwrap())
1160 );
1161 }
1162
1163 #[test]
1164 fn matrix_permute_reorders_without_copying_indices() {
1165 let mut matrix = DataMatrix::new(8);
1166 for row_index in 0..4 {
1167 let mut row = matrix.row_builder().unwrap();
1168 row.push(row_index, 1.0).unwrap();
1169 row.finish().unwrap();
1170 }
1171
1172 let before = matrix.allocated_bytes();
1173 matrix.permute(&[3, 1, 0, 2]).unwrap();
1174 assert_eq!(
1175 matrix.allocated_bytes(),
1176 before,
1177 "permute must not allocate"
1178 );
1179
1180 let seen = (0..4)
1181 .map(|i| matrix.row(i).unwrap().indices()[0])
1182 .collect::<Vec<_>>();
1183 assert_eq!(seen, vec![3, 1, 0, 2]);
1184
1185 assert!(matrix.permute(&[0, 1]).is_err(), "length must be checked");
1186 }
1187
1188 #[test]
1189 fn matrix_split_off_and_retain() {
1190 let mut matrix = DataMatrix::new(6);
1191 for row_index in 0..10 {
1192 let mut row = matrix.row_builder().unwrap();
1193 row.push(row_index % 6, 1.0).unwrap();
1194 row.finish().unwrap();
1195 }
1196
1197 let tail = matrix.split_off(7).unwrap();
1198 assert_eq!(matrix.len(), 7);
1199 assert_eq!(tail.len(), 3);
1200 assert_eq!(
1201 tail.row(0).unwrap().indices(),
1202 &[u32::try_from(7 % 6).unwrap()]
1203 );
1204
1205 matrix.retain_indices(&[1, 3, 5]).unwrap();
1206 assert_eq!(matrix.row_len(), 3);
1207 assert_eq!(matrix.len(), 7);
1208 assert_eq!(matrix.row(1).unwrap().indices(), &[0]);
1210 assert_eq!(matrix.row(0).unwrap().count_nonzero(), 0);
1212 }
1213
1214 #[test]
1215 fn matrix_column_sums() {
1216 let mut matrix = DataMatrix::new(4);
1217 for pattern in [vec![0usize, 2], vec![2], vec![1, 2, 3]] {
1218 let mut row = matrix.row_builder().unwrap();
1219 for index in pattern {
1220 row.push(index, 1.0).unwrap();
1221 }
1222 row.finish().unwrap();
1223 }
1224
1225 assert_eq!(matrix.column_sums(), vec![1.0, 1.0, 3.0, 1.0]);
1226 }
1227
1228 #[test]
1229 fn matrix_serde_round_trip() {
1230 let mut matrix = DataMatrix::new(4);
1231 for row_index in 0..3 {
1232 let mut row = matrix.row_builder().unwrap();
1233 row.push(row_index, 1.0).unwrap();
1234 row.finish().unwrap();
1235 }
1236
1237 let json = serde_json::to_string(&matrix).unwrap();
1238 let back: DataMatrix = serde_json::from_str(&json).unwrap();
1239 assert_eq!(back, matrix);
1240 }
1241
1242 #[test]
1244 fn matrix_overhead_is_bounded() {
1245 const FEATURES: usize = 1_000_000;
1246 const PER_ROW: usize = 6900;
1247
1248 for rows in [1usize, 10, 400] {
1249 let mut matrix = DataMatrix::new(FEATURES);
1250 for row_index in 0..rows {
1251 let mut row = matrix.row_builder().unwrap();
1252 for step in 0..PER_ROW {
1253 row.push((row_index + step * 101) % FEATURES, 1.0).unwrap();
1254 }
1255 row.finish().unwrap();
1256 }
1257
1258 let payload = rows * bytes_per_row(PER_ROW);
1259 let actual = matrix.allocated_bytes();
1260 assert!(
1261 actual >= payload,
1262 "{rows} rows: {actual} < payload {payload}"
1263 );
1264
1265 let slack = BLOCK_INDICES * std::mem::size_of::<u32>()
1267 + rows * std::mem::size_of::<RowRef>() * 2
1268 + bytes_per_row(PER_ROW) * 2;
1269 assert!(
1270 actual - payload <= slack,
1271 "{rows} rows: overhead {} exceeds {slack}",
1272 actual - payload
1273 );
1274 }
1275 }
1276}