pub struct SparseVec { /* private fields */ }Expand description
A sparse ternary vector using COO (Coordinate) format.
Only non-zero values are stored, making this efficient for vectors where most elements are zero (high sparsity).
§Storage
Non-zero indices are stored separately for positive and negative values:
positive_indices: indices where value is +1negative_indices: indices where value is -1
§When to Use
Use SparseVec when sparsity > 90% for memory efficiency.
Use PackedTritVec for denser vectors or when operations like dot product
need consistent O(n) time regardless of sparsity.
§Examples
use trit_vsa::{SparseVec, Trit};
let mut vec = SparseVec::new(1000);
vec.set(10, Trit::P);
vec.set(500, Trit::N);
assert_eq!(vec.get(10), Trit::P);
assert_eq!(vec.get(500), Trit::N);
assert_eq!(vec.get(0), Trit::Z);
assert_eq!(vec.count_nonzero(), 2);Implementations§
Source§impl SparseVec
impl SparseVec
Sourcepub fn new(num_dims: usize) -> Self
pub fn new(num_dims: usize) -> Self
Create a new sparse vector with given dimension count.
All values are initialized to zero (no storage needed).
Sourcepub fn from_indices(
positive_indices: Vec<usize>,
negative_indices: Vec<usize>,
num_dims: usize,
) -> Result<Self>
pub fn from_indices( positive_indices: Vec<usize>, negative_indices: Vec<usize>, num_dims: usize, ) -> Result<Self>
Sourcepub fn from_trits(trits: &[Trit]) -> Self
pub fn from_trits(trits: &[Trit]) -> Self
Create from a slice of trits.
Sourcepub fn from_packed(packed: &PackedTritVec) -> Self
pub fn from_packed(packed: &PackedTritVec) -> Self
Create from a PackedTritVec.
Sourcepub fn count_nonzero(&self) -> usize
pub fn count_nonzero(&self) -> usize
Count non-zero elements.
Sourcepub fn count_positive(&self) -> usize
pub fn count_positive(&self) -> usize
Count positive (+1) elements.
Sourcepub fn count_negative(&self) -> usize
pub fn count_negative(&self) -> usize
Count negative (-1) elements.
Sourcepub fn dot(&self, other: &SparseVec) -> i32
pub fn dot(&self, other: &SparseVec) -> i32
Compute dot product with another sparse vector.
This is O(k1 + k2) where k1 and k2 are the number of non-zero elements.
§Panics
Panics if vectors have different dimensions.
Sourcepub fn dot_packed(&self, other: &PackedTritVec) -> i32
pub fn dot_packed(&self, other: &PackedTritVec) -> i32
Compute dot product with a packed vector.
Efficient when this sparse vector has few non-zeros.
§Panics
Panics if vectors have different dimensions.
Sourcepub fn positive_indices(&self) -> &[usize]
pub fn positive_indices(&self) -> &[usize]
Get reference to positive indices.
Sourcepub fn negative_indices(&self) -> &[usize]
pub fn negative_indices(&self) -> &[usize]
Get reference to negative indices.
Sourcepub fn to_packed(&self) -> PackedTritVec
pub fn to_packed(&self) -> PackedTritVec
Convert to a PackedTritVec.
Sourcepub fn memory_bytes(&self) -> usize
pub fn memory_bytes(&self) -> usize
Memory size in bytes (approximate).