optirs-core 0.3.1

OptiRS core optimization algorithms and utilities
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
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
// Event-Driven Optimization Algorithms
//
// This module implements event-driven optimization algorithms that process
// updates asynchronously based on neuromorphic events, designed for
// neuromorphic computing platforms with event-based architectures.

use super::{
    EventPriority, MembraneDynamicsConfig, NeuromorphicEvent, NeuromorphicMetrics, PlasticityModel,
    STDPConfig, Spike, SpikeTrain,
};
use crate::error::{OptimError, Result};
use crate::optimizers::Optimizer;
use scirs2_core::ndarray::{Array1, Array2, ArrayBase, Data, DataMut, Dimension};
use scirs2_core::numeric::Float;
use std::cmp::Reverse;
use std::collections::{BinaryHeap, HashMap, HashSet, VecDeque};
use std::fmt::Debug;
use std::sync::{Arc, Mutex, RwLock};
use std::time::{Duration, Instant};

/// Event types for neuromorphic computing
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum EventType {
    /// Spike event from a neuron
    Spike,

    /// Synaptic weight update event
    WeightUpdate,

    /// Membrane potential threshold crossing
    ThresholdCrossing,

    /// Plasticity-triggered event
    PlasticityEvent,

    /// External stimulus event
    ExternalStimulus,

    /// Timer-based event
    TimerEvent,

    /// Error backpropagation event
    ErrorEvent,

    /// Homeostatic adaptation event
    HomeostaticEvent,

    /// Population synchronization event
    SynchronizationEvent,

    /// Energy budget event
    EnergyEvent,
}

/// Event-driven optimization configuration
#[derive(Debug, Clone)]
pub struct EventDrivenConfig<T: Float + Debug + Send + Sync + 'static> {
    /// Maximum event queue size
    pub max_queue_size: usize,

    /// Event processing timeout (ms)
    pub processing_timeout: T,

    /// Enable event priority scheduling
    pub priority_scheduling: bool,

    /// Event filtering threshold
    pub event_threshold: T,

    /// Enable event batching
    pub event_batching: bool,

    /// Batch size for event processing
    pub batch_size: usize,

    /// Enable temporal event correlation
    pub temporal_correlation: bool,

    /// Temporal correlation window (ms)
    pub correlation_window: T,

    /// Enable adaptive event handling
    pub adaptive_handling: bool,

    /// Event rate limits (events/second)
    pub rate_limits: HashMap<EventType, T>,

    /// Enable event compression
    pub event_compression: bool,

    /// Compression algorithm
    pub compression_algorithm: EventCompressionAlgorithm,

    /// Enable distributed event processing
    pub distributed_processing: bool,

    /// Load balancing strategy
    pub load_balancing: LoadBalancingStrategy,
}

/// Event compression algorithms
#[derive(Debug, Clone, Copy)]
pub enum EventCompressionAlgorithm {
    /// No compression
    None,

    /// Delta encoding
    DeltaEncoding,

    /// Huffman encoding
    HuffmanEncoding,

    /// Run-length encoding
    RunLengthEncoding,

    /// Sparse encoding
    SparseEncoding,

    /// Predictive encoding
    PredictiveEncoding,
}

/// Load balancing strategies for distributed event processing
#[derive(Debug, Clone, Copy)]
pub enum LoadBalancingStrategy {
    /// Round-robin distribution
    RoundRobin,

    /// Event type-based partitioning
    TypeBased,

    /// Load-aware distribution
    LoadAware,

    /// Locality-aware distribution
    LocalityAware,

    /// Dynamic load balancing
    Dynamic,
}

impl<T: Float + Debug + Send + Sync + 'static> Default for EventDrivenConfig<T> {
    fn default() -> Self {
        let mut rate_limits = HashMap::new();
        rate_limits.insert(
            EventType::Spike,
            T::from(1000.0).unwrap_or_else(|| T::zero()),
        );
        rate_limits.insert(
            EventType::WeightUpdate,
            T::from(100.0).unwrap_or_else(|| T::zero()),
        );
        rate_limits.insert(
            EventType::PlasticityEvent,
            T::from(50.0).unwrap_or_else(|| T::zero()),
        );

        Self {
            max_queue_size: 10000,
            processing_timeout: T::from(1.0).unwrap_or_else(|| T::zero()),
            priority_scheduling: true,
            event_threshold: T::from(0.001).unwrap_or_else(|| T::zero()),
            event_batching: true,
            batch_size: 32,
            temporal_correlation: true,
            correlation_window: T::from(10.0).unwrap_or_else(|| T::zero()),
            adaptive_handling: true,
            rate_limits,
            event_compression: false,
            compression_algorithm: EventCompressionAlgorithm::None,
            distributed_processing: false,
            load_balancing: LoadBalancingStrategy::RoundRobin,
        }
    }
}

/// Priority queue entry for event scheduling
#[derive(Debug, Clone)]
struct PriorityEventEntry<T: Float + Debug + Send + Sync + 'static> {
    event: NeuromorphicEvent<T>,
    insertion_time: Instant,
}

impl<T: Float + Debug + Send + Sync + 'static> PartialEq for PriorityEventEntry<T> {
    fn eq(&self, other: &Self) -> bool {
        self.event.priority == other.event.priority
    }
}

impl<T: Float + Debug + Send + Sync + 'static> Eq for PriorityEventEntry<T> {}

impl<T: Float + Debug + Send + Sync + 'static> PartialOrd for PriorityEventEntry<T> {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl<T: Float + Debug + Send + Sync + 'static> Ord for PriorityEventEntry<T> {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        // Higher priority events come first (reverse order)
        other
            .event
            .priority
            .cmp(&self.event.priority)
            .then_with(|| self.insertion_time.cmp(&other.insertion_time))
    }
}

/// Event-driven optimizer
pub struct EventDrivenOptimizer<T: Float + Debug + Send + Sync + 'static> {
    /// Configuration
    config: EventDrivenConfig<T>,

    /// STDP configuration
    stdp_config: STDPConfig<T>,

    /// Membrane dynamics configuration
    membrane_config: MembraneDynamicsConfig<T>,

    /// Event queue with priority scheduling
    event_queue: BinaryHeap<PriorityEventEntry<T>>,

    /// Event processing statistics
    event_stats: HashMap<EventType, EventStatistics<T>>,

    /// Current system state
    system_state: SystemState<T>,

    /// Event handlers
    event_handlers: HashMap<EventType, Box<dyn EventHandler<T>>>,

    /// Temporal correlation tracker
    correlation_tracker: TemporalCorrelationTracker<T>,

    /// Event rate limiter
    rate_limiter: EventRateLimiter<T>,

    /// Performance metrics
    metrics: NeuromorphicMetrics<T>,

    /// Distributed processing coordinator
    distributed_coordinator: Option<DistributedEventCoordinator<T>>,

    /// Event compression engine
    compression_engine: EventCompressionEngine<T>,

    /// Adaptive handler
    adaptive_handler: AdaptiveEventHandler<T>,
}

/// Event processing statistics
#[derive(Debug, Clone)]
pub struct EventStatistics<T: Float + Debug + Send + Sync + 'static> {
    /// Total events processed
    pub total_processed: usize,

    /// Average processing time (ms)
    pub avg_processing_time: T,

    /// Event rate (events/second)
    pub event_rate: T,

    /// Queue wait time (ms)
    pub avg_queue_wait_time: T,

    /// Error count
    pub error_count: usize,

    /// Last update time
    pub last_update: Instant,
}

/// System state for event-driven optimization
#[derive(Debug, Clone)]
pub struct SystemState<T: Float + Debug + Send + Sync + 'static> {
    /// Current membrane potentials
    pub membrane_potentials: Array1<T>,

    /// Synaptic weights
    pub synaptic_weights: Array2<T>,

    /// Last spike times
    pub last_spike_times: Array1<T>,

    /// Refractory states
    pub refractory_until: Array1<T>,

    /// Current simulation time
    pub current_time: T,

    /// Active neurons
    pub active_neurons: HashSet<usize>,

    /// Pending weight updates
    pub pending_updates: HashMap<(usize, usize), T>,
}

/// Event handler trait
trait EventHandler<T: Float + Debug + Send + Sync + 'static>: Send + Sync {
    fn handle_event(
        &mut self,
        event: &NeuromorphicEvent<T>,
        state: &mut SystemState<T>,
    ) -> Result<()>;
    fn can_handle(&self, eventtype: EventType) -> bool;
}

/// Spike event handler
struct SpikeEventHandler<T: Float + Debug + Send + Sync + 'static> {
    stdp_config: STDPConfig<T>,
    membrane_config: MembraneDynamicsConfig<T>,
}

impl<T: Float + Debug + Send + Sync + 'static> EventHandler<T> for SpikeEventHandler<T> {
    fn handle_event(
        &mut self,
        event: &NeuromorphicEvent<T>,
        state: &mut SystemState<T>,
    ) -> Result<()> {
        let neuron_id = event.source_neuron;

        // Generate spike
        if neuron_id < state.membrane_potentials.len() {
            // Reset membrane potential
            state.membrane_potentials[neuron_id] = self.membrane_config.reset_potential;

            // Set refractory period
            state.refractory_until[neuron_id] =
                state.current_time + self.membrane_config.refractory_period;

            // Update last spike time
            state.last_spike_times[neuron_id] = state.current_time;

            // Add to active neurons
            state.active_neurons.insert(neuron_id);

            // Trigger STDP updates for connected synapses
            self.trigger_stdp_updates(neuron_id, state)?;
        }

        Ok(())
    }

    fn can_handle(&self, event_type: EventType) -> bool {
        event_type == EventType::Spike
    }
}

impl<T: Float + Debug + Send + Sync + 'static> SpikeEventHandler<T> {
    fn trigger_stdp_updates(&self, post_neuron: usize, state: &mut SystemState<T>) -> Result<()> {
        // Check all presynaptic connections
        for pre_neuron in 0..state.last_spike_times.len() {
            if pre_neuron != post_neuron {
                let pre_spike_time = state.last_spike_times[pre_neuron];

                if pre_spike_time > T::from(-1000.0).unwrap_or_else(|| T::zero()) {
                    let dt = state.current_time - pre_spike_time;
                    let weight_change = self.compute_stdp_weight_change(dt);

                    // Add to pending updates
                    state
                        .pending_updates
                        .insert((pre_neuron, post_neuron), weight_change);
                }
            }
        }

        Ok(())
    }

    fn compute_stdp_weight_change(&self, dt: T) -> T {
        if dt > T::zero() {
            // Post-before-pre: LTP
            let exp_arg = -dt / self.stdp_config.tau_pot;
            self.stdp_config.learning_rate_pot * exp_arg.exp()
        } else {
            // Pre-before-post: LTD
            let exp_arg = dt / self.stdp_config.tau_dep;
            -self.stdp_config.learning_rate_dep * exp_arg.exp()
        }
    }
}

/// Weight update event handler
struct WeightUpdateEventHandler<T: Float + Debug + Send + Sync + 'static> {
    stdp_config: STDPConfig<T>,
}

impl<T: Float + Debug + Send + Sync + 'static> EventHandler<T> for WeightUpdateEventHandler<T> {
    fn handle_event(
        &mut self,
        event: &NeuromorphicEvent<T>,
        state: &mut SystemState<T>,
    ) -> Result<()> {
        let source = event.source_neuron;

        if let Some(target) = event.target_neuron {
            if source < state.synaptic_weights.nrows() && target < state.synaptic_weights.ncols() {
                // Apply weight update
                let current_weight = state.synaptic_weights[[source, target]];
                let new_weight = (current_weight + event.value)
                    .max(self.stdp_config.weight_min)
                    .min(self.stdp_config.weight_max);

                state.synaptic_weights[[source, target]] = new_weight;
            }
        }

        Ok(())
    }

    fn can_handle(&self, event_type: EventType) -> bool {
        event_type == EventType::WeightUpdate
    }
}

/// Temporal correlation tracker
struct TemporalCorrelationTracker<T: Float + Debug + Send + Sync + 'static> {
    correlation_window: T,
    event_history: VecDeque<(T, EventType, usize)>,
    correlation_patterns: HashMap<(EventType, EventType), T>,
}

impl<T: Float + Debug + Send + Sync + 'static + std::ops::AddAssign> TemporalCorrelationTracker<T> {
    fn new(correlation_window: T) -> Self {
        Self {
            correlation_window,
            event_history: VecDeque::new(),
            correlation_patterns: HashMap::new(),
        }
    }

    fn add_event(&mut self, time: T, event_type: EventType, neuron_id: usize) {
        // Add new event
        self.event_history.push_back((time, event_type, neuron_id));

        // Remove old events outside correlation window
        while let Some(&(old_time, _, _)) = self.event_history.front() {
            if time - old_time > self.correlation_window {
                self.event_history.pop_front();
            } else {
                break;
            }
        }

        // Update correlation patterns
        self.update_correlations(time, event_type);
    }

    fn update_correlations(&mut self, current_time: T, current_event: EventType) {
        for &(event_time, event_type_, _) in &self.event_history {
            if current_time - event_time <= self.correlation_window {
                let correlation_key = (event_type_, current_event);
                let time_diff = current_time - event_time;
                let correlation_strength = (-time_diff / self.correlation_window).exp();

                *self
                    .correlation_patterns
                    .entry(correlation_key)
                    .or_insert(T::zero()) += correlation_strength;
            }
        }
    }

    fn get_correlation(&self, event1: EventType, event2: EventType) -> T {
        self.correlation_patterns
            .get(&(event1, event2))
            .copied()
            .unwrap_or(T::zero())
    }
}

/// Event rate limiter
struct EventRateLimiter<T: Float + Debug + Send + Sync + 'static> {
    rate_limits: HashMap<EventType, T>,
    event_counts: HashMap<EventType, usize>,
    last_reset: Instant,
    reset_interval: Duration,
}

impl<T: Float + Debug + Send + Sync + 'static> EventRateLimiter<T> {
    fn new(rate_limits: HashMap<EventType, T>) -> Self {
        Self {
            rate_limits,
            event_counts: HashMap::new(),
            last_reset: Instant::now(),
            reset_interval: Duration::from_secs(1),
        }
    }

    fn can_process(&mut self, event_type: EventType) -> bool {
        // Reset counters if interval elapsed
        if self.last_reset.elapsed() >= self.reset_interval {
            self.event_counts.clear();
            self.last_reset = Instant::now();
        }

        if let Some(&limit) = self.rate_limits.get(&event_type) {
            let current_count = self.event_counts.get(&event_type).copied().unwrap_or(0);
            if T::from(current_count).unwrap_or_else(|| T::zero()) < limit {
                *self.event_counts.entry(event_type).or_insert(0) += 1;
                true
            } else {
                false
            }
        } else {
            true
        }
    }
}

/// Event compression engine
struct EventCompressionEngine<T: Float + Debug + Send + Sync + 'static> {
    algorithm: EventCompressionAlgorithm,
    compression_buffer: Vec<u8>,
    decompression_buffer: Vec<u8>,
    _phantom: std::marker::PhantomData<T>,
}

impl<T: Float + Debug + Send + Sync + 'static> EventCompressionEngine<T> {
    fn new(algorithm: EventCompressionAlgorithm) -> Self {
        Self {
            algorithm,
            compression_buffer: Vec::new(),
            decompression_buffer: Vec::new(),
            _phantom: std::marker::PhantomData,
        }
    }

    fn compress_event(&mut self, event: &NeuromorphicEvent<T>) -> Result<Vec<u8>> {
        match self.algorithm {
            EventCompressionAlgorithm::None => {
                // No compression, serialize directly
                self.serialize_event(event)
            }
            EventCompressionAlgorithm::DeltaEncoding => self.delta_encode_event(event),
            EventCompressionAlgorithm::SparseEncoding => self.sparse_encode_event(event),
            _ => {
                // Fallback to no compression
                self.serialize_event(event)
            }
        }
    }

    fn serialize_event(&self, event: &NeuromorphicEvent<T>) -> Result<Vec<u8>> {
        // Simplified serialization
        let mut data = Vec::new();
        data.extend_from_slice(&(event.event_type as u8).to_le_bytes());
        data.extend_from_slice(&event.source_neuron.to_le_bytes());

        if let Some(target) = event.target_neuron {
            data.push(1);
            data.extend_from_slice(&target.to_le_bytes());
        } else {
            data.push(0);
        }

        Ok(data)
    }

    fn delta_encode_event(&mut self, event: &NeuromorphicEvent<T>) -> Result<Vec<u8>> {
        // Simplified delta encoding implementation
        Ok(vec![0u8; 16])
    }

    fn sparse_encode_event(&mut self, event: &NeuromorphicEvent<T>) -> Result<Vec<u8>> {
        // Simplified sparse encoding implementation
        Ok(vec![0u8; 8])
    }
}

/// Adaptive event handler
struct AdaptiveEventHandler<T: Float + Debug + Send + Sync + 'static> {
    adaptation_rate: T,
    performance_history: VecDeque<T>,
    current_strategy: AdaptationStrategy,
}

#[derive(Debug, Clone, Copy)]
enum AdaptationStrategy {
    Conservative,
    Balanced,
    Aggressive,
}

impl<T: Float + Debug + Send + Sync + 'static + std::iter::Sum> AdaptiveEventHandler<T> {
    fn new() -> Self {
        Self {
            adaptation_rate: T::from(0.1).unwrap_or_else(|| T::zero()),
            performance_history: VecDeque::new(),
            current_strategy: AdaptationStrategy::Balanced,
        }
    }

    fn adapt_processing(&mut self, current_performance: T) {
        self.performance_history.push_back(current_performance);

        if self.performance_history.len() > 100 {
            self.performance_history.pop_front();
        }

        if self.performance_history.len() >= 10 {
            let recent_avg = self
                .performance_history
                .iter()
                .rev()
                .take(10)
                .cloned()
                .sum::<T>()
                / T::from(10).unwrap_or_else(|| T::zero());
            let older_avg = if self.performance_history.len() >= 20 {
                self.performance_history
                    .iter()
                    .rev()
                    .skip(10)
                    .take(10)
                    .cloned()
                    .sum::<T>()
                    / T::from(10).unwrap_or_else(|| T::zero())
            } else {
                recent_avg
            };

            let performance_change = recent_avg - older_avg;

            self.current_strategy =
                if performance_change > T::from(0.1).unwrap_or_else(|| T::zero()) {
                    AdaptationStrategy::Aggressive
                } else if performance_change < T::from(-0.1).unwrap_or_else(|| T::zero()) {
                    AdaptationStrategy::Conservative
                } else {
                    AdaptationStrategy::Balanced
                };
        }
    }

    fn get_adaptation_factor(&self) -> T {
        match self.current_strategy {
            AdaptationStrategy::Conservative => T::from(0.5).unwrap_or_else(|| T::zero()),
            AdaptationStrategy::Balanced => T::one(),
            AdaptationStrategy::Aggressive => T::from(1.5).unwrap_or_else(|| T::zero()),
        }
    }
}

/// Distributed event coordinator
struct DistributedEventCoordinator<T: Float + Debug + Send + Sync + 'static> {
    load_balancing: LoadBalancingStrategy,
    worker_loads: HashMap<usize, T>,
    current_worker: usize,
    total_workers: usize,
}

impl<T: Float + Debug + Send + Sync + 'static> DistributedEventCoordinator<T> {
    fn new(strategy: LoadBalancingStrategy, num_workers: usize) -> Self {
        Self {
            load_balancing: strategy,
            worker_loads: HashMap::new(),
            current_worker: 0,
            total_workers: num_workers,
        }
    }

    fn assign_worker(&mut self, event: &NeuromorphicEvent<T>) -> usize {
        match self.load_balancing {
            LoadBalancingStrategy::RoundRobin => {
                let worker = self.current_worker;
                self.current_worker = (self.current_worker + 1) % self.total_workers;
                worker
            }
            LoadBalancingStrategy::TypeBased => {
                // Hash event type to worker
                (event.event_type as usize) % self.total_workers
            }
            LoadBalancingStrategy::LoadAware => {
                // Find worker with minimum load
                self.worker_loads
                    .iter()
                    .min_by(|a, b| a.1.partial_cmp(b.1).unwrap_or(std::cmp::Ordering::Equal))
                    .map(|(&worker_id, _)| worker_id)
                    .unwrap_or(0)
            }
            _ => 0,
        }
    }

    fn update_worker_load(&mut self, worker_id: usize, load: T) {
        self.worker_loads.insert(worker_id, load);
    }
}

impl<
        T: Float
            + Debug
            + Send
            + Sync
            + 'static
            + std::iter::Sum
            + scirs2_core::ndarray::ScalarOperand
            + std::ops::AddAssign,
    > EventDrivenOptimizer<T>
{
    /// Create a new event-driven optimizer
    pub fn new(
        config: EventDrivenConfig<T>,
        stdp_config: STDPConfig<T>,
        membrane_config: MembraneDynamicsConfig<T>,
        num_neurons: usize,
    ) -> Self {
        let mut optimizer = Self {
            config: config.clone(),
            stdp_config: stdp_config.clone(),
            membrane_config: membrane_config.clone(),
            event_queue: BinaryHeap::new(),
            event_stats: HashMap::new(),
            system_state: SystemState {
                membrane_potentials: Array1::from_elem(
                    num_neurons,
                    membrane_config.resting_potential,
                ),
                synaptic_weights: Array2::ones((num_neurons, num_neurons))
                    * T::from(0.1).unwrap_or_else(|| T::zero()),
                last_spike_times: Array1::from_elem(
                    num_neurons,
                    T::from(-1000.0).unwrap_or_else(|| T::zero()),
                ),
                refractory_until: Array1::zeros(num_neurons),
                current_time: T::zero(),
                active_neurons: HashSet::new(),
                pending_updates: HashMap::new(),
            },
            event_handlers: HashMap::new(),
            correlation_tracker: TemporalCorrelationTracker::new(config.correlation_window),
            rate_limiter: EventRateLimiter::new(config.rate_limits.clone()),
            metrics: NeuromorphicMetrics::default(),
            distributed_coordinator: if config.distributed_processing {
                Some(DistributedEventCoordinator::new(config.load_balancing, 4))
            } else {
                None
            },
            compression_engine: EventCompressionEngine::new(config.compression_algorithm),
            adaptive_handler: AdaptiveEventHandler::new(),
        };

        // Register default event handlers
        optimizer.register_default_handlers();

        optimizer
    }

    /// Register default event handlers
    fn register_default_handlers(&mut self) {
        let spike_handler = Box::new(SpikeEventHandler {
            stdp_config: self.stdp_config.clone(),
            membrane_config: self.membrane_config.clone(),
        });

        let weight_handler = Box::new(WeightUpdateEventHandler {
            stdp_config: self.stdp_config.clone(),
        });

        self.event_handlers.insert(EventType::Spike, spike_handler);
        self.event_handlers
            .insert(EventType::WeightUpdate, weight_handler);
    }

    /// Add event to the processing queue
    pub fn enqueue_event(&mut self, event: NeuromorphicEvent<T>) -> Result<()> {
        // Check rate limits
        if !self.rate_limiter.can_process(event.event_type) {
            return Err(OptimError::InvalidConfig("Rate limit exceeded".to_string()));
        }

        // Check queue capacity
        if self.event_queue.len() >= self.config.max_queue_size {
            return Err(OptimError::InvalidConfig("Event queue full".to_string()));
        }

        // Extract event fields before moving
        let timestamp = event.timestamp;
        let event_type = event.event_type;
        let source_neuron = event.source_neuron;

        let entry = PriorityEventEntry {
            event,
            insertion_time: Instant::now(),
        };

        self.event_queue.push(entry);

        // Update correlation tracking
        if self.config.temporal_correlation {
            self.correlation_tracker
                .add_event(timestamp, event_type, source_neuron);
        }

        Ok(())
    }

    /// Process events from the queue
    pub fn process_events(&mut self) -> Result<usize> {
        let mut processed_count = 0;
        let start_time = Instant::now();
        let timeout =
            Duration::from_millis(self.config.processing_timeout.to_u64().unwrap_or(1000));

        while !self.event_queue.is_empty() && start_time.elapsed() < timeout {
            if self.config.event_batching {
                let batch_size = self.config.batch_size.min(self.event_queue.len());
                processed_count += self.process_event_batch(batch_size)?;
            } else if let Some(entry) = self.event_queue.pop() {
                self.process_single_event(&entry.event)?;
                processed_count += 1;
            }
        }

        // Apply pending weight updates
        self.apply_pending_updates()?;

        // Update adaptive processing
        let processing_rate = T::from(processed_count).unwrap_or_else(|| T::zero())
            / T::from(start_time.elapsed().as_millis()).expect("unwrap failed");
        self.adaptive_handler.adapt_processing(processing_rate);

        Ok(processed_count)
    }

    /// Process a batch of events
    fn process_event_batch(&mut self, batch_size: usize) -> Result<usize> {
        let mut batch_events = Vec::with_capacity(batch_size);

        // Collect batch events
        for _ in 0..batch_size {
            if let Some(entry) = self.event_queue.pop() {
                batch_events.push(entry.event);
            } else {
                break;
            }
        }

        // Process batch
        for event in &batch_events {
            self.process_single_event(event)?;
        }

        Ok(batch_events.len())
    }

    /// Process a single event
    fn process_single_event(&mut self, event: &NeuromorphicEvent<T>) -> Result<()> {
        let start_time = Instant::now();

        // Find appropriate handler
        if let Some(handler) = self.event_handlers.get_mut(&event.event_type) {
            handler.handle_event(event, &mut self.system_state)?;
        } else {
            // Default handling
            self.default_event_handling(event)?;
        }

        // Update statistics
        let processing_time = start_time.elapsed().as_nanos() as f64 / 1_000_000.0;
        self.update_event_statistics(
            event.event_type,
            T::from(processing_time).unwrap_or_else(|| T::zero()),
        );

        // Update energy consumption
        self.metrics.energy_consumption += event.energy_cost;

        Ok(())
    }

    /// Default event handling
    fn default_event_handling(&mut self, event: &NeuromorphicEvent<T>) -> Result<()> {
        match event.event_type {
            EventType::ExternalStimulus
                // Apply external stimulus to neuron
                if event.source_neuron < self.system_state.membrane_potentials.len() => {
                    self.system_state.membrane_potentials[event.source_neuron] += event.value;
                }
            EventType::TimerEvent => {
                // Update system time
                self.system_state.current_time = event.timestamp;
            }
            _ => {
                // Ignore unknown events
            }
        }

        Ok(())
    }

    /// Apply pending weight updates
    fn apply_pending_updates(&mut self) -> Result<()> {
        for ((pre, post), weight_change) in self.system_state.pending_updates.drain() {
            if pre < self.system_state.synaptic_weights.nrows()
                && post < self.system_state.synaptic_weights.ncols()
            {
                let current_weight = self.system_state.synaptic_weights[[pre, post]];
                let new_weight = (current_weight + weight_change)
                    .max(self.stdp_config.weight_min)
                    .min(self.stdp_config.weight_max);

                self.system_state.synaptic_weights[[pre, post]] = new_weight;
            }
        }

        Ok(())
    }

    /// Update event processing statistics
    fn update_event_statistics(&mut self, event_type: EventType, processing_time: T) {
        let stats = self
            .event_stats
            .entry(event_type)
            .or_insert_with(|| EventStatistics {
                total_processed: 0,
                avg_processing_time: T::zero(),
                event_rate: T::zero(),
                avg_queue_wait_time: T::zero(),
                error_count: 0,
                last_update: Instant::now(),
            });

        stats.total_processed += 1;

        // Update average processing _time using exponential moving average
        let alpha = T::from(0.1).unwrap_or_else(|| T::zero());
        stats.avg_processing_time =
            stats.avg_processing_time * (T::one() - alpha) + processing_time * alpha;

        // Update event rate
        let time_since_last = stats.last_update.elapsed().as_secs_f64();
        if time_since_last > 0.0 {
            let current_rate = T::one() / T::from(time_since_last).unwrap_or_else(|| T::zero());
            stats.event_rate = stats.event_rate * (T::one() - alpha) + current_rate * alpha;
        }

        stats.last_update = Instant::now();
    }

    /// Get event processing statistics
    pub fn get_event_statistics(&self) -> &HashMap<EventType, EventStatistics<T>> {
        &self.event_stats
    }

    /// Get current system state
    pub fn get_system_state(&self) -> &SystemState<T> {
        &self.system_state
    }

    /// Get current metrics
    pub fn get_metrics(&self) -> &NeuromorphicMetrics<T> {
        &self.metrics
    }

    /// Clear event queue
    pub fn clear_event_queue(&mut self) {
        self.event_queue.clear();
    }

    /// Get queue size
    pub fn get_queue_size(&self) -> usize {
        self.event_queue.len()
    }

    /// Enable distributed processing
    pub fn enable_distributed_processing(&mut self, num_workers: usize) {
        self.distributed_coordinator = Some(DistributedEventCoordinator::new(
            self.config.load_balancing,
            num_workers,
        ));
        self.config.distributed_processing = true;
    }

    /// Disable distributed processing
    pub fn disable_distributed_processing(&mut self) {
        self.distributed_coordinator = None;
        self.config.distributed_processing = false;
    }
}

impl<T: Float + Debug + Send + Sync + 'static> Default for EventStatistics<T> {
    fn default() -> Self {
        Self {
            total_processed: 0,
            avg_processing_time: T::zero(),
            event_rate: T::zero(),
            avg_queue_wait_time: T::zero(),
            error_count: 0,
            last_update: Instant::now(),
        }
    }
}