ruvector_nervous_system/
lib.rs

1//! # RuVector Nervous System
2//!
3//! Biologically-inspired nervous system components for RuVector including:
4//! - Dendritic coincidence detection with NMDA-like nonlinearity
5//! - Hyperdimensional computing (HDC) for neural-symbolic AI
6//! - Cognitive routing for multi-agent systems
7//!
8//! ## Dendrite Module
9//!
10//! Implements reduced compartment dendritic models that detect temporal coincidence
11//! of synaptic inputs within 10-50ms windows. Based on Dendrify framework and
12//! DenRAM RRAM circuits.
13//!
14//! ### Example
15//!
16//! ```rust
17//! use ruvector_nervous_system::dendrite::{Dendrite, DendriticTree};
18//!
19//! // Create a dendrite with NMDA threshold of 5 synapses
20//! let mut dendrite = Dendrite::new(5, 20.0);
21//!
22//! // Simulate coincident synaptic inputs
23//! for i in 0..6 {
24//!     dendrite.receive_spike(i, 100);
25//! }
26//!
27//! // Update dendrite - should trigger plateau potential
28//! let plateau_triggered = dendrite.update(100, 1.0);
29//! assert!(plateau_triggered);
30//! ```
31//!
32//! ## HDC Module
33//!
34//! High-performance hyperdimensional computing implementation with SIMD-optimized
35//! operations for neural-symbolic AI.
36//!
37//! ### Example
38//!
39//! ```rust
40//! use ruvector_nervous_system::hdc::{Hypervector, HdcMemory};
41//!
42//! // Create random hypervectors
43//! let v1 = Hypervector::random();
44//! let v2 = Hypervector::random();
45//!
46//! // Bind vectors with XOR
47//! let bound = v1.bind(&v2);
48//!
49//! // Compute similarity (0.0 to 1.0)
50//! let sim = v1.similarity(&v2);
51//! ```
52//!
53//! ## EventBus Module
54//!
55//! Lock-free event queue system for DVS (Dynamic Vision Sensor) event streams
56//! with 10,000+ events/millisecond throughput.
57//!
58//! ### Example
59//!
60//! ```rust
61//! use ruvector_nervous_system::eventbus::{DVSEvent, EventRingBuffer, ShardedEventBus};
62//!
63//! // Create event
64//! let event = DVSEvent::new(1000, 42, 123, true);
65//!
66//! // Lock-free ring buffer
67//! let buffer = EventRingBuffer::new(1024);
68//! buffer.push(event).unwrap();
69//!
70//! // Sharded bus for parallel processing
71//! let bus = ShardedEventBus::new_spatial(4, 256);
72//! bus.push(event).unwrap();
73//! ```
74
75pub mod compete;
76pub mod dendrite;
77pub mod eventbus;
78pub mod hdc;
79pub mod hopfield;
80pub mod integration;
81pub mod plasticity;
82pub mod routing;
83pub mod separate;
84
85pub use compete::{KWTALayer, LateralInhibition, WTALayer};
86pub use dendrite::{Compartment, Dendrite, DendriticTree, PlateauPotential};
87pub use eventbus::{
88    BackpressureController, BackpressureState, DVSEvent, Event, EventRingBuffer, EventSurface,
89    ShardedEventBus,
90};
91pub use hdc::{HdcError, HdcMemory, Hypervector};
92pub use hopfield::ModernHopfield;
93pub use plasticity::eprop::{EpropLIF, EpropNetwork, EpropSynapse, LearningSignal};
94pub use routing::{
95    BudgetGuardrail, CircadianController, CircadianPhase, CircadianScheduler, CoherenceGatedSystem,
96    GlobalWorkspace, HysteresisTracker, NervousSystemMetrics, NervousSystemScorecard,
97    OscillatoryRouter, PhaseModulation, PredictiveLayer, Representation, ScorecardTargets,
98};
99pub use separate::{DentateGyrus, SparseBitVector, SparseProjection};
100
101#[derive(Debug, thiserror::Error)]
102pub enum NervousSystemError {
103    #[error("Invalid parameter: {0}")]
104    InvalidParameter(String),
105
106    #[error("Compartment index out of bounds: {0}")]
107    CompartmentOutOfBounds(usize),
108
109    #[error("Synapse index out of bounds: {0}")]
110    SynapseOutOfBounds(usize),
111
112    #[error("Invalid weight: {0}")]
113    InvalidWeight(f32),
114
115    #[error("Invalid time constant: {0}")]
116    InvalidTimeConstant(f32),
117
118    #[error("Invalid gradients: {0}")]
119    InvalidGradients(String),
120
121    #[error("Dimension mismatch: expected {expected}, got {actual}")]
122    DimensionMismatch { expected: usize, actual: usize },
123
124    #[error("HDC error: {0}")]
125    HdcError(#[from] HdcError),
126
127    #[error("Invalid dimension: {0}")]
128    InvalidDimension(String),
129
130    #[error("Invalid sparsity: {0}")]
131    InvalidSparsity(String),
132}
133
134pub type Result<T> = std::result::Result<T, NervousSystemError>;
135
136#[cfg(test)]
137mod tests {
138    use super::*;
139
140    #[test]
141    fn test_basic_hdc_workflow() {
142        let v1 = Hypervector::random();
143        let v2 = Hypervector::random();
144
145        // Similarity of random vectors should be ~0.0 (50% bit overlap)
146        // Formula: 1 - 2*hamming/dim = 1 - 2*0.5 = 0
147        let sim = v1.similarity(&v2);
148        assert!(sim > -0.2 && sim < 0.2, "random similarity: {}", sim);
149
150        // Binding produces ~0 similarity with original
151        let bound = v1.bind(&v2);
152        assert!(
153            bound.similarity(&v1) > -0.2,
154            "bound similarity: {}",
155            bound.similarity(&v1)
156        );
157
158        // Memory
159        let mut memory = HdcMemory::new();
160        memory.store("test", v1.clone());
161        let results = memory.retrieve(&v1, 0.9);
162        assert_eq!(results.len(), 1);
163        assert_eq!(results[0].0, "test");
164    }
165
166    #[test]
167    fn test_dendrite_workflow() {
168        let mut dendrite = Dendrite::new(5, 20.0);
169
170        // Insufficient spikes - no plateau
171        for i in 0..3 {
172            dendrite.receive_spike(i, 100);
173        }
174        let triggered = dendrite.update(100, 1.0);
175        assert!(!triggered);
176
177        // Sufficient spikes - trigger plateau
178        for i in 3..8 {
179            dendrite.receive_spike(i, 100);
180        }
181        let triggered = dendrite.update(100, 1.0);
182        assert!(triggered);
183        assert!(dendrite.has_plateau());
184    }
185}