scirs2-optimize 0.4.2

Optimization module for SciRS2 (scirs2-optimize)
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
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
//! Advanced Spike-Timing Dependent Plasticity (STDP) Learning
//!
//! Implementation of cutting-edge STDP-based optimization algorithms with:
//! - Multi-timescale adaptive plasticity
//! - Homeostatic mechanisms and synaptic scaling
//! - Intrinsic plasticity for neurons
//! - Metaplasticity (plasticity of plasticity)
//! - Triplet STDP rules
//! - Calcium-based synaptic dynamics

use scirs2_core::error::CoreResult as Result;
use scirs2_core::ndarray::{Array1, ArrayView1};
use scirs2_core::random::{Rng, RngExt};
use statrs::statistics::Statistics;
use std::collections::VecDeque;

/// Advanced Multi-Timescale STDP with Metaplasticity
#[derive(Debug, Clone)]
pub struct AdvancedAdvancedSTDP {
    // Basic STDP traces
    pub pre_trace_fast: f64,
    pub post_trace_fast: f64,
    pub pre_trace_slow: f64,
    pub post_trace_slow: f64,

    // Triplet STDP traces
    pub pre_trace_triplet: f64,
    pub post_trace_triplet: f64,

    // Calcium dynamics
    pub calcium_concentration: f64,
    pub calcium_threshold_low: f64,
    pub calcium_threshold_high: f64,

    // Metaplasticity variables
    pub metaplasticity_factor: f64,
    pub recent_activity: VecDeque<f64>,
    pub sliding_threshold: f64,

    // Homeostatic variables
    pub target_firing_rate: f64,
    pub current_firing_rate: f64,
    pub scaling_factor: f64,

    // Time constants
    pub tau_plus_fast: f64,
    pub tau_minus_fast: f64,
    pub tau_plus_slow: f64,
    pub tau_minus_slow: f64,
    pub tau_calcium: f64,
    pub tau_metaplasticity: f64,

    // Learning rates
    pub eta_ltp: f64,
    pub eta_ltd: f64,
    pub eta_triplet: f64,
    pub eta_homeostatic: f64,

    // BCM-like thresholds
    pub theta_d: f64,
    pub theta_p: f64,

    // Spike timing windows
    pub spike_history_pre: VecDeque<f64>,
    pub spike_history_post: VecDeque<f64>,

    // Weight bounds
    pub w_min: f64,
    pub w_max: f64,
}

impl AdvancedAdvancedSTDP {
    /// Create new advanced STDP rule with sophisticated plasticity mechanisms
    pub fn new(eta_ltp: f64, eta_ltd: f64, target_firing_rate: f64) -> Self {
        Self {
            // Initialize traces
            pre_trace_fast: 0.0,
            post_trace_fast: 0.0,
            pre_trace_slow: 0.0,
            post_trace_slow: 0.0,
            pre_trace_triplet: 0.0,
            post_trace_triplet: 0.0,

            // Calcium dynamics
            calcium_concentration: 0.0,
            calcium_threshold_low: 0.2,
            calcium_threshold_high: 0.6,

            // Metaplasticity
            metaplasticity_factor: 1.0,
            recent_activity: VecDeque::with_capacity(1000),
            sliding_threshold: 0.5,

            // Homeostasis
            target_firing_rate,
            current_firing_rate: 0.0,
            scaling_factor: 1.0,

            // Time constants (in seconds)
            tau_plus_fast: 0.017,      // 17ms fast LTP
            tau_minus_fast: 0.034,     // 34ms fast LTD
            tau_plus_slow: 0.688,      // 688ms slow LTP
            tau_minus_slow: 0.688,     // 688ms slow LTD
            tau_calcium: 0.048,        // 48ms calcium decay
            tau_metaplasticity: 100.0, // 100s metaplasticity

            // Learning rates
            eta_ltp,
            eta_ltd,
            eta_triplet: eta_ltp * 0.1,
            eta_homeostatic: eta_ltp * 0.01,

            // BCM thresholds
            theta_d: 0.2,
            theta_p: 0.8,

            // Spike histories
            spike_history_pre: VecDeque::with_capacity(100),
            spike_history_post: VecDeque::with_capacity(100),

            // Weight bounds
            w_min: -2.0,
            w_max: 2.0,
        }
    }

