trustformers-core 0.1.1

Core traits and utilities for TrustformeRS
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
//! Spiking Neural Network implementation

#![allow(unused_variables)] // Neuromorphic implementation with reserved parameters

use crate::neuromorphic::SpikeEvent;
use anyhow::Result;
use scirs2_core::random::*; // SciRS2 Policy compliant

/// Spiking neural network
#[derive(Debug, Clone)]
pub struct SpikingNeuralNetwork {
    pub neurons: Vec<SpikingNeuron>,
    pub synapses: Vec<Synapse>,
    pub topology: NetworkTopology,
    pub learning_rules: Vec<PlasticityRule>,
    pub power_gated: bool,
}

/// Individual spiking neuron
#[derive(Debug, Clone)]
pub struct SpikingNeuron {
    pub id: usize,
    pub neuron_type: NeuronType,
    pub membrane_potential: f32,
    pub threshold: f32,
    pub leak_rate: f32,
    pub refractory_period: f32,
    pub last_spike_time: f64,
    pub input_current: f32,
}

/// Types of neurons
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NeuronType {
    LeakyIntegrateAndFire,
    AdaptiveExponential,
    Izhikevich,
    HodgkinHuxley,
}

/// Synaptic connection between neurons
#[derive(Debug, Clone)]
pub struct Synapse {
    pub pre_neuron: usize,
    pub post_neuron: usize,
    pub weight: f32,
    pub delay: f32,
    pub synapse_type: SynapseType,
    pub plasticity_enabled: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SynapseType {
    Excitatory,
    Inhibitory,
    Modulatory,
}

/// Network topology patterns
#[derive(Debug, Clone)]
pub enum NetworkTopology {
    FullyConnected,
    Layered { layers: Vec<usize> },
    SmallWorld { rewiring_prob: f32 },
    ScaleFree { gamma: f32 },
    Custom { adjacency_matrix: Vec<Vec<bool>> },
}

/// Plasticity learning rules
#[derive(Debug, Clone)]
pub enum PlasticityRule {
    STDP {
        tau_plus: f32,
        tau_minus: f32,
        a_plus: f32,
        a_minus: f32,
    },
    BCM {
        theta: f32,
        tau: f32,
    },
    Homeostatic {
        target_rate: f32,
        alpha: f32,
    },
}

impl SpikingNeuralNetwork {
    /// Create a new spiking neural network
    pub fn new(num_neurons: usize) -> Self {
        let neurons = (0..num_neurons)
            .map(|id| SpikingNeuron::new(id, NeuronType::LeakyIntegrateAndFire))
            .collect();

        Self {
            neurons,
            synapses: Vec::new(),
            topology: NetworkTopology::FullyConnected,
            learning_rules: Vec::new(),
            power_gated: false,
        }
    }

    /// Add a synapse between neurons
    pub fn add_synapse(&mut self, pre: usize, post: usize, weight: f32, delay: f32) -> Result<()> {
        if pre >= self.neurons.len() || post >= self.neurons.len() {
            return Err(anyhow::anyhow!("Invalid neuron indices"));
        }

        let synapse = Synapse {
            pre_neuron: pre,
            post_neuron: post,
            weight,
            delay,
            synapse_type: if weight >= 0.0 {
                SynapseType::Excitatory
            } else {
                SynapseType::Inhibitory
            },
            plasticity_enabled: true,
        };

        self.synapses.push(synapse);
        Ok(())
    }

    /// Process one time step
    pub fn process_time_step(
        &mut self,
        input_spikes: &[SpikeEvent],
        dt: f64,
    ) -> Result<Vec<SpikeEvent>> {
        let mut output_spikes = Vec::new();

        // Apply input currents from spikes
        for spike in input_spikes {
            if spike.neuron_id < self.neurons.len() {
                self.neurons[spike.neuron_id].input_current += spike.weight;
            }
        }

        // Update each neuron and collect spikes
        let mut spiked_neurons = Vec::new();
        for neuron in &mut self.neurons {
            if neuron.update(dt) {
                // Neuron spiked
                output_spikes.push(SpikeEvent::new(neuron.id, 0.0, 1.0));
                spiked_neurons.push(neuron.id);
            }
        }

        // Propagate spikes through synapses
        for neuron_id in spiked_neurons {
            for synapse in &self.synapses {
                if synapse.pre_neuron == neuron_id {
                    if let Some(post_neuron) = self.neurons.get_mut(synapse.post_neuron) {
                        post_neuron.receive_spike(synapse.weight, synapse.delay);
                    }
                }
            }
        }

        // Apply plasticity rules
        self.apply_plasticity(&output_spikes, dt);

        // Reset input currents
        for neuron in &mut self.neurons {
            neuron.input_current = 0.0;
        }

        Ok(output_spikes)
    }

