ruvector-nervous-system 2.0.6

Bio-inspired neural system with spiking networks, BTSP learning, and EWC plasticity
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
//! Sparse bit vector for efficient k-winners-take-all representation
//!
//! Implements memory-efficient sparse bit vectors using index lists
//! with fast set operations for similarity computation.

use serde::{Deserialize, Serialize};
use std::collections::HashSet;

/// Sparse bit vector storing only active indices
///
/// Efficient representation for sparse binary vectors where only
/// a small fraction of bits are set (active). Stores only the indices
/// of active bits rather than the full bit array.
///
/// # Properties
///
/// - Memory: O(k) where k is number of active bits
/// - Set operations: O(k1 + k2) for intersection/union
/// - Typical k: 200-500 active bits out of 10000+ total
///
/// # Example
///
/// ```
/// use ruvector_nervous_system::SparseBitVector;
///
/// let mut sparse = SparseBitVector::new(10000);
/// sparse.set(42);
/// sparse.set(100);
/// sparse.set(500);
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SparseBitVector {
    /// Sorted list of active bit indices
    pub indices: Vec<u16>,

    /// Total capacity (maximum index + 1)
    capacity: u16,
}

impl SparseBitVector {
    /// Create a new sparse bit vector with given capacity
    ///
    /// # Arguments
    ///
    /// * `capacity` - Maximum number of bits (max index + 1)
    ///
    /// # Example
    ///
    /// ```
    /// use ruvector_nervous_system::SparseBitVector;
    ///
    /// let sparse = SparseBitVector::new(10000);
    /// ```
    pub fn new(capacity: u16) -> Self {
        Self {
            indices: Vec::new(),
            capacity,
        }
    }

    /// Create from a list of active indices
    ///
    /// # Arguments
    ///
    /// * `indices` - Vector of active bit indices
    /// * `capacity` - Total capacity
    ///
    /// # Example
    ///
    /// ```
    /// use ruvector_nervous_system::SparseBitVector;
    ///
    /// let sparse = SparseBitVector::from_indices(vec![10, 20, 30], 10000);
    /// ```
    pub fn from_indices(mut indices: Vec<u16>, capacity: u16) -> Self {
        indices.sort_unstable();
        indices.dedup();
        Self { indices, capacity }
    }

    /// Set a bit to active
    ///
    /// # Arguments
    ///
    /// * `index` - Bit index to set
    ///
    /// # Panics
    ///
    /// Panics if index >= capacity
    pub fn set(&mut self, index: u16) {
        assert!(index < self.capacity, "Index out of bounds");

        // Binary search for insertion point
        match self.indices.binary_search(&index) {
            Ok(_) => {} // Already present
            Err(pos) => self.indices.insert(pos, index),
        }
    }

    /// Check if a bit is active
    ///
    /// # Arguments
    ///
    /// * `index` - Bit index to check
    ///
    /// # Returns
    ///
    /// true if bit is set, false otherwise
    pub fn is_set(&self, index: u16) -> bool {
        self.indices.binary_search(&index).is_ok()
    }

    /// Get number of active bits
    pub fn count(&self) -> usize {
        self.indices.len()
    }

    /// Get capacity
    pub fn capacity(&self) -> u16 {
        self.capacity
    }

    /// Compute intersection with another sparse bit vector
    ///
    /// # Arguments
    ///
    /// * `other` - Other sparse bit vector
    ///
    /// # Returns
    ///
    /// New sparse bit vector containing intersection
    ///
    /// # Example
    ///
    /// ```
    /// use ruvector_nervous_system::SparseBitVector;
    ///
    /// let a = SparseBitVector::from_indices(vec![1, 2, 3], 100);
    /// let b = SparseBitVector::from_indices(vec![2, 3, 4], 100);
    /// let intersection = a.intersection(&b);
    /// assert_eq!(intersection.count(), 2); // {2, 3}
    /// ```
    pub fn intersection(&self, other: &Self) -> Self {
        let mut result = Vec::new();
        let mut i = 0;
        let mut j = 0;

        // Merge algorithm for sorted lists
        while i < self.indices.len() && j < other.indices.len() {
            match self.indices[i].cmp(&other.indices[j]) {
                std::cmp::Ordering::Equal => {
                    result.push(self.indices[i]);
                    i += 1;
                    j += 1;
                }
                std::cmp::Ordering::Less => i += 1,
                std::cmp::Ordering::Greater => j += 1,
            }
        }

        Self {
            indices: result,
            capacity: self.capacity,
        }
    }

    /// Compute union with another sparse bit vector
    ///
    /// # Arguments
    ///
    /// * `other` - Other sparse bit vector
    ///
    /// # Returns
    ///
    /// New sparse bit vector containing union
    pub fn union(&self, other: &Self) -> Self {
        let mut result = Vec::new();
        let mut i = 0;
        let mut j = 0;

        while i < self.indices.len() && j < other.indices.len() {
            match self.indices[i].cmp(&other.indices[j]) {
                std::cmp::Ordering::Equal => {
                    result.push(self.indices[i]);
                    i += 1;
                    j += 1;
                }
                std::cmp::Ordering::Less => {
                    result.push(self.indices[i]);
                    i += 1;
                }
                std::cmp::Ordering::Greater => {
                    result.push(other.indices[j]);
                    j += 1;
                }
            }
        }

        // Add remaining elements
        while i < self.indices.len() {
            result.push(self.indices[i]);
            i += 1;
        }
        while j < other.indices.len() {
            result.push(other.indices[j]);
            j += 1;
        }

        Self {
            indices: result,
            capacity: self.capacity,
        }
    }