    /// Update all internal states and compute weight change
    pub fn update_weight_advanced(
        &mut self,
        current_weight: f64,
        pre_spike: bool,
        post_spike: bool,
        dt: f64,
        current_time: f64,
        objective_improvement: f64,
    ) -> f64 {
        // Update calcium concentration based on spikes
        self.update_calcium(pre_spike, post_spike, dt);

        // Update metaplasticity based on recent activity
        self.update_metaplasticity(current_time, objective_improvement);

        // Update homeostatic scaling
        self.update_homeostasis(pre_spike, post_spike, dt);

        // Decay all traces
        self.decay_traces(dt);

        // Update spike histories
        if pre_spike {
            self.spike_history_pre.push_back(current_time);
            if self.spike_history_pre.len() > 100 {
                self.spike_history_pre.pop_front();
            }
        }
        if post_spike {
            self.spike_history_post.push_back(current_time);
            if self.spike_history_post.len() > 100 {
                self.spike_history_post.pop_front();
            }
        }

        let mut total_weight_change = 0.0;

        // 1. Pairwise STDP with multiple timescales
        total_weight_change += self.compute_pairwise_stdp(pre_spike, post_spike);

        // 2. Triplet STDP for complex spike patterns
        total_weight_change += self.compute_triplet_stdp(pre_spike, post_spike);

        // 3. Calcium-based plasticity rules
        total_weight_change += self.compute_calcium_plasticity(current_weight);

        // 4. BCM-like metaplasticity
        total_weight_change += self.compute_bcm_plasticity(pre_spike, post_spike, current_weight);

        // 5. Homeostatic synaptic scaling
        total_weight_change += self.compute_homeostatic_scaling(current_weight);

        // Apply metaplasticity modulation
        total_weight_change *= self.metaplasticity_factor;

        // Apply global scaling factor
        total_weight_change *= self.scaling_factor;

        // Apply weight bounds and soft constraints
        let new_weight = current_weight + total_weight_change;
        self.apply_weight_constraints(new_weight)
    }

    fn update_calcium(&mut self, pre_spike: bool, post_spike: bool, dt: f64) {
        // Decay calcium
        self.calcium_concentration *= (-dt / self.tau_calcium).exp();

        // Add calcium from spikes
        if pre_spike {
            self.calcium_concentration += 0.1;
        }
        if post_spike {
            self.calcium_concentration += 0.2;
        }

        // Bound calcium concentration
        self.calcium_concentration = self.calcium_concentration.min(1.0);
    }

    fn update_metaplasticity(&mut self, current_time: f64, objective_improvement: f64) {
        // Store recent activity
        self.recent_activity.push_back(objective_improvement);
        if self.recent_activity.len() > 1000 {
            self.recent_activity.pop_front();
        }

        // Compute activity variance for metaplasticity
        if self.recent_activity.len() > 10 {
            let mean: f64 =
                self.recent_activity.iter().sum::<f64>() / self.recent_activity.len() as f64;
            let variance: f64 = self
                .recent_activity
                .iter()
                .map(|&x| (x - mean).powi(2))
                .sum::<f64>()
                / self.recent_activity.len() as f64;

            // High variance increases plasticity
            self.metaplasticity_factor = 1.0 + variance.sqrt();

            // Update sliding threshold
            self.sliding_threshold = 0.9 * self.sliding_threshold + 0.1 * mean.abs();
        }
    }

    fn update_homeostasis(&mut self, pre_spike: bool, post_spike: bool, dt: f64) {
        // Update current firing rate estimate
        let spike_rate = if post_spike { 1.0 / dt } else { 0.0 };
        self.current_firing_rate = 0.999 * self.current_firing_rate + 0.001 * spike_rate;

        // Compute homeostatic scaling factor
        let rate_ratio = self.current_firing_rate / self.target_firing_rate.max(0.1);
        self.scaling_factor = (2.0 / (1.0 + rate_ratio)).min(2.0).max(0.5);
    }

    fn decay_traces(&mut self, dt: f64) {
        // Decay fast traces
        self.pre_trace_fast *= (-dt / self.tau_plus_fast).exp();
        self.post_trace_fast *= (-dt / self.tau_minus_fast).exp();

        // Decay slow traces
        self.pre_trace_slow *= (-dt / self.tau_plus_slow).exp();
        self.post_trace_slow *= (-dt / self.tau_minus_slow).exp();

        // Decay triplet traces
        self.pre_trace_triplet *= (-dt / (self.tau_plus_fast * 2.0)).exp();
        self.post_trace_triplet *= (-dt / (self.tau_minus_fast * 2.0)).exp();
    }