    /// Apply plasticity learning rules
    fn apply_plasticity(&mut self, spikes: &[SpikeEvent], dt: f64) {
        if self.learning_rules.is_empty() {
            return;
        }

        // Collect rules to avoid borrowing conflicts
        let rules = self.learning_rules.clone();
        for rule in &rules {
            match rule {
                PlasticityRule::STDP {
                    tau_plus,
                    tau_minus,
                    a_plus,
                    a_minus,
                } => {
                    self.apply_stdp(*tau_plus, *tau_minus, *a_plus, *a_minus, spikes, dt);
                },
                PlasticityRule::BCM { theta, tau } => {
                    self.apply_bcm(*theta, *tau, spikes, dt);
                },
                PlasticityRule::Homeostatic { target_rate, alpha } => {
                    self.apply_homeostatic(*target_rate, *alpha, spikes, dt);
                },
            }
        }
    }

    fn apply_stdp(
        &mut self,
        tau_plus: f32,
        tau_minus: f32,
        a_plus: f32,
        a_minus: f32,
        spikes: &[SpikeEvent],
        dt: f64,
    ) {
        // Simplified STDP implementation
        for spike in spikes {
            let pre_neuron_id = spike.neuron_id;

            for synapse in &mut self.synapses {
                if synapse.plasticity_enabled && synapse.pre_neuron == pre_neuron_id {
                    let post_neuron = &self.neurons[synapse.post_neuron];
                    let delta_t = spike.timestamp - post_neuron.last_spike_time;

                    if delta_t > 0.0 {
                        // Pre before post - potentiation
                        synapse.weight += a_plus * (-delta_t as f32 / tau_plus).exp();
                    } else {
                        // Post before pre - depression
                        synapse.weight -= a_minus * (delta_t as f32 / tau_minus).exp();
                    }

                    // Clip weights
                    synapse.weight = synapse.weight.clamp(-1.0, 1.0);
                }
            }
        }
    }

    fn apply_bcm(&mut self, theta: f32, tau: f32, spikes: &[SpikeEvent], dt: f64) {
        // BCM rule implementation (placeholder)
        for spike in spikes {
            // BCM plasticity based on postsynaptic activity
            let neuron = &self.neurons[spike.neuron_id];
            let activity = neuron.membrane_potential;

            for synapse in &mut self.synapses {
                if synapse.plasticity_enabled && synapse.post_neuron == spike.neuron_id {
                    let delta_w = activity * (activity - theta) * synapse.weight * dt as f32 / tau;
                    synapse.weight += delta_w;
                    synapse.weight = synapse.weight.clamp(-1.0, 1.0);
                }
            }
        }
    }

    fn apply_homeostatic(&mut self, target_rate: f32, alpha: f32, spikes: &[SpikeEvent], dt: f64) {
        // Homeostatic plasticity to maintain target firing rate
        let current_rate = spikes.len() as f32 / (self.neurons.len() as f32 * dt as f32);
        let rate_error = target_rate - current_rate;

        for synapse in &mut self.synapses {
            if synapse.plasticity_enabled {
                synapse.weight += alpha * rate_error * dt as f32;
                synapse.weight = synapse.weight.clamp(-1.0, 1.0);
            }
        }
    }

    /// Set network topology
    pub fn set_topology(&mut self, topology: NetworkTopology) {
        // Clone the topology data we need before assigning
        match &topology {
            NetworkTopology::Layered { layers } => {
                let layers_clone = layers.clone();
                self.topology = topology;
                self.create_layered_connections(&layers_clone);
            },
            NetworkTopology::SmallWorld { rewiring_prob } => {
                let rewiring_prob_val = *rewiring_prob;
                self.topology = topology;
                self.create_small_world_connections(rewiring_prob_val);
            },
            _ => {
                self.topology = topology;
            },
        }
    }

    fn create_layered_connections(&mut self, layers: &[usize]) {
        self.synapses.clear();
        let mut neuron_idx = 0;
        let mut rng = thread_rng();

        for i in 0..layers.len() - 1 {
            let current_layer_size = layers[i];
            let next_layer_size = layers[i + 1];

            for current in 0..current_layer_size {
                for next in 0..next_layer_size {
                    let pre = neuron_idx + current;
                    let post = neuron_idx + current_layer_size + next;
                    let weight = (rng.random::<f32>() - 0.5) * 2.0; // Random weight [-1, 1]
                    let _ = self.add_synapse(pre, post, weight, 1.0);
                }
            }
            neuron_idx += current_layer_size;
        }
    }