    /// Compute Jaccard similarity with another sparse bit vector
    ///
    /// Jaccard similarity = |A ∩ B| / |A ∪ B|
    ///
    /// # Arguments
    ///
    /// * `other` - Other sparse bit vector
    ///
    /// # Returns
    ///
    /// Similarity in range [0.0, 1.0]
    ///
    /// # Example
    ///
    /// ```
    /// use ruvector_nervous_system::SparseBitVector;
    ///
    /// let a = SparseBitVector::from_indices(vec![1, 2, 3], 100);
    /// let b = SparseBitVector::from_indices(vec![2, 3, 4], 100);
    /// let sim = a.jaccard_similarity(&b);
    /// assert!((sim - 0.5).abs() < 0.001); // 2/4 = 0.5
    /// ```
    pub fn jaccard_similarity(&self, other: &Self) -> f32 {
        if self.indices.is_empty() && other.indices.is_empty() {
            return 1.0;
        }

        let intersection_size = self.intersection_size(other);
        let union_size = self.indices.len() + other.indices.len() - intersection_size;

        if union_size == 0 {
            return 0.0;
        }

        intersection_size as f32 / union_size as f32
    }

    /// Compute Hamming distance with another sparse bit vector
    ///
    /// Hamming distance = number of positions where bits differ
    ///
    /// # Arguments
    ///
    /// * `other` - Other sparse bit vector
    ///
    /// # Returns
    ///
    /// Hamming distance (number of differing bits)
    pub fn hamming_distance(&self, other: &Self) -> u32 {
        let intersection_size = self.intersection_size(other);
        let total_active = self.indices.len() + other.indices.len();
        (total_active - 2 * intersection_size) as u32
    }

    /// Helper: compute intersection size efficiently
    fn intersection_size(&self, other: &Self) -> usize {
        let mut count = 0;
        let mut i = 0;
        let mut j = 0;

        while i < self.indices.len() && j < other.indices.len() {
            match self.indices[i].cmp(&other.indices[j]) {
                std::cmp::Ordering::Equal => {
                    count += 1;
                    i += 1;
                    j += 1;
                }
                std::cmp::Ordering::Less => i += 1,
                std::cmp::Ordering::Greater => j += 1,
            }
        }

        count
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_sparse_bitvector_creation() {
        let sparse = SparseBitVector::new(10000);
        assert_eq!(sparse.count(), 0);
        assert_eq!(sparse.capacity(), 10000);
    }

    #[test]
    fn test_set_and_check() {
        let mut sparse = SparseBitVector::new(100);
        sparse.set(10);
        sparse.set(20);
        sparse.set(30);

        assert!(sparse.is_set(10));
        assert!(sparse.is_set(20));
        assert!(sparse.is_set(30));
        assert!(!sparse.is_set(15));
        assert_eq!(sparse.count(), 3);
    }

    #[test]
    fn test_from_indices() {
        let sparse = SparseBitVector::from_indices(vec![30, 10, 20, 10], 100);
        assert_eq!(sparse.count(), 3); // Deduped
        assert!(sparse.is_set(10));
        assert!(sparse.is_set(20));
        assert!(sparse.is_set(30));
    }

    #[test]
    fn test_intersection() {
        let a = SparseBitVector::from_indices(vec![1, 2, 3, 4], 100);
        let b = SparseBitVector::from_indices(vec![3, 4, 5, 6], 100);
        let intersection = a.intersection(&b);

        assert_eq!(intersection.count(), 2);
        assert!(intersection.is_set(3));
        assert!(intersection.is_set(4));
    }

    #[test]
    fn test_union() {
        let a = SparseBitVector::from_indices(vec![1, 2, 3], 100);
        let b = SparseBitVector::from_indices(vec![3, 4, 5], 100);
        let union = a.union(&b);

        assert_eq!(union.count(), 5);
        for i in 1..=5 {
            assert!(union.is_set(i));
        }
    }

    #[test]
    fn test_jaccard_similarity() {
        let a = SparseBitVector::from_indices(vec![1, 2, 3, 4], 100);
        let b = SparseBitVector::from_indices(vec![3, 4, 5, 6], 100);

        // Intersection: {3, 4} = 2
        // Union: {1, 2, 3, 4, 5, 6} = 6
        // Jaccard = 2/6 = 0.333...
        let sim = a.jaccard_similarity(&b);
        assert!((sim - 0.333333).abs() < 0.001);
    }

    #[test]
    fn test_jaccard_identical() {
        let a = SparseBitVector::from_indices(vec![1, 2, 3], 100);
        let b = SparseBitVector::from_indices(vec![1, 2, 3], 100);

        let sim = a.jaccard_similarity(&b);
        assert_eq!(sim, 1.0);
    }

    #[test]
    fn test_jaccard_disjoint() {
        let a = SparseBitVector::from_indices(vec![1, 2, 3], 100);
        let b = SparseBitVector::from_indices(vec![4, 5, 6], 100);

        let sim = a.jaccard_similarity(&b);
        assert_eq!(sim, 0.0);
    }

    #[test]
    fn test_hamming_distance() {
        let a = SparseBitVector::from_indices(vec![1, 2, 3, 4], 100);
        let b = SparseBitVector::from_indices(vec![3, 4, 5, 6], 100);

        // Symmetric difference: {1, 2, 5, 6} = 4
        let dist = a.hamming_distance(&b);
        assert_eq!(dist, 4);
    }

    #[test]
    fn test_hamming_identical() {
        let a = SparseBitVector::from_indices(vec![1, 2, 3], 100);
        let b = SparseBitVector::from_indices(vec![1, 2, 3], 100);

        let dist = a.hamming_distance(&b);
        assert_eq!(dist, 0);
    }

    #[test]
    #[should_panic(expected = "Index out of bounds")]
    fn test_set_out_of_bounds() {
        let mut sparse = SparseBitVector::new(100);
        sparse.set(100); // Should panic
    }
}