Skip to main content

embeddenator_vsa/
lib.rs

1//! Embeddenator VSA - Vector Symbolic Architecture Core
2//!
3//! This crate provides the foundational Vector Symbolic Architecture (VSA)
4//! operations for sparse ternary representations used in Embeddenator.
5//!
6//! # Overview
7//!
8//! VSA is a computational framework for representing and manipulating
9//! high-dimensional vectors through algebraic operations:
10//!
11//! - **Bundle (⊕)**: Superposition of multiple vectors
12//! - **Bind (⊙)**: Compositional binding of associations
13//! - **Similarity**: Cosine similarity for pattern retrieval
14//!
15//! # Core Types
16//!
17//! - [`SparseVec`]: Sparse ternary vector representation
18//! - [`PackedTritVec`]: Memory-efficient packed trit storage
19//! - [`Codebook`]: Mapping between symbols and vectors
20//!
21//! # Example
22//!
23//! ```rust
24//! use embeddenator_vsa::{SparseVec, ReversibleVSAConfig};
25//!
26//! // Create random sparse vectors
27//! let a = SparseVec::random();
28//! let b = SparseVec::random();
29//!
30//! // Bundle operation (superposition)
31//! let bundled = a.bundle(&b);
32//!
33//! // Compute similarity
34//! let similarity = a.cosine(&b);
35//! assert!(similarity >= -1.0 && similarity <= 1.0);
36//! ```
37
38use std::fmt;
39
40/// Unified error type for VSA operations
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub enum VsaError {
43    /// Value is outside the valid range for the operation
44    ValueOutOfRange { value: i64, min: i64, max: i64 },
45    /// Hash operation produced unexpected length
46    InvalidHashLength { expected: usize, actual: usize },
47    /// Operation expected a non-empty collection
48    EmptyCollection,
49    /// Packed data could not be unpacked
50    InvalidPackedData,
51    /// Value cannot be converted to the target type
52    InvalidValue(String),
53}
54
55impl fmt::Display for VsaError {
56    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57        match self {
58            VsaError::ValueOutOfRange { value, min, max } => {
59                write!(
60                    f,
61                    "Value {} is outside valid range [{}, {}]",
62                    value, min, max
63                )
64            }
65            VsaError::InvalidHashLength { expected, actual } => {
66                write!(
67                    f,
68                    "Invalid hash length: expected {}, got {}",
69                    expected, actual
70                )
71            }
72            VsaError::EmptyCollection => {
73                write!(f, "Operation requires non-empty collection")
74            }
75            VsaError::InvalidPackedData => {
76                write!(f, "Packed data could not be unpacked")
77            }
78            VsaError::InvalidValue(msg) => {
79                write!(f, "Invalid value: {}", msg)
80            }
81        }
82    }
83}
84
85impl std::error::Error for VsaError {}
86
87pub mod codebook;
88pub mod dimensional;
89#[cfg(feature = "cuda")]
90pub mod gpu;
91pub mod simd_cosine;
92pub mod ternary;
93pub mod ternary_vec;
94pub mod vsa;
95
96// Re-export main types
97pub use codebook::{
98    BalancedTernaryWord, Codebook, ProjectionConfig, ProjectionResult, SemanticOutlier,
99    WordMetadata,
100};
101pub use dimensional::{
102    DifferentialEncoder, DifferentialEncoding, DimensionalConfig, HyperVec, Trit as DimTrit,
103    TritDepthConfig, Tryte,
104};
105#[cfg(feature = "cuda")]
106pub use gpu::{
107    GpuArch, GpuBackend, GpuConfig, GpuError, GpuMemoryConfig, DEFAULT_MEMORY_HEADROOM_PERCENT,
108    MAX_MEMORY_USAGE_RATIO, MIN_SYSTEM_RESERVE_BYTES,
109};
110#[cfg(all(target_arch = "x86_64", target_feature = "avx2"))]
111pub use simd_cosine::cosine_avx2;
112#[cfg(target_arch = "aarch64")]
113pub use simd_cosine::cosine_neon;
114pub use simd_cosine::cosine_scalar;
115pub use ternary::{CorrectionEntry, ParityTrit, Trit, Tryte3, Word6};
116pub use ternary_vec::PackedTritVec;
117pub use vsa::{ReversibleVSAConfig, SparseVec, SparsityScaling, VsaConfig, VsaConfigSchema, DIM};