omega_snn/
lib.rs

1//! # Omega SNN - Spiking Neural Network Substrate
2//!
3//! Biologically-inspired spiking neural network implementation for ExoGenesis Omega.
4//! Provides the foundational neural dynamics layer that enables brain-like computation.
5//!
6//! ## Features
7//!
8//! - **Leaky Integrate-and-Fire (LIF) Neurons**: Biologically plausible neuron model
9//! - **Spike-Timing Dependent Plasticity (STDP)**: Hebbian learning based on spike timing
10//! - **Neuromodulation**: Dopamine, norepinephrine, serotonin, acetylcholine
11//! - **Short-Term Plasticity**: Synaptic facilitation and depression
12//! - **Population Coding**: Sparse distributed representations
13//!
14//! ## Architecture
15//!
16//! ```text
17//! ┌─────────────────────────────────────────────────────────────┐
18//! │                    SPIKING NEURAL NETWORK                    │
19//! ├─────────────────────────────────────────────────────────────┤
20//! │                                                              │
21//! │  ┌──────────────────────────────────────────────────────┐  │
22//! │  │              NEUROMODULATOR SYSTEM                    │  │
23//! │  │  Dopamine │ Norepinephrine │ Serotonin │ Acetylcholine│  │
24//! │  └──────────────────────────────────────────────────────┘  │
25//! │                          ↓                                   │
26//! │  ┌──────────────────────────────────────────────────────┐  │
27//! │  │                  NEURAL POPULATIONS                   │  │
28//! │  │  ┌─────────┐  ┌─────────┐  ┌─────────┐  ┌─────────┐ │  │
29//! │  │  │Excitatory│  │Inhibitory│  │ Sensory │  │  Motor  │ │  │
30//! │  │  │ Neurons │  │ Neurons │  │ Neurons │  │ Neurons │ │  │
31//! │  │  └─────────┘  └─────────┘  └─────────┘  └─────────┘ │  │
32//! │  └──────────────────────────────────────────────────────┘  │
33//! │                          ↓                                   │
34//! │  ┌──────────────────────────────────────────────────────┐  │
35//! │  │                 SYNAPTIC CONNECTIONS                  │  │
36//! │  │        STDP │ Short-Term Plasticity │ Weights        │  │
37//! │  └──────────────────────────────────────────────────────┘  │
38//! │                          ↓                                   │
39//! │  ┌──────────────────────────────────────────────────────┐  │
40//! │  │                   SPIKE TRAINS                        │  │
41//! │  │           Temporal coding │ Rate coding               │  │
42//! │  └──────────────────────────────────────────────────────┘  │
43//! │                                                              │
44//! └─────────────────────────────────────────────────────────────┘
45//! ```
46
47pub mod neuron;
48pub mod synapse;
49pub mod neuromodulators;
50pub mod network;
51pub mod spike_train;
52pub mod population;
53
54pub use neuron::{
55    SpikingNeuron, NeuronId, NeuronState, NeuronType,
56    LIFNeuron, LIFParams, AdaptiveLIFNeuron,
57};
58pub use synapse::{
59    Synapse, SynapseId, SynapticPlasticity,
60    STDPRule, STDPParams, ShortTermPlasticity,
61};
62pub use neuromodulators::{
63    NeuromodulatorSystem, Neuromodulator, NeuromodulatorType,
64    DopamineState, NorepinephrineState, SerotoninState, AcetylcholineState,
65};
66pub use network::{SpikingNetwork, NetworkConfig, Layer, LayerId};
67pub use spike_train::{SpikeTrain, Spike, SpikeAnalysis};
68pub use population::{NeuralPopulation, PopulationActivity, SparseCode};
69
70use std::time::Duration;
71use thiserror::Error;
72
73/// Time step for simulation (1ms default, matching biological timescales)
74pub const DEFAULT_DT: Duration = Duration::from_micros(1000);
75
76/// Errors that can occur in the SNN module
77#[derive(Error, Debug)]
78pub enum SNNError {
79    #[error("Neuron not found: {0}")]
80    NeuronNotFound(NeuronId),
81
82    #[error("Synapse not found: {0}")]
83    SynapseNotFound(SynapseId),
84
85    #[error("Invalid connection: {0}")]
86    InvalidConnection(String),
87
88    #[error("Simulation error: {0}")]
89    SimulationError(String),
90
91    #[error("Configuration error: {0}")]
92    ConfigError(String),
93}
94
95pub type Result<T> = std::result::Result<T, SNNError>;
96
97/// Main SNN engine that orchestrates all components
98pub struct SNNEngine {
99    network: SpikingNetwork,
100    neuromodulators: NeuromodulatorSystem,
101    time: Duration,
102    dt: Duration,
103}
104
105impl SNNEngine {
106    /// Create a new SNN engine with default configuration
107    pub fn new(config: NetworkConfig) -> Self {
108        Self {
109            network: SpikingNetwork::new(config),
110            neuromodulators: NeuromodulatorSystem::new(),
111            time: Duration::ZERO,
112            dt: DEFAULT_DT,
113        }
114    }
115
116    /// Step the simulation forward by one time step
117    pub fn step(&mut self) -> Vec<Spike> {
118        // 1. Apply neuromodulator effects to all synapses
119        self.neuromodulators.modulate_network(&mut self.network);
120
121        // 2. Propagate spikes through network
122        let spikes = self.network.step(self.dt);
123
124        // 3. Apply STDP learning based on spike timing
125        self.network.apply_stdp(&spikes, self.time);
126
127        // 4. Update neuromodulator levels based on activity
128        self.neuromodulators.update(self.dt, &spikes);
129
130        // 5. Advance time
131        self.time += self.dt;
132
133        spikes
134    }
135
136    /// Run simulation for specified duration
137    pub fn run(&mut self, duration: Duration) -> Vec<SpikeTrain> {
138        let steps = (duration.as_micros() / self.dt.as_micros()) as usize;
139        let mut all_spikes: Vec<Spike> = Vec::new();
140
141        for _ in 0..steps {
142            let spikes = self.step();
143            all_spikes.extend(spikes);
144        }
145
146        // Group spikes by neuron
147        self.network.collect_spike_trains(&all_spikes)
148    }
149
150    /// Inject current into specific neurons
151    pub fn inject_current(&mut self, neuron_id: NeuronId, current: f64) {
152        self.network.inject_current(neuron_id, current);
153    }
154
155    /// Set neuromodulator level
156    pub fn set_neuromodulator(&mut self, modulator: NeuromodulatorType, level: f64) {
157        self.neuromodulators.set_level(modulator, level);
158    }
159
160    /// Get current network state
161    pub fn state(&self) -> NetworkState {
162        NetworkState {
163            time: self.time,
164            neuron_count: self.network.neuron_count(),
165            synapse_count: self.network.synapse_count(),
166            neuromodulators: self.neuromodulators.levels(),
167        }
168    }
169
170    /// Access the underlying network
171    pub fn network(&self) -> &SpikingNetwork {
172        &self.network
173    }
174
175    /// Access the underlying network mutably
176    pub fn network_mut(&mut self) -> &mut SpikingNetwork {
177        &mut self.network
178    }
179}
180
181/// Current state of the network
182#[derive(Debug, Clone)]
183pub struct NetworkState {
184    pub time: Duration,
185    pub neuron_count: usize,
186    pub synapse_count: usize,
187    pub neuromodulators: NeuromodulatorLevels,
188}
189
190/// Current levels of all neuromodulators
191#[derive(Debug, Clone, Default)]
192pub struct NeuromodulatorLevels {
193    pub dopamine: f64,
194    pub norepinephrine: f64,
195    pub serotonin: f64,
196    pub acetylcholine: f64,
197}
198
199#[cfg(test)]
200mod tests {
201    use super::*;
202
203    #[test]
204    fn test_snn_engine_creation() {
205        let config = NetworkConfig::default();
206        let engine = SNNEngine::new(config);
207
208        let state = engine.state();
209        assert_eq!(state.time, Duration::ZERO);
210    }
211
212    #[test]
213    fn test_snn_engine_step() {
214        let config = NetworkConfig::default();
215        let mut engine = SNNEngine::new(config);
216
217        let spikes = engine.step();
218        assert_eq!(engine.state().time, DEFAULT_DT);
219    }
220}