    fn create_small_world_connections(&mut self, rewiring_prob: f32) {
        // Simplified small-world network creation
        self.synapses.clear();
        let n = self.neurons.len();
        let mut rng = thread_rng();

        // Create ring lattice
        for i in 0..n {
            let next = (i + 1) % n;
            let weight = (rng.random::<f32>() - 0.5) * 2.0;
            let _ = self.add_synapse(i, next, weight, 1.0);
        }

        // Rewire some connections
        let mut synapses_to_rewire = Vec::new();
        for (idx, synapse) in self.synapses.iter().enumerate() {
            if rng.random::<f32>() < rewiring_prob {
                synapses_to_rewire.push(idx);
            }
        }

        for idx in synapses_to_rewire {
            let new_target = rng.random_range(0..n);
            self.synapses[idx].post_neuron = new_target;
        }
    }

    /// Add plasticity rule
    pub fn add_plasticity_rule(&mut self, rule: PlasticityRule) {
        self.learning_rules.push(rule);
    }

    /// Enable power gating
    pub fn enable_power_gating(&mut self) {
        self.power_gated = true;
    }

    /// Adjust firing thresholds
    pub fn adjust_firing_thresholds(&mut self, factor: f32) {
        for neuron in &mut self.neurons {
            neuron.threshold *= factor;
        }
    }

    /// Get network statistics
    pub fn get_statistics(&self) -> NetworkStatistics {
        let total_synapses = self.synapses.len();
        let excitatory_synapses = self
            .synapses
            .iter()
            .filter(|s| matches!(s.synapse_type, SynapseType::Excitatory))
            .count();
        let inhibitory_synapses = total_synapses - excitatory_synapses;

        let average_weight = if total_synapses > 0 {
            self.synapses.iter().map(|s| s.weight).sum::<f32>() / total_synapses as f32
        } else {
            0.0
        };

        NetworkStatistics {
            num_neurons: self.neurons.len(),
            num_synapses: total_synapses,
            excitatory_synapses,
            inhibitory_synapses,
            average_weight,
            plasticity_enabled: !self.learning_rules.is_empty(),
        }
    }
}

impl SpikingNeuron {
    /// Create a new spiking neuron
    pub fn new(id: usize, neuron_type: NeuronType) -> Self {
        Self {
            id,
            neuron_type,
            membrane_potential: 0.0,
            threshold: 1.0,
            leak_rate: 0.1,
            refractory_period: 2.0,
            last_spike_time: -100.0,
            input_current: 0.0,
        }
    }

    /// Update neuron state and return true if spiked
    pub fn update(&mut self, dt: f64) -> bool {
        match self.neuron_type {
            NeuronType::LeakyIntegrateAndFire => self.update_lif(dt),
            NeuronType::AdaptiveExponential => self.update_aeif(dt),
            NeuronType::Izhikevich => self.update_izhikevich(dt),
            NeuronType::HodgkinHuxley => self.update_hh(dt),
        }
    }

    fn update_lif(&mut self, dt: f64) -> bool {
        // Leaky Integrate-and-Fire model
        let dt_f32 = dt as f32;

        // Update membrane potential
        self.membrane_potential +=
            dt_f32 * (-self.leak_rate * self.membrane_potential + self.input_current);

        // Check for spike
        if self.membrane_potential >= self.threshold {
            self.membrane_potential = 0.0; // Reset
            self.last_spike_time = 0.0; // Current time (simplified)
            return true;
        }

        false
    }

    fn update_aeif(&mut self, dt: f64) -> bool {
        // Adaptive Exponential Integrate-and-Fire (simplified)
        self.update_lif(dt) // Placeholder - use LIF for now
    }

    fn update_izhikevich(&mut self, dt: f64) -> bool {
        // Izhikevich model (simplified)
        self.update_lif(dt) // Placeholder - use LIF for now
    }

    fn update_hh(&mut self, dt: f64) -> bool {
        // Hodgkin-Huxley model (simplified)
        self.update_lif(dt) // Placeholder - use LIF for now
    }

    /// Receive spike from presynaptic neuron
    pub fn receive_spike(&mut self, weight: f32, delay: f32) {
        // Simplified - add to input current immediately (ignore delay for now)
        self.input_current += weight;
    }
}

/// Network statistics
#[derive(Debug, Clone)]
pub struct NetworkStatistics {
    pub num_neurons: usize,
    pub num_synapses: usize,
    pub excitatory_synapses: usize,
    pub inhibitory_synapses: usize,
    pub average_weight: f32,
    pub plasticity_enabled: bool,
}

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

    #[test]
    fn test_spiking_neuron_creation() {
        let neuron = SpikingNeuron::new(0, NeuronType::LeakyIntegrateAndFire);
        assert_eq!(neuron.id, 0);
        assert_eq!(neuron.membrane_potential, 0.0);
        assert_eq!(neuron.threshold, 1.0);
    }

    #[test]
    fn test_neuron_update() {
        let mut neuron = SpikingNeuron::new(0, NeuronType::LeakyIntegrateAndFire);
        neuron.input_current = 2.0; // Strong input

        let spiked = neuron.update(1.0);
        assert!(spiked); // Should spike with strong input
        assert_eq!(neuron.membrane_potential, 0.0); // Should reset
    }

    #[test]
    fn test_spiking_network_creation() {
        let network = SpikingNeuralNetwork::new(5);
        assert_eq!(network.neurons.len(), 5);
        assert_eq!(network.synapses.len(), 0);
    }

    #[test]
    fn test_add_synapse() {
        let mut network = SpikingNeuralNetwork::new(3);
        let result = network.add_synapse(0, 1, 0.5, 1.0);
        assert!(result.is_ok());
        assert_eq!(network.synapses.len(), 1);

        let synapse = &network.synapses[0];
        assert_eq!(synapse.pre_neuron, 0);
        assert_eq!(synapse.post_neuron, 1);
        assert_eq!(synapse.weight, 0.5);
    }

    #[test]
    fn test_invalid_synapse() {
        let mut network = SpikingNeuralNetwork::new(2);
        let result = network.add_synapse(0, 5, 0.5, 1.0); // Invalid post neuron
        assert!(result.is_err());
    }

    #[test]
    fn test_plasticity_rules() {
        let mut network = SpikingNeuralNetwork::new(3);
        let stdp_rule = PlasticityRule::STDP {
            tau_plus: 20.0,
            tau_minus: 20.0,
            a_plus: 0.01,
            a_minus: 0.012,
        };

        network.add_plasticity_rule(stdp_rule);
        assert_eq!(network.learning_rules.len(), 1);
    }

    #[test]
    fn test_network_statistics() {
        let mut network = SpikingNeuralNetwork::new(4);
        let _ = network.add_synapse(0, 1, 0.5, 1.0);
        let _ = network.add_synapse(1, 2, -0.3, 1.0);
        let _ = network.add_synapse(2, 3, 0.8, 1.0);

        let stats = network.get_statistics();
        assert_eq!(stats.num_neurons, 4);
        assert_eq!(stats.num_synapses, 3);
        assert_eq!(stats.excitatory_synapses, 2);
        assert_eq!(stats.inhibitory_synapses, 1);
    }

    #[test]
    fn test_layered_topology() {
        let mut network = SpikingNeuralNetwork::new(6);
        let topology = NetworkTopology::Layered {
            layers: vec![2, 2, 2],
        };
        network.set_topology(topology);

        // Should create connections between layers
        assert!(!network.synapses.is_empty());
    }

    #[test]
    fn test_synapse_types() {
        let excitatory = Synapse {
            pre_neuron: 0,
            post_neuron: 1,
            weight: 0.5,
            delay: 1.0,
            synapse_type: SynapseType::Excitatory,
            plasticity_enabled: true,
        };

        let inhibitory = Synapse {
            pre_neuron: 1,
            post_neuron: 2,
            weight: -0.3,
            delay: 1.0,
            synapse_type: SynapseType::Inhibitory,
            plasticity_enabled: true,
        };

        assert_eq!(excitatory.synapse_type, SynapseType::Excitatory);
        assert_eq!(inhibitory.synapse_type, SynapseType::Inhibitory);
    }

    #[test]
    fn test_power_gating() {
        let mut network = SpikingNeuralNetwork::new(3);
        assert!(!network.power_gated);

        network.enable_power_gating();
        assert!(network.power_gated);
    }

    #[test]
    fn test_threshold_adjustment() {
        let mut network = SpikingNeuralNetwork::new(3);
        let original_threshold = network.neurons[0].threshold;

        network.adjust_firing_thresholds(1.5);
        assert_eq!(network.neurons[0].threshold, original_threshold * 1.5);
    }
}