    fn compute_pairwise_stdp(&mut self, pre_spike: bool, post_spike: bool) -> f64 {
        let mut weight_change = 0.0;

        if pre_spike {
            self.pre_trace_fast += 1.0;
            self.pre_trace_slow += 1.0;

            // LTD: post-before-pre (fast and slow)
            weight_change -= self.eta_ltd * (self.post_trace_fast + 0.1 * self.post_trace_slow);
        }

        if post_spike {
            self.post_trace_fast += 1.0;
            self.post_trace_slow += 1.0;

            // LTP: pre-before-post (fast and slow)
            weight_change += self.eta_ltp * (self.pre_trace_fast + 0.1 * self.pre_trace_slow);
        }

        weight_change
    }

    fn compute_triplet_stdp(&mut self, pre_spike: bool, post_spike: bool) -> f64 {
        let mut weight_change = 0.0;

        if pre_spike {
            self.pre_trace_triplet += 1.0;
            // Triplet LTD
            weight_change -= self.eta_triplet * self.post_trace_fast * self.post_trace_triplet;
        }

        if post_spike {
            self.post_trace_triplet += 1.0;
            // Triplet LTP
            weight_change += self.eta_triplet * self.pre_trace_fast * self.pre_trace_triplet;
        }

        weight_change
    }

    fn compute_calcium_plasticity(&self, current_weight: f64) -> f64 {
        let ca = self.calcium_concentration;

        if ca < self.calcium_threshold_low {
            // Low calcium: LTD
            -self.eta_ltd * 0.1 * current_weight.abs()
        } else if ca > self.calcium_threshold_high {
            // High calcium: LTP
            self.eta_ltp * 0.1 * (self.w_max - current_weight.abs())
        } else {
            // Intermediate calcium: proportional to calcium level
            let normalized_ca = (ca - self.calcium_threshold_low)
                / (self.calcium_threshold_high - self.calcium_threshold_low);
            self.eta_ltp * 0.05 * (2.0 * normalized_ca - 1.0)
        }
    }

    fn compute_bcm_plasticity(
        &self,
        pre_spike: bool,
        post_spike: bool,
        _current_weight: f64,
    ) -> f64 {
        if !pre_spike && !post_spike {
            return 0.0;
        }

        let post_activity = if post_spike { 1.0 } else { 0.0 };
        let pre_activity = if pre_spike { 1.0 } else { 0.0 };

        // BCM rule: Δw ∝ pre * post * (post - θ)
        let theta = self.sliding_threshold;
        pre_activity * post_activity * (post_activity - theta) * self.eta_ltp * 0.1
    }

    fn compute_homeostatic_scaling(&self, current_weight: f64) -> f64 {
        // Homeostatic synaptic scaling to maintain target activity
        let rate_error = self.target_firing_rate - self.current_firing_rate;
        self.eta_homeostatic * rate_error * current_weight * 0.01
    }

    fn apply_weight_constraints(&self, weight: f64) -> f64 {
        // Soft bounds with exponential penalty near limits
        if weight > self.w_max {
            self.w_max - (weight - self.w_max).exp().recip()
        } else if weight < self.w_min {
            self.w_min + (self.w_min - weight).exp().recip()
        } else {
            weight
        }
    }

    /// Get plasticity statistics for monitoring
    pub fn get_plasticity_stats(&self) -> PlasticityStats {
        PlasticityStats {
            calcium_level: self.calcium_concentration,
            metaplasticity_factor: self.metaplasticity_factor,
            scaling_factor: self.scaling_factor,
            firing_rate_error: self.target_firing_rate - self.current_firing_rate,
            sliding_threshold: self.sliding_threshold,
            trace_strength: (self.pre_trace_fast + self.post_trace_fast) / 2.0,
        }
    }
}

/// Statistics for monitoring plasticity mechanisms
#[derive(Debug, Clone)]
pub struct PlasticityStats {
    pub calcium_level: f64,
    pub metaplasticity_factor: f64,
    pub scaling_factor: f64,
    pub firing_rate_error: f64,
    pub sliding_threshold: f64,
    pub trace_strength: f64,
}

/// Legacy STDP learning rule for backward compatibility
#[derive(Debug, Clone)]
pub struct STDPLearningRule {
    /// Pre-synaptic trace
    pub pre_trace: f64,
    /// Post-synaptic trace  
    pub post_trace: f64,
    /// Learning rate
    pub learning_rate: f64,
    /// Time constants
    pub tau_plus: f64,
    pub tau_minus: f64,
}

impl STDPLearningRule {
    /// Create new simple STDP rule
    pub fn new(learning_rate: f64) -> Self {
        Self {
            pre_trace: 0.0,
            post_trace: 0.0,
            learning_rate,
            tau_plus: 0.020,  // 20ms
            tau_minus: 0.020, // 20ms
        }
    }

    /// Update synaptic weight based on spike timing
    pub fn update_weight(
        &mut self,
        current_weight: f64,
        pre_spike: bool,
        post_spike: bool,
        dt: f64,
    ) -> f64 {
        // Decay traces
        self.pre_trace *= (-dt / self.tau_plus).exp();
        self.post_trace *= (-dt / self.tau_minus).exp();

        let mut weight_change = 0.0;

        if pre_spike {
            self.pre_trace += 1.0;
            // LTD: post-before-pre
            if self.post_trace > 0.0 {
                weight_change -= self.learning_rate * self.post_trace;
            }
        }

        if post_spike {
            self.post_trace += 1.0;
            // LTP: pre-before-post
            if self.pre_trace > 0.0 {
                weight_change += self.learning_rate * self.pre_trace;
            }
        }

        (current_weight + weight_change).max(-1.0).min(1.0)
    }
}

/// Advanced-advanced STDP network for complex optimization problems
#[derive(Debug, Clone)]
pub struct AdvancedSTDPNetwork {
    /// Network layers
    pub layers: Vec<STDPLayer>,
    /// Advanced-advanced STDP rules
    pub advanced_stdp_rules: Vec<Vec<AdvancedAdvancedSTDP>>,
    /// Current parameters being optimized
    pub current_params: Array1<f64>,
    /// Best parameters found
    pub best_params: Array1<f64>,
    /// Best objective value
    pub best_objective: f64,
    /// Iteration counter
    pub nit: usize,
    /// Network statistics
    pub network_stats: NetworkStats,
}

/// Layer in STDP network
#[derive(Debug, Clone)]
pub struct STDPLayer {
    /// Layer size
    pub size: usize,
    /// Neuron potentials
    pub potentials: Array1<f64>,
    /// Spike times
    pub last_spike_times: Array1<Option<f64>>,
    /// Firing rates
    pub firing_rates: Array1<f64>,
}

/// Network-wide statistics
#[derive(Debug, Clone)]
pub struct NetworkStats {
    /// Average plasticity across all synapses
    pub avg_plasticity: f64,
    /// Network synchrony measure
    pub synchrony: f64,
    /// Energy consumption estimate
    pub energy_consumption: f64,
    /// Convergence measure
    pub convergence: f64,
}

impl Default for NetworkStats {
    fn default() -> Self {
        Self {
            avg_plasticity: 0.0,
            synchrony: 0.0,
            energy_consumption: 0.0,
            convergence: 0.0,
        }
    }
}

impl AdvancedSTDPNetwork {
    /// Create new advanced STDP network
    pub fn new(layer_sizes: Vec<usize>, target_firing_rate: f64, learning_rate: f64) -> Self {
        let mut layers = Vec::new();
        let mut advanced_stdp_rules = Vec::new();

        for (layer_idx, &size) in layer_sizes.iter().enumerate() {
            let layer = STDPLayer {
                size,
                potentials: Array1::zeros(size),
                last_spike_times: Array1::from_vec(vec![None; size]),
                firing_rates: Array1::zeros(size),
            };
            layers.push(layer);

            // Create STDP rules for connections from previous layer
            if layer_idx > 0 {
                let prev_size = layer_sizes[layer_idx - 1];
                let mut layer_rules = Vec::new();

                for _i in 0..size {
                    for _j in 0..prev_size {
                        layer_rules.push(AdvancedAdvancedSTDP::new(
                            learning_rate,
                            learning_rate * 0.5,
                            target_firing_rate,
                        ));
                    }
                }
                advanced_stdp_rules.push(layer_rules);
            }
        }

        let input_size = layer_sizes[0];

        Self {
            layers,
            advanced_stdp_rules,
            current_params: Array1::zeros(input_size),
            best_params: Array1::zeros(input_size),
            best_objective: f64::INFINITY,
            nit: 0,
            network_stats: NetworkStats::default(),
        }
    }

    /// Run advanced STDP optimization
    pub fn optimize<F>(
        &mut self,
        objective: F,
        initial_params: &ArrayView1<f64>,
        max_nit: usize,
        dt: f64,
    ) -> Result<Array1<f64>>
    where
        F: Fn(&ArrayView1<f64>) -> f64,
    {
        self.current_params = initial_params.to_owned();
        self.best_params = initial_params.to_owned();
        self.best_objective = objective(initial_params);

        let mut prev_objective = self.best_objective;

        for iteration in 0..max_nit {
            let current_time = iteration as f64 * dt;

            // Evaluate current objective
            let current_objective = objective(&self.current_params.view());
            let objective_improvement = prev_objective - current_objective;

            // Update best solution
            if current_objective < self.best_objective {
                self.best_objective = current_objective;
                self.best_params = self.current_params.clone();
            }

            // Encode parameters as spike patterns
            let spike_patterns =
                self.encode_parameters_to_spikes(&self.current_params, current_time);

            // Simulate network dynamics
            let network_spikes =
                self.simulate_network_dynamics(&spike_patterns, current_time, dt)?;

            // Update synaptic weights using advanced STDP
            self.update_advanced_stdp_weights(
                &network_spikes,
                current_time,
                dt,
                objective_improvement,
            )?;

            // Decode new parameters from network state
            let param_updates = self.decode_parameters_from_network(current_time);

            // Apply parameter updates with adaptive step size
            let step_size = self.compute_adaptive_step_size(objective_improvement, iteration);
            for (i, update) in param_updates.iter().enumerate() {
                if i < self.current_params.len() {
                    self.current_params[i] += step_size * update;
                }
            }

            // Update network statistics
            self.update_network_statistics(current_time);

            // Check convergence
            if objective_improvement.abs() < 1e-8 && iteration > 100 {
                break;
            }

            prev_objective = current_objective;
            self.nit = iteration + 1;
        }

        Ok(self.best_params.clone())
    }

    fn encode_parameters_to_spikes(
        &self,
        params: &Array1<f64>,
        _current_time: f64,
    ) -> Vec<Vec<bool>> {
        let mut spike_patterns = Vec::new();

        for layer in &self.layers {
            let mut layer_spikes = vec![false; layer.size];

            // For first layer, use parameter values to determine spike probability
            for i in 0..layer.size.min(params.len()) {
                let spike_prob = ((params[i] + 1.0) / 2.0).max(0.0).min(1.0);
                layer_spikes[i] = scirs2_core::random::rng().random::<f64>() < spike_prob * 0.1;
            }

            spike_patterns.push(layer_spikes);
        }

        spike_patterns
    }

    fn simulate_network_dynamics(
        &mut self,
        input_spikes: &[Vec<bool>],
        current_time: f64,
        dt: f64,
    ) -> Result<Vec<Vec<bool>>> {
        let mut all_spikes = input_spikes.to_vec();

        // Propagate through layers
        for layer_idx in 1..self.layers.len() {
            let mut layer_spikes = vec![false; self.layers[layer_idx].size];

            for neuron_idx in 0..self.layers[layer_idx].size {
                // Compute input from previous layer
                let mut input_current = 0.0;

                for prev_neuron_idx in 0..self.layers[layer_idx - 1].size {
                    if all_spikes[layer_idx - 1][prev_neuron_idx] {
                        // Use synaptic weight (simplified - would normally track weights)
                        input_current += 0.1;
                    }
                }

                // Update membrane potential
                self.layers[layer_idx].potentials[neuron_idx] +=
                    dt * (-self.layers[layer_idx].potentials[neuron_idx] + input_current) / 0.02;

                // Check for spike
                if self.layers[layer_idx].potentials[neuron_idx] > 1.0 {
                    self.layers[layer_idx].potentials[neuron_idx] = 0.0;
                    self.layers[layer_idx].last_spike_times[neuron_idx] = Some(current_time);
                    layer_spikes[neuron_idx] = true;
                }

                // Update firing rate
                let spike_rate = if layer_spikes[neuron_idx] {
                    1.0 / dt
                } else {
                    0.0
                };
                self.layers[layer_idx].firing_rates[neuron_idx] =
                    0.99 * self.layers[layer_idx].firing_rates[neuron_idx] + 0.01 * spike_rate;
            }

            all_spikes.push(layer_spikes);
        }

        Ok(all_spikes)
    }

    fn update_advanced_stdp_weights(
        &mut self,
        all_spikes: &[Vec<bool>],
        current_time: f64,
        dt: f64,
        objective_improvement: f64,
    ) -> Result<()> {
        // Update STDP rules for each layer connection
        for layer_idx in 0..self.advanced_stdp_rules.len() {
            let input_spikes = &all_spikes[layer_idx];
            let output_spikes = &all_spikes[layer_idx + 1];

            for (connection_idx, rule) in self.advanced_stdp_rules[layer_idx].iter_mut().enumerate()
            {
                // Calculate neuron and input indices from connection index
                let _layer_size = self.layers[layer_idx + 1].size;
                let prev_layer_size = self.layers[layer_idx].size;
                let neuron_idx = connection_idx / prev_layer_size;
                let input_idx = connection_idx % prev_layer_size;

                let pre_spike = input_spikes.get(input_idx).copied().unwrap_or(false);
                let post_spike = output_spikes.get(neuron_idx).copied().unwrap_or(false);

                // Update using advanced STDP
                let _new_weight = rule.update_weight_advanced(
                    0.5, // Current weight (simplified)
                    pre_spike,
                    post_spike,
                    dt,
                    current_time,
                    objective_improvement,
                );
            }
        }

        Ok(())
    }

    fn decode_parameters_from_network(&self, current_time: f64) -> Array1<f64> {
        let mut updates = Array1::zeros(self.current_params.len());

        // Use firing rates from first layer as parameter updates
        if !self.layers.is_empty() {
            for (i, &rate) in self.layers[0].firing_rates.iter().enumerate() {
                if i < updates.len() {
                    updates[i] = (rate - 5.0) * 0.01; // Center around target rate
                }
            }
        }

        updates
    }

    fn compute_adaptive_step_size(&self, objective_improvement: f64, iteration: usize) -> f64 {
        let base_step = 0.01;
        let improvement_factor = if objective_improvement > 0.0 {
            1.2
        } else {
            0.8
        };
        let decay_factor = 1.0 / (1.0 + iteration as f64 * 0.001);

        base_step * improvement_factor * decay_factor
    }

    fn update_network_statistics(&mut self, current_time: f64) {
        // Compute average plasticity
        let mut total_plasticity = 0.0;
        let mut count = 0;

        for layer_rules in &self.advanced_stdp_rules {
            for rule in layer_rules {
                let stats = rule.get_plasticity_stats();
                total_plasticity += stats.metaplasticity_factor;
                count += 1;
            }
        }

        if count > 0 {
            self.network_stats.avg_plasticity = total_plasticity / count as f64;
        }

        // Compute network synchrony (simplified)
        let mut synchrony = 0.0;
        for layer in &self.layers {
            let rate_variance = layer.firing_rates.clone().variance();
            synchrony += 1.0 / (1.0 + rate_variance);
        }
        self.network_stats.synchrony = synchrony / self.layers.len() as f64;

        // Energy consumption estimate
        let total_spikes: f64 = self
            .layers
            .iter()
            .map(|layer| layer.firing_rates.sum())
            .sum();
        self.network_stats.energy_consumption = total_spikes * 1e-12; // Simplified energy model
    }

    /// Get network performance statistics
    pub fn get_network_stats(&self) -> &NetworkStats {
        &self.network_stats
    }
}

/// STDP-based parameter optimization
#[allow(dead_code)]
pub fn stdp_optimize<F>(
    objective: F,
    initial_params: &ArrayView1<f64>,
    num_nit: usize,
) -> Result<Array1<f64>>
where
    F: Fn(&ArrayView1<f64>) -> f64,
{
    let mut params = initial_params.to_owned();
    let mut stdp_rules: Vec<STDPLearningRule> = (0..params.len())
        .map(|_| STDPLearningRule::new(0.01))
        .collect();

    let mut prev_obj = objective(&params.view());

    for _iter in 0..num_nit {
        let current_obj = objective(&params.view());
        let improvement = prev_obj - current_obj;

        // More sophisticated spike-based encoding
        for (i, rule) in stdp_rules.iter_mut().enumerate() {
            let pre_spike =
                scirs2_core::random::rng().random::<f64>() < (params[i].abs() * 0.1).min(0.5);
            let post_spike = improvement > 0.0 && scirs2_core::random::rng().random::<f64>() < 0.2;

            params[i] = rule.update_weight(params[i], pre_spike, post_spike, 0.001);
        }

        prev_obj = current_obj;
    }

    Ok(params)
}

/// Advanced-advanced STDP optimization with full network simulation
#[allow(dead_code)]
pub fn advanced_stdp_optimize<F>(
    objective: F,
    initial_params: &ArrayView1<f64>,
    max_nit: usize,
    network_config: Option<(Vec<usize>, f64, f64)>, // (layer_sizes, target_rate, learning_rate)
) -> Result<Array1<f64>>
where
    F: Fn(&ArrayView1<f64>) -> f64,
{
    let (layer_sizes, target_rate, learning_rate) = network_config.unwrap_or_else(|| {
        let input_size = initial_params.len();
        (vec![input_size, input_size * 2, input_size], 5.0, 0.01)
    });

    let mut network = AdvancedSTDPNetwork::new(layer_sizes, target_rate, learning_rate);
    network.optimize(objective, initial_params, max_nit, 0.001)
}

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

    #[test]
    fn test_advanced_stdp_creation() {
        let stdp = AdvancedAdvancedSTDP::new(0.01, 0.005, 5.0);
        assert_eq!(stdp.eta_ltp, 0.01);
        assert_eq!(stdp.target_firing_rate, 5.0);
    }

    #[test]
    fn test_advanced_stdp_weight_update() {
        let mut stdp = AdvancedAdvancedSTDP::new(0.1, 0.05, 5.0);

        let new_weight = stdp.update_weight_advanced(0.5, true, true, 0.001, 0.0, 0.1);

        assert!(new_weight.is_finite());
        assert!(new_weight >= stdp.w_min && new_weight <= stdp.w_max);
    }

    #[test]
    fn test_advanced_stdp_network() {
        let layer_sizes = vec![3, 5, 3];
        let network = AdvancedSTDPNetwork::new(layer_sizes, 5.0, 0.01);

        assert_eq!(network.layers.len(), 3);
        assert_eq!(network.layers[0].size, 3);
        assert_eq!(network.layers[1].size, 5);
        assert_eq!(network.layers[2].size, 3);
    }

    #[test]
    fn test_plasticity_stats() {
        let stdp = AdvancedAdvancedSTDP::new(0.01, 0.005, 5.0);
        let stats = stdp.get_plasticity_stats();

        assert!(stats.calcium_level >= 0.0);
        assert!(stats.metaplasticity_factor > 0.0);
        assert!(stats.scaling_factor > 0.0);
    }

    #[test]
    fn test_basic_stdp_optimization() {
        let objective = |x: &ArrayView1<f64>| x[0].powi(2) + x[1].powi(2);
        let initial = Array1::from(vec![1.0, 1.0]);

        let result = stdp_optimize(objective, &initial.view(), 100).expect("Operation failed");

        let final_obj = objective(&result.view());
        let initial_obj = objective(&initial.view());
        assert!(final_obj <= initial_obj);
    }

    #[test]
    fn test_advanced_stdp_optimization() {
        let objective = |x: &ArrayView1<f64>| (x[0] - 1.0).powi(2) + (x[1] + 0.5).powi(2);
        let initial = Array1::from(vec![0.0, 0.0]);

        let result = advanced_stdp_optimize(
            objective,
            &initial.view(),
            50,
            Some((vec![2, 4, 2], 3.0, 0.05)),
        )
        .expect("Operation failed");

        assert_eq!(result.len(), 2);
        let final_obj = objective(&result.view());
        let initial_obj = objective(&initial.view());
        assert!(final_obj <= initial_obj * 2.0); // Allow some tolerance for stochastic method
    }
}

#[allow(dead_code)]
pub fn placeholder() {
    // Placeholder function to prevent unused module warnings
}