optirs-core 0.3.2

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
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
// Energy-Efficient Optimization for Neuromorphic Computing
//
// This module implements energy-efficient optimization algorithms specifically designed
// for neuromorphic computing platforms, focusing on minimizing power consumption while
// maintaining performance and accuracy.

use super::{NeuromorphicMetrics, ThermalManagementConfig};
use crate::error::Result;
use scirs2_core::ndarray::{Array2, ArrayBase, Data, Dimension};
use scirs2_core::numeric::Float;
use std::collections::{HashMap, VecDeque};
use std::fmt::Debug;
use std::time::{Duration, Instant};

/// Convert an `f64` literal/derived value to the generic float type `T`,
/// falling back to `fallback` when the numeric type cannot represent it.
/// Defensive only: always succeeds for the `f32`/`f64` types this crate
/// targets.
#[inline]
fn to_t_or<T: Float>(value: f64, fallback: T) -> T {
    T::from(value).unwrap_or(fallback)
}

// --- Documented device power model -----------------------------------
//
// These constants define a small but real CMOS-style power model used to
// derive `current_power` and every optimization strategy's savings from
// the actual `WorkloadSample`/system state, instead of fixed percentages.
// The model has two components:
//
//   P_total = P_static(active_neurons) + P_dynamic * (V/V_nom)^2 * (f/f_nom)
//
// where `P_dynamic` is itself an activity-weighted sum of spike, synaptic
// and communication contributions. `(V/V_nom)^2 * (f/f_nom)` is the
// standard CMOS dynamic-power scaling law (`P_dyn ∝ C·V²·f`).

/// Nominal (reference) operating point: matches `DVFSController`'s
/// mid-range voltage/frequency level, used as the DVFS scaling baseline.
const NOMINAL_VOLTAGE: f64 = 1.0;
const NOMINAL_FREQUENCY_MHZ: f64 = 1000.0;

/// Static leakage power per provisioned neuron (nW), independent of
/// activity — this is what power-gating and clock-gating recover.
const STATIC_POWER_PER_NEURON_NW: f64 = 0.05;
/// Dynamic energy per spike (nJ) at the nominal operating point.
const DYNAMIC_ENERGY_PER_SPIKE_NJ: f64 = 0.02;
/// Dynamic power per unit of synaptic activity (nW) at nominal V/f.
const DYNAMIC_POWER_PER_SYNAPTIC_ACTIVITY_NW: f64 = 5.0;
/// Dynamic power per unit of communication overhead (nW) at nominal V/f.
const DYNAMIC_POWER_PER_COMM_OVERHEAD_NW: f64 = 2.0;

/// Number of independently power/clock-gateable neuron domains (a coarse,
/// fixed partition of the provisioned neuron population).
const GATING_DOMAINS: usize = 8;
/// Minimum idle fraction before any domain is considered worth gating (the
/// wake-up overhead makes gating unprofitable below this).
const GATING_IDLE_THRESHOLD: f64 = 0.15;
/// Fraction of a fully idle domain's dynamic power that clock gating can
/// actually recover (gating logic itself has overhead).
const CLOCK_GATING_EFFICIENCY: f64 = 0.9;
/// Fraction of dynamic power recovered in light vs. deep sleep, before
/// scaling by idle fraction.
const LIGHT_SLEEP_SAVINGS: f64 = 0.4;
const DEEP_SLEEP_SAVINGS: f64 = 0.85;
/// Idle fraction above which sleep mode escalates from light to deep sleep.
const DEEP_SLEEP_IDLE_THRESHOLD: f64 = 0.7;
/// Thermal throttling proportional-controller range (°C): no throttling
/// below the safe temperature, `THERMAL_MAX_REDUCTION` reached at or above
/// the critical temperature, linear in between.
const THERMAL_SAFE_TEMP_C: f64 = 60.0;
const THERMAL_CRITICAL_TEMP_C: f64 = 90.0;
const THERMAL_MIN_REDUCTION: f64 = 0.05;
const THERMAL_MAX_REDUCTION: f64 = 0.6;

/// Energy optimization strategies for neuromorphic computing
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum EnergyOptimizationStrategy {
    /// Dynamic voltage and frequency scaling
    DynamicVoltageScaling,

    /// Power gating for unused neurons
    PowerGating,

    /// Clock gating for inactive regions
    ClockGating,

    /// Adaptive precision reduction
    AdaptivePrecision,

    /// Sparse computation optimization
    SparseComputation,

    /// Event-driven processing
    EventDrivenProcessing,

    /// Sleep mode management
    SleepModeOptimization,

    /// Thermal-aware optimization
    ThermalAwareOptimization,

    /// Multi-level optimization
    MultiLevel,
}

/// Energy budget configuration
#[derive(Debug, Clone)]
pub struct EnergyBudget<T: Float + Debug + Send + Sync + 'static> {
    /// Total energy budget (nJ)
    pub total_budget: T,

    /// Current energy consumption (nJ)
    pub current_consumption: T,

    /// Energy budget per operation (nJ/op)
    pub per_operation_budget: T,

    /// Energy allocation per component
    pub component_allocation: HashMap<EnergyComponent, T>,

    /// Energy efficiency targets
    pub efficiency_targets: EnergyEfficiencyTargets<T>,

    /// Emergency energy reserves
    pub emergency_reserves: T,

    /// Energy monitoring frequency
    pub monitoring_frequency: Duration,
}

/// Energy components for budget allocation
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum EnergyComponent {
    /// Synaptic operations
    SynapticOps,

    /// Membrane dynamics
    MembraneDynamics,

    /// Spike generation
    SpikeGeneration,

    /// Plasticity updates
    PlasticityUpdates,

    /// Memory access
    MemoryAccess,

    /// Communication
    Communication,

    /// Control logic
    ControlLogic,

    /// Thermal management
    ThermalManagement,
}

/// Energy efficiency targets
#[derive(Debug, Clone)]
pub struct EnergyEfficiencyTargets<T: Float + Debug + Send + Sync + 'static> {
    /// Operations per joule target
    pub ops_per_joule: T,

    /// Spikes per joule target
    pub spikes_per_joule: T,

    /// Synaptic updates per joule target
    pub synaptic_updates_per_joule: T,

    /// Memory bandwidth efficiency (ops/J/bandwidth)
    pub memory_bandwidth_efficiency: T,

    /// Thermal efficiency (performance/Watt/°C)
    pub thermal_efficiency: T,
}

/// Energy-efficient optimizer configuration
#[derive(Debug, Clone)]
pub struct EnergyEfficientConfig<T: Float + Debug + Send + Sync + 'static> {
    /// Primary optimization strategy
    pub primary_strategy: EnergyOptimizationStrategy,

    /// Fallback strategies
    pub fallback_strategies: Vec<EnergyOptimizationStrategy>,

    /// Energy budget configuration
    pub energy_budget: EnergyBudget<T>,

    /// Enable adaptive strategy switching
    pub adaptive_strategy_switching: bool,

    /// Strategy switching threshold (efficiency drop %)
    pub strategy_switching_threshold: T,

    /// Enable predictive energy management
    pub predictive_energy_management: bool,

    /// Prediction horizon (ms)
    pub prediction_horizon: T,

    /// Enable energy harvesting support
    pub energy_harvesting: bool,

    /// Harvesting efficiency
    pub harvesting_efficiency: T,

    /// Enable distributed energy management
    pub distributed_energy_management: bool,

    /// Enable real-time energy monitoring
    pub real_time_monitoring: bool,

    /// Monitoring resolution (μs)
    pub monitoring_resolution: T,

    /// Enable energy-aware workload balancing
    pub energy_aware_load_balancing: bool,

    /// Energy optimization aggressiveness (0.0 to 1.0)
    pub optimization_aggressiveness: T,
}

impl<T: Float + Debug + Send + Sync + 'static> Default for EnergyEfficientConfig<T> {
    fn default() -> Self {
        let mut component_allocation = HashMap::new();
        component_allocation.insert(
            EnergyComponent::SynapticOps,
            T::from(0.4).unwrap_or_else(|| T::zero()),
        );
        component_allocation.insert(
            EnergyComponent::MembraneDynamics,
            T::from(0.2).unwrap_or_else(|| T::zero()),
        );
        component_allocation.insert(
            EnergyComponent::SpikeGeneration,
            T::from(0.15).unwrap_or_else(|| T::zero()),
        );
        component_allocation.insert(
            EnergyComponent::PlasticityUpdates,
            T::from(0.1).unwrap_or_else(|| T::zero()),
        );
        component_allocation.insert(
            EnergyComponent::MemoryAccess,
            T::from(0.1).unwrap_or_else(|| T::zero()),
        );
        component_allocation.insert(
            EnergyComponent::Communication,
            T::from(0.05).unwrap_or_else(|| T::zero()),
        );

        Self {
            primary_strategy: EnergyOptimizationStrategy::DynamicVoltageScaling,
            fallback_strategies: vec![
                EnergyOptimizationStrategy::PowerGating,
                EnergyOptimizationStrategy::ClockGating,
                EnergyOptimizationStrategy::SparseComputation,
            ],
            energy_budget: EnergyBudget {
                total_budget: T::from(1000.0).unwrap_or_else(|| T::zero()), // 1 μJ
                current_consumption: T::zero(),
                per_operation_budget: T::from(10.0).unwrap_or_else(|| T::zero()), // 10 nJ per op
                component_allocation,
                efficiency_targets: EnergyEfficiencyTargets {
                    ops_per_joule: T::from(1e12).unwrap_or_else(|| T::zero()), // 1 TOP/J
                    spikes_per_joule: T::from(1e9).unwrap_or_else(|| T::zero()), // 1 GSp/J
                    synaptic_updates_per_joule: T::from(1e10).unwrap_or_else(|| T::zero()), // 10 GSyOp/J
                    memory_bandwidth_efficiency: T::from(1e6).unwrap_or_else(|| T::zero()),
                    thermal_efficiency: T::from(1e9).unwrap_or_else(|| T::zero()),
                },
                emergency_reserves: T::from(100.0).unwrap_or_else(|| T::zero()), // 100 nJ reserve
                monitoring_frequency: Duration::from_micros(100),
            },
            adaptive_strategy_switching: true,
            strategy_switching_threshold: T::from(0.1).unwrap_or_else(|| T::zero()), // 10% efficiency drop
            predictive_energy_management: true,
            prediction_horizon: T::from(10.0).unwrap_or_else(|| T::zero()), // 10 ms
            energy_harvesting: false,
            harvesting_efficiency: T::from(0.1).unwrap_or_else(|| T::zero()),
            distributed_energy_management: false,
            real_time_monitoring: true,
            monitoring_resolution: T::from(1.0).unwrap_or_else(|| T::zero()), // 1 μs
            energy_aware_load_balancing: true,
            optimization_aggressiveness: T::from(0.7).unwrap_or_else(|| T::zero()),
        }
    }
}

/// Energy monitoring and tracking
#[derive(Debug, Clone)]
struct EnergyMonitor<
    T: Float
        + Debug
        + scirs2_core::ndarray::ScalarOperand
        + std::fmt::Debug
        + std::iter::Sum
        + Send
        + Sync,
> {
    /// Energy consumption history
    consumption_history: VecDeque<(Instant, T)>,

    /// Power consumption history
    power_history: VecDeque<(Instant, T)>,

    /// Current power draw (nW)
    current_power: T,

    /// Peak power observed (nW)
    peak_power: T,

    /// Average power over window (nW)
    average_power: T,

    /// Last monitoring update
    last_update: Instant,

    /// Monitoring window size
    window_size: Duration,
}

/// Dynamic voltage and frequency scaling controller
#[derive(Debug, Clone)]
struct DVFSController<T: Float + Debug + Send + Sync + 'static> {
    /// Available voltage levels (V)
    voltage_levels: Vec<T>,

    /// Available frequency levels (MHz)
    frequency_levels: Vec<T>,

    /// Current voltage index
    current_voltage_idx: usize,

    /// Current frequency index
    current_frequency_idx: usize,
}

impl<T: Float + Debug + Send + Sync + 'static> DVFSController<T> {
    fn new() -> Self {
        Self {
            voltage_levels: vec![
                to_t_or(0.7, T::one()),
                to_t_or(0.9, T::one()),
                to_t_or(1.0, T::one()),
                to_t_or(1.2, T::one()),
            ],
            frequency_levels: vec![
                to_t_or(500.0, T::one()),
                to_t_or(1000.0, T::one()),
                to_t_or(1500.0, T::one()),
                to_t_or(2000.0, T::one()),
            ],
            current_voltage_idx: 2,
            current_frequency_idx: 2,
        }
    }

    /// Choose a voltage/frequency level proportional to how utilized the
    /// device is for this workload sample: a workload using few of the
    /// provisioned neurons is scaled down towards the lowest V/f level, a
    /// fully-active workload runs at the highest.
    fn compute_optimal_levels(
        &mut self,
        workload: &WorkloadSample<T>,
        total_neurons: usize,
    ) -> Result<(T, T)> {
        let total = to_t_or(total_neurons.max(1) as f64, T::one());
        let utilization = (to_t_or(workload.active_neurons as f64, T::zero()) / total)
            .max(T::zero())
            .min(T::one());
        let idx = (utilization * to_t_or((self.voltage_levels.len() - 1) as f64, T::zero()))
            .to_usize()
            .unwrap_or(2);

        self.current_voltage_idx = idx.min(self.voltage_levels.len() - 1);
        self.current_frequency_idx = idx.min(self.frequency_levels.len() - 1);

        Ok((
            self.voltage_levels[self.current_voltage_idx],
            self.frequency_levels[self.current_frequency_idx],
        ))
    }
}

/// Power gating controller
#[derive(Debug, Clone)]
struct PowerGatingController<T: Float + Debug + Send + Sync + 'static> {
    /// Gated neuron groups
    gated_groups: HashMap<usize, GatedGroup>,

    /// Power gate overhead energy
    gate_overhead_energy: f64,

    /// Total provisioned neurons, used to size each gateable domain.
    total_neurons: usize,

    /// Phantom data for type parameter
    _phantom: std::marker::PhantomData<T>,
}

impl<T: Float + Debug + Send + Sync + 'static> PowerGatingController<T> {
    fn new(total_neurons: usize) -> Self {
        Self {
            gated_groups: HashMap::new(),
            gate_overhead_energy: 0.001,
            total_neurons: total_neurons.max(1),
            _phantom: std::marker::PhantomData,
        }
    }

    /// Power saved (nW) by gating `region_id`, proportional to the static
    /// leakage power of the neurons in that domain scaled by how idle the
    /// current workload is (a domain fully idle recovers its whole static
    /// power budget; the recovery is proportional otherwise).
    fn gate_region(&mut self, region_id: usize, idle_fraction: T) -> Result<T> {
        let neurons_per_domain = (self.total_neurons / GATING_DOMAINS.max(1)).max(1);
        let domain_static_power = to_t_or(
            neurons_per_domain as f64 * STATIC_POWER_PER_NEURON_NW,
            T::zero(),
        );
        let saved = domain_static_power * idle_fraction;

        // Only the gated flag is ever read back; the surrounding bookkeeping
        // fields (`neuron_ids`, `last_activity`, thresholds) were written once
        // at insert and never updated or consulted, so they are not modelled.
        self.gated_groups
            .insert(region_id, GatedGroup { is_gated: true });

        Ok(saved)
    }

    /// Identify which fixed neuron domains are idle enough (given this
    /// workload's idle fraction) to be worth power-gating. The number of
    /// domains gated scales with how idle the device is, rather than a
    /// single fixed region.
    fn identify_gatable_regions(&self, idle_fraction: T) -> Vec<usize> {
        if idle_fraction < to_t_or(GATING_IDLE_THRESHOLD, T::zero()) {
            return Vec::new();
        }
        let fraction = idle_fraction.to_f64().unwrap_or(0.0).clamp(0.0, 1.0);
        let gatable_domains =
            ((fraction * GATING_DOMAINS as f64).round() as usize).clamp(1, GATING_DOMAINS);
        (0..gatable_domains).collect()
    }
}

/// Gated neuron group
#[derive(Debug, Clone)]
struct GatedGroup {
    /// Whether this domain is currently power-gated.
    is_gated: bool,
}

/// Sparse computation optimizer
#[derive(Debug, Clone)]
struct SparseComputationOptimizer<T: Float + Debug + Send + Sync + 'static> {
    /// Sparsity threshold
    sparsity_threshold: T,

    /// Total provisioned neurons, used as the activity-estimate denominator
    /// when no real weight/activation matrix is available.
    total_neurons: usize,
}

impl<T: Float + Debug + Send + Sync + 'static> SparseComputationOptimizer<T> {
    fn new(total_neurons: usize) -> Self {
        Self {
            sparsity_threshold: to_t_or(0.01, T::zero()),
            total_neurons: total_neurons.max(1),
        }
    }

    /// Estimate the sparsity relevant to this optimization step.
    ///
    /// When `matrix` is provided, sparsity is the *real* fraction of
    /// near-zero entries in it (elements with `|v| <= sparsity_threshold`).
    /// Otherwise it falls back to an activity-derived estimate using the
    /// device's actual provisioned neuron count: `1 - active/total`.
    fn analyze_sparsity<S, Dm>(
        &mut self,
        workload: &WorkloadSample<T>,
        matrix: Option<&ArrayBase<S, Dm>>,
    ) -> Result<SparsityAnalysis<T>>
    where
        S: Data<Elem = T>,
        Dm: Dimension,
    {
        let sparsity_ratio = if let Some(m) = matrix {
            let total = m.len().max(1);
            let zero_count = m
                .iter()
                .filter(|&&v| v.abs() <= self.sparsity_threshold)
                .count();
            to_t_or(zero_count as f64 / total as f64, T::zero())
        } else {
            let total = to_t_or(self.total_neurons as f64, T::one());
            let active = to_t_or(workload.active_neurons as f64, T::zero());
            (T::one() - (active / total)).max(T::zero()).min(T::one())
        };

        Ok(SparsityAnalysis { sparsity_ratio })
    }

    /// Energy saved by skipping the near-zero entries.
    ///
    /// Derived from the *measured* `sparsity_ratio` rather than a value
    /// pre-baked at analysis time: `SPARSE_SAVING_EFFICIENCY` is the fraction
    /// of the skipped work that translates into energy, the rest being indexing
    /// and gather overhead a sparse kernel still pays.
    fn apply_compression(&mut self, analysis: &SparsityAnalysis<T>) -> Result<T> {
        Ok(analysis.sparsity_ratio * to_t_or(SPARSE_SAVING_EFFICIENCY, T::zero()))
    }

    fn apply_sparse_optimizations(&mut self, analysis: &SparsityAnalysis<T>) -> Result<T> {
        // Apply sparse optimizations based on analysis
        let compression_savings = self.apply_compression(analysis)?;
        Ok(compression_savings)
    }
}

/// Fraction of the work skipped by sparsity that becomes real energy saving;
/// the remainder is indexing/gather overhead a sparse kernel still pays.
const SPARSE_SAVING_EFFICIENCY: f64 = 0.8;

#[derive(Debug, Clone)]
struct SparsityAnalysis<T: Float + Debug + Send + Sync + 'static> {
    /// Measured fraction of near-zero entries.
    sparsity_ratio: T,
}

/// Energy-efficient optimizer
pub struct EnergyEfficientOptimizer<
    T: Float
        + Debug
        + scirs2_core::ndarray::ScalarOperand
        + std::fmt::Debug
        + std::iter::Sum
        + Send
        + Sync,
> {
    /// Configuration
    config: EnergyEfficientConfig<T>,

    /// Energy monitor
    energy_monitor: EnergyMonitor<T>,

    /// DVFS controller
    dvfs_controller: DVFSController<T>,

    /// Power gating controller
    power_gating_controller: PowerGatingController<T>,

    /// Sparse computation optimizer
    sparse_optimizer: SparseComputationOptimizer<T>,

    /// Thermal management
    thermal_manager: ThermalManager<T>,

    /// Predictive energy manager
    predictive_manager: PredictiveEnergyManager<T>,

    /// Current optimization strategy
    current_strategy: EnergyOptimizationStrategy,

    /// Strategy effectiveness history
    strategy_effectiveness: HashMap<EnergyOptimizationStrategy, T>,

    /// System state
    system_state: EnergySystemState<T>,

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

/// Energy system state
#[derive(Debug, Clone)]
pub struct EnergySystemState<T: Float + Debug + Send + Sync + 'static> {
    /// Current energy consumption (nJ)
    pub current_energy: T,

    /// Current power consumption (nW)
    pub current_power: T,

    /// Temperature (°C)
    pub temperature: T,

    /// Active neuron count
    pub active_neurons: usize,

    /// Active synapses count
    pub active_synapses: usize,

    /// Current voltage (V)
    pub current_voltage: T,

    /// Current frequency (MHz)
    pub current_frequency: T,

    /// Gated regions
    pub gated_regions: Vec<usize>,

    /// Sleep mode status
    pub sleep_status: SleepStatus,
}

#[derive(Debug, Clone, Copy)]
pub enum SleepStatus {
    Active,
    LightSleep,
    DeepSleep,
    Hibernation,
}

/// Thermal manager for energy efficiency
#[derive(Debug, Clone)]
struct ThermalManager<T: Float + Debug + Send + Sync + 'static> {
    /// Current temperature reading (°C)
    current_temperature: T,

    /// Temperature history
    temperature_history: VecDeque<(Instant, T)>,

    /// Thermal model parameters
    thermal_model: ThermalModel<T>,

    /// Timestamp of the previous `update()` call, used to integrate the
    /// thermal RC model over the actual elapsed time (F59).
    last_update: Instant,
}

impl<T: Float + Debug + Send + Sync + 'static> ThermalManager<T> {
    /// Builds a thermal manager. The configuration is consumed to seed the
    /// thermal model rather than stored: nothing read it back.
    fn new(_config: ThermalManagementConfig<T>) -> Self {
        Self {
            current_temperature: to_t_or(25.0, T::zero()),
            temperature_history: VecDeque::new(),
            thermal_model: ThermalModel {
                time_constant: to_t_or(10.0, T::one()),
                thermal_resistance: to_t_or(0.5, T::zero()),
                ambient_temperature: to_t_or(25.0, T::zero()),
            },
            last_update: Instant::now(),
        }
    }

    /// Integrate the thermal RC model one step forward (F59):
    /// `dT/dt = (P·R + T_amb - T) / τ`, discretized over the actual
    /// elapsed time since the previous call as
    /// `T += dt/τ · (P·R + T_amb - T)`. Unlike the previous instantaneous
    /// `T = P·R + T_amb` formula, this respects thermal inertia (a sudden
    /// power spike heats the die gradually, not instantly).
    fn update(&mut self, system_state: &EnergySystemState<T>) -> Result<()> {
        let now = Instant::now();
        let dt_seconds = to_t_or(
            now.duration_since(self.last_update).as_secs_f64().max(1e-6),
            to_t_or(1e-3, T::one()),
        );
        self.last_update = now;

        let steady_state = system_state.current_power * self.thermal_model.thermal_resistance
            + self.thermal_model.ambient_temperature;
        let tau = if self.thermal_model.time_constant > T::zero() {
            self.thermal_model.time_constant
        } else {
            T::one()
        };
        self.current_temperature = self.current_temperature
            + (dt_seconds / tau) * (steady_state - self.current_temperature);

        self.temperature_history
            .push_back((now, self.current_temperature));
        // Bound the history so it cannot grow without limit (F59).
        while self.temperature_history.len() > 100 {
            self.temperature_history.pop_front();
        }
        Ok(())
    }
}

/// Thermal model for prediction
#[derive(Debug, Clone)]
struct ThermalModel<T: Float + Debug + Send + Sync + 'static> {
    /// Thermal time constant (s)
    time_constant: T,

    /// Thermal resistance (°C/W)
    thermal_resistance: T,

    /// Ambient temperature (°C)
    ambient_temperature: T,
}

/// Predictive energy manager
#[derive(Debug, Clone)]
struct PredictiveEnergyManager<T: Float + Debug + Send + Sync + 'static> {
    /// Workload history
    workload_history: VecDeque<WorkloadSample<T>>,

    /// Observed `(timestamp, power_nw)` samples used to fit the linear
    /// trend that [`Self::predict_energy`] extrapolates from (F18: this
    /// history used to never be populated, so predictions always fell back
    /// to a fabricated constant regardless of `horizon`).
    power_history: VecDeque<(Instant, T)>,
}

impl<T: Float + Debug + Send + Sync + 'static> PredictiveEnergyManager<T> {
    fn new() -> Self {
        Self {
            workload_history: VecDeque::new(),
            power_history: VecDeque::new(),
        }
    }

    /// Record an observed workload/power sample so future
    /// [`Self::predict_energy`] calls have real data to extrapolate from.
    fn record_sample(&mut self, workload: WorkloadSample<T>, power: T) {
        self.power_history.push_back((Instant::now(), power));
        while self.power_history.len() > 100 {
            self.power_history.pop_front();
        }
        self.workload_history.push_back(workload);
        while self.workload_history.len() > 100 {
            self.workload_history.pop_front();
        }
    }

    /// Predict total energy (nJ) expected over the next `horizon`, by
    /// extrapolating the recent average power draw (nW) across that
    /// window: `E = P_avg * horizon` (F18: `horizon` was previously
    /// accepted but never used, and with no history ever recorded this
    /// always returned a hardcoded `1.0`).
    fn predict_energy(&self, horizon: Duration) -> Result<T> {
        if self.power_history.is_empty() {
            return Ok(T::zero());
        }
        let sum: T = self
            .power_history
            .iter()
            .map(|(_, power)| *power)
            .fold(T::zero(), |acc, x| acc + x);
        let avg_power = sum / to_t_or(self.power_history.len() as f64, T::one());

        // Mirrors the file's `energy(nJ) = power(nW) * time(ms) / 1000`
        // convention used throughout the strategy implementations above.
        let horizon_ms = to_t_or(horizon.as_secs_f64() * 1000.0, T::zero());
        let predicted = avg_power * horizon_ms / to_t_or(1000.0, T::one());

        Ok(predicted)
    }
}

/// Workload sample for prediction
#[derive(Debug, Clone)]
pub struct WorkloadSample<T: Float + Debug + Send + Sync + 'static> {
    /// Timestamp
    pub timestamp: Instant,

    /// Number of active neurons
    pub active_neurons: usize,

    /// Spike rate (Hz)
    pub spike_rate: T,

    /// Synaptic activity
    pub synaptic_activity: T,

    /// Memory access pattern
    pub memory_access_pattern: MemoryAccessPattern,

    /// Communication overhead
    pub communication_overhead: T,
}

#[derive(Debug, Clone, Copy)]
pub enum MemoryAccessPattern {
    Sequential,
    Random,
    Sparse,
    Burst,
    Mixed,
}

impl<
        T: Float
            + Debug
            + Send
            + Sync
            + scirs2_core::ndarray::ScalarOperand
            + std::fmt::Debug
            + std::iter::Sum,
    > EnergyEfficientOptimizer<T>
{
    /// Create a new energy-efficient optimizer
    pub fn new(_config: EnergyEfficientConfig<T>, numneurons: usize) -> Self {
        Self {
            config: _config.clone(),
            energy_monitor: EnergyMonitor::new(_config.energy_budget.monitoring_frequency),
            dvfs_controller: DVFSController::new(),
            power_gating_controller: PowerGatingController::new(numneurons),
            sparse_optimizer: SparseComputationOptimizer::new(numneurons),
            thermal_manager: ThermalManager::new(ThermalManagementConfig::default()),
            predictive_manager: PredictiveEnergyManager::new(),
            current_strategy: _config.primary_strategy,
            strategy_effectiveness: HashMap::new(),
            system_state: EnergySystemState {
                current_energy: T::zero(),
                current_power: T::zero(),
                temperature: T::from(25.0).unwrap_or_else(|| T::zero()), // 25°C ambient
                active_neurons: numneurons,
                active_synapses: numneurons * numneurons,
                current_voltage: T::from(1.0).unwrap_or_else(|| T::zero()), // 1V
                current_frequency: T::from(100.0).unwrap_or_else(|| T::zero()), // 100 MHz
                gated_regions: Vec::new(),
                sleep_status: SleepStatus::Active,
            },
            metrics: NeuromorphicMetrics::default(),
        }
    }

    /// Optimize energy consumption
    pub fn optimize_energy(
        &mut self,
        workload: &WorkloadSample<T>,
    ) -> Result<EnergyOptimizationResult<T>> {
        self.optimize_energy_impl(workload, None::<&Array2<T>>)
    }

    /// Like [`Self::optimize_energy`], but lets the caller supply a real
    /// weight/activation matrix so that, when the active strategy is
    /// [`EnergyOptimizationStrategy::SparseComputation`], sparsity is
    /// measured from the matrix's actual zero fraction instead of an
    /// activity-derived estimate (F18).
    pub fn optimize_energy_with_matrix<S, Dm>(
        &mut self,
        workload: &WorkloadSample<T>,
        matrix: Option<&ArrayBase<S, Dm>>,
    ) -> Result<EnergyOptimizationResult<T>>
    where
        S: Data<Elem = T>,
        Dm: Dimension,
    {
        self.optimize_energy_impl(workload, matrix)
    }

    fn optimize_energy_impl<S, Dm>(
        &mut self,
        workload: &WorkloadSample<T>,
        matrix: Option<&ArrayBase<S, Dm>>,
    ) -> Result<EnergyOptimizationResult<T>>
    where
        S: Data<Elem = T>,
        Dm: Dimension,
    {
        // Update energy monitoring
        self.energy_monitor.update(&self.system_state)?;

        // Get energy predictions (horizon-aware forecast for the next
        // minute; exercised here so predictive strategy switching has a
        // real signal to react to in future extensions).
        let _prediction = if self.config.predictive_energy_management {
            self.predictive_manager
                .predict_energy(Duration::from_secs(60))?
        } else {
            T::zero()
        };

        // Apply current optimization strategy
        let optimization_result = match self.current_strategy {
            EnergyOptimizationStrategy::DynamicVoltageScaling => {
                self.apply_dvfs_optimization(workload)?
            }
            EnergyOptimizationStrategy::PowerGating => {
                self.apply_power_gating_optimization(workload)?
            }
            EnergyOptimizationStrategy::ClockGating => {
                self.apply_clock_gating_optimization(workload)?
            }
            EnergyOptimizationStrategy::SparseComputation => {
                self.apply_sparse_computation_optimization(workload, matrix)?
            }
            EnergyOptimizationStrategy::SleepModeOptimization => {
                self.apply_sleep_mode_optimization(workload)?
            }
            EnergyOptimizationStrategy::ThermalAwareOptimization => {
                self.apply_thermal_aware_optimization(workload)?
            }
            EnergyOptimizationStrategy::MultiLevel => {
                self.apply_multi_level_optimization(workload)?
            }
            _ => {
                // Default optimization
                self.apply_default_optimization(workload)?
            }
        };

        // Record this (workload, power) sample for future predictions
        // (F18: `predict_energy` previously always saw an empty history and
        // returned a fabricated constant).
        self.predictive_manager
            .record_sample(workload.clone(), self.system_state.current_power);

        // Evaluate strategy effectiveness
        self.evaluate_strategy_effectiveness(&optimization_result);

        // Adaptive strategy switching
        if self.config.adaptive_strategy_switching {
            self.consider_strategy_switch()?;
        }

        // Update thermal management (RC-integrated, F59) and sync the
        // authoritative temperature back into `system_state` so the
        // thermal-aware strategy above reacts to the real modeled
        // temperature rather than a disconnected, manually decayed value.
        self.thermal_manager.update(&self.system_state)?;
        self.system_state.temperature = self.thermal_manager.current_temperature;

        // Update metrics
        self.update_metrics(&optimization_result);

        Ok(optimization_result)
    }

    /// Fraction of the device's provisioned neurons that are idle for this
    /// workload sample, clamped to `[0, 1]`. This is the common activity
    /// signal driving clock-gating, power-gating and sleep-mode savings
    /// below (F18): a workload using few of the provisioned neurons frees
    /// up a correspondingly large fraction of gateable/sleepable capacity.
    fn idle_fraction(&self, workload: &WorkloadSample<T>) -> T {
        let total = to_t_or(self.system_state.active_neurons.max(1) as f64, T::one());
        let active = to_t_or(workload.active_neurons as f64, T::zero());
        (T::one() - (active / total)).max(T::zero()).min(T::one())
    }

    /// Estimate the instantaneous power draw (nW) implied by a workload
    /// sample at the device's current voltage/frequency operating point:
    /// `P = P_static(active_neurons) + P_dynamic(spikes, synapses, comm) *
    /// (V/V_nom)² * (f/f_nom)`. This replaces reading back a stored
    /// `current_power` field that starts at (and can get stuck at) zero;
    /// every strategy below derives its baseline from the actual workload.
    fn estimate_workload_power(&self, workload: &WorkloadSample<T>) -> T {
        // Static leakage is incurred by the whole provisioned chip
        // (`system_state.active_neurons`, fixed at construction), not just
        // by however many neurons this particular sample activates — an
        // idle neuron still leaks, which is exactly what clock/power
        // gating and sleep mode recover below via `idle_fraction`.
        let static_power = to_t_or(
            self.system_state.active_neurons as f64 * STATIC_POWER_PER_NEURON_NW,
            T::zero(),
        );
        let spike_power = workload.spike_rate * to_t_or(DYNAMIC_ENERGY_PER_SPIKE_NJ, T::zero());
        let synaptic_power =
            workload.synaptic_activity * to_t_or(DYNAMIC_POWER_PER_SYNAPTIC_ACTIVITY_NW, T::zero());
        let comm_power = workload.communication_overhead
            * to_t_or(DYNAMIC_POWER_PER_COMM_OVERHEAD_NW, T::zero());
        let dynamic_baseline = spike_power + synaptic_power + comm_power;

        let v_nom = to_t_or(NOMINAL_VOLTAGE, T::one());
        let f_nom = to_t_or(NOMINAL_FREQUENCY_MHZ, T::one());
        let voltage_ratio = if v_nom > T::zero() {
            self.system_state.current_voltage / v_nom
        } else {
            T::one()
        };
        let freq_ratio = if f_nom > T::zero() {
            self.system_state.current_frequency / f_nom
        } else {
            T::one()
        };

        static_power + dynamic_baseline * voltage_ratio * voltage_ratio * freq_ratio
    }

    /// Apply DVFS optimization
    fn apply_dvfs_optimization(
        &mut self,
        workload: &WorkloadSample<T>,
    ) -> Result<EnergyOptimizationResult<T>> {
        // Baseline power under the workload at the CURRENT operating point.
        let initial_power = self.estimate_workload_power(workload);

        // Capture the pre-transition operating point BEFORE mutating state
        // (F17: previously voltage/frequency were overwritten first and
        // the reduction ratio was computed against those *new* values,
        // forcing numerator == denominator == 1.0 on every call).
        let v_old = self.system_state.current_voltage;
        let f_old = self.system_state.current_frequency;

        // Determine optimal voltage and frequency for this workload.
        let (optimal_voltage, optimal_frequency) = self
            .dvfs_controller
            .compute_optimal_levels(workload, self.system_state.active_neurons)?;

        let power_reduction =
            self.calculate_power_reduction(v_old, f_old, optimal_voltage, optimal_frequency);
        let performance_impact = self.calculate_performance_impact(f_old, optimal_frequency);
        let new_power = initial_power * power_reduction;
        let thermal_impact = self.calculate_thermal_impact(initial_power, new_power);

        // Commit the new operating point and derived power.
        self.system_state.current_voltage = optimal_voltage;
        self.system_state.current_frequency = optimal_frequency;
        self.system_state.current_power = new_power;

        // Update accumulated energy consumption (nJ) over a 1 ms step.
        let time_delta = to_t_or(1.0, T::one());
        let energy_delta = new_power * time_delta / to_t_or(1000.0, T::one());
        self.system_state.current_energy = self.system_state.current_energy + energy_delta;

        Ok(EnergyOptimizationResult {
            strategy_used: EnergyOptimizationStrategy::DynamicVoltageScaling,
            energy_saved: (initial_power - new_power).max(T::zero()) * time_delta
                / to_t_or(1000.0, T::one()),
            power_reduction: initial_power - new_power,
            performance_impact,
            thermal_impact,
            optimization_overhead: to_t_or(0.1, T::zero()), // 0.1 nJ overhead
        })
    }

    /// Apply power gating optimization
    fn apply_power_gating_optimization(
        &mut self,
        workload: &WorkloadSample<T>,
    ) -> Result<EnergyOptimizationResult<T>> {
        let initial_power = self.estimate_workload_power(workload);
        let idle_fraction = self.idle_fraction(workload);

        // Identify idle domains worth gating, sized to how idle we are.
        let gatable_regions = self
            .power_gating_controller
            .identify_gatable_regions(idle_fraction);

        let mut total_power_saved = T::zero();
        for region_id in gatable_regions {
            let power_saved = self
                .power_gating_controller
                .gate_region(region_id, idle_fraction)?;
            total_power_saved = total_power_saved + power_saved;
            if !self.system_state.gated_regions.contains(&region_id) {
                self.system_state.gated_regions.push(region_id);
            }
        }

        let new_power = (initial_power - total_power_saved).max(T::zero());
        self.system_state.current_power = new_power;

        let time_delta = to_t_or(1.0, T::one());
        let energy_saved = total_power_saved * time_delta / to_t_or(1000.0, T::one());
        let overhead = to_t_or(self.power_gating_controller.gate_overhead_energy, T::zero())
            * to_t_or(self.system_state.gated_regions.len() as f64, T::zero());

        Ok(EnergyOptimizationResult {
            strategy_used: EnergyOptimizationStrategy::PowerGating,
            energy_saved,
            power_reduction: total_power_saved,
            performance_impact: T::zero(), // Gated domains resume on demand
            thermal_impact: total_power_saved * to_t_or(0.8, T::zero()),
            optimization_overhead: overhead,
        })
    }

    /// Apply sparse computation optimization. `matrix`, when present, gives
    /// the *real* sparsity of the current weight/activation tensor (F18);
    /// otherwise sparsity is estimated from workload activity.
    fn apply_sparse_computation_optimization<S, Dm>(
        &mut self,
        workload: &WorkloadSample<T>,
        matrix: Option<&ArrayBase<S, Dm>>,
    ) -> Result<EnergyOptimizationResult<T>>
    where
        S: Data<Elem = T>,
        Dm: Dimension,
    {
        let initial_power = self.estimate_workload_power(workload);

        // Analyze sparsity patterns
        let sparsity_analysis = self.sparse_optimizer.analyze_sparsity(workload, matrix)?;

        // Apply sparse optimizations
        let energy_savings = self
            .sparse_optimizer
            .apply_sparse_optimizations(&sparsity_analysis)?;

        // Update system state
        let new_power = initial_power * (T::one() - energy_savings);
        self.system_state.current_power = new_power;

        Ok(EnergyOptimizationResult {
            strategy_used: EnergyOptimizationStrategy::SparseComputation,
            energy_saved: initial_power * energy_savings,
            power_reduction: initial_power - new_power,
            performance_impact: energy_savings * to_t_or(0.1, T::zero()), // Small performance impact
            thermal_impact: (initial_power - new_power) * to_t_or(0.9, T::zero()),
            optimization_overhead: to_t_or(0.2, T::zero()), // Moderate overhead
        })
    }

    /// Apply multi-level optimization
    fn apply_multi_level_optimization(
        &mut self,
        workload: &WorkloadSample<T>,
    ) -> Result<EnergyOptimizationResult<T>> {
        let mut total_result = EnergyOptimizationResult {
            strategy_used: EnergyOptimizationStrategy::MultiLevel,
            energy_saved: T::zero(),
            power_reduction: T::zero(),
            performance_impact: T::zero(),
            thermal_impact: T::zero(),
            optimization_overhead: T::zero(),
        };

        // Apply multiple strategies in sequence
        let strategies = [
            EnergyOptimizationStrategy::SparseComputation,
            EnergyOptimizationStrategy::DynamicVoltageScaling,
            EnergyOptimizationStrategy::PowerGating,
        ];

        for strategy in &strategies {
            let prev_strategy = self.current_strategy;
            self.current_strategy = *strategy;

            let result = match strategy {
                EnergyOptimizationStrategy::SparseComputation => {
                    self.apply_sparse_computation_optimization(workload, None::<&Array2<T>>)?
                }
                EnergyOptimizationStrategy::DynamicVoltageScaling => {
                    self.apply_dvfs_optimization(workload)?
                }
                EnergyOptimizationStrategy::PowerGating => {
                    self.apply_power_gating_optimization(workload)?
                }
                _ => continue,
            };

            // Accumulate results
            total_result.energy_saved = total_result.energy_saved + result.energy_saved;
            total_result.power_reduction = total_result.power_reduction + result.power_reduction;
            total_result.performance_impact =
                total_result.performance_impact + result.performance_impact;
            total_result.thermal_impact = total_result.thermal_impact + result.thermal_impact;
            total_result.optimization_overhead =
                total_result.optimization_overhead + result.optimization_overhead;

            self.current_strategy = prev_strategy;
        }

        Ok(total_result)
    }

    /// Apply default optimization
    fn apply_default_optimization(
        &mut self,
        _workload: &WorkloadSample<T>,
    ) -> Result<EnergyOptimizationResult<T>> {
        // Minimal optimization - just monitoring
        Ok(EnergyOptimizationResult {
            strategy_used: self.current_strategy,
            energy_saved: T::zero(),
            power_reduction: T::zero(),
            performance_impact: T::zero(),
            thermal_impact: T::zero(),
            optimization_overhead: to_t_or(0.01, T::zero()),
        })
    }

    /// Apply clock gating optimization. The fraction of dynamic power
    /// recoverable is the workload's idle fraction times the gating
    /// circuit's own efficiency (it cannot recover 100% due to gating
    /// overhead) — derived from the workload, not a fixed percentage.
    fn apply_clock_gating_optimization(
        &mut self,
        workload: &WorkloadSample<T>,
    ) -> Result<EnergyOptimizationResult<T>> {
        let initial_power = self.estimate_workload_power(workload);
        let idle_fraction = self.idle_fraction(workload);
        let reduction_factor = idle_fraction * to_t_or(CLOCK_GATING_EFFICIENCY, T::zero());
        let new_power = initial_power * (T::one() - reduction_factor);

        self.system_state.current_power = new_power;

        Ok(EnergyOptimizationResult {
            strategy_used: EnergyOptimizationStrategy::ClockGating,
            energy_saved: initial_power * reduction_factor,
            power_reduction: initial_power - new_power,
            performance_impact: T::zero(), // Gated clocks resume with no latency
            thermal_impact: (initial_power - new_power) * to_t_or(0.8, T::zero()),
            optimization_overhead: to_t_or(0.05, T::zero()),
        })
    }

    /// Apply sleep mode optimization. Sleep depth (light vs. deep) and the
    /// resulting savings scale with the workload's idle fraction, rather
    /// than a fixed 50% constant.
    fn apply_sleep_mode_optimization(
        &mut self,
        workload: &WorkloadSample<T>,
    ) -> Result<EnergyOptimizationResult<T>> {
        let initial_power = self.estimate_workload_power(workload);
        let idle_fraction = self.idle_fraction(workload);

        let deep_sleep_threshold = to_t_or(DEEP_SLEEP_IDLE_THRESHOLD, T::one());
        let (status, base_savings, wakeup_latency) = if idle_fraction >= deep_sleep_threshold {
            (SleepStatus::DeepSleep, DEEP_SLEEP_SAVINGS, 0.2)
        } else {
            (SleepStatus::LightSleep, LIGHT_SLEEP_SAVINGS, 0.1)
        };
        self.system_state.sleep_status = status;

        let reduction_factor = idle_fraction * to_t_or(base_savings, T::zero());
        let new_power = initial_power * (T::one() - reduction_factor);
        self.system_state.current_power = new_power;

        Ok(EnergyOptimizationResult {
            strategy_used: EnergyOptimizationStrategy::SleepModeOptimization,
            energy_saved: initial_power * reduction_factor,
            power_reduction: initial_power - new_power,
            performance_impact: to_t_or(wakeup_latency, T::zero()),
            thermal_impact: (initial_power - new_power) * to_t_or(0.95, T::zero()),
            optimization_overhead: to_t_or(0.1, T::zero()),
        })
    }

    /// Apply thermal-aware optimization: a proportional controller that
    /// scales power reduction linearly with how far the (RC-modeled)
    /// temperature has overshot a safe operating range, rather than a
    /// hardcoded two-step reduction factor.
    fn apply_thermal_aware_optimization(
        &mut self,
        workload: &WorkloadSample<T>,
    ) -> Result<EnergyOptimizationResult<T>> {
        let initial_power = self.estimate_workload_power(workload);

        let safe_temp = to_t_or(THERMAL_SAFE_TEMP_C, T::zero());
        let critical_temp = to_t_or(THERMAL_CRITICAL_TEMP_C, T::one());
        let min_reduction = to_t_or(THERMAL_MIN_REDUCTION, T::zero());
        let max_reduction = to_t_or(THERMAL_MAX_REDUCTION, T::zero());

        let span = (critical_temp - safe_temp).max(to_t_or(1e-6, T::one()));
        let overshoot = ((self.system_state.temperature - safe_temp) / span)
            .max(T::zero())
            .min(T::one());
        let reduction_factor = min_reduction + (max_reduction - min_reduction) * overshoot;

        let new_power = initial_power * (T::one() - reduction_factor);
        self.system_state.current_power = new_power;

        Ok(EnergyOptimizationResult {
            strategy_used: EnergyOptimizationStrategy::ThermalAwareOptimization,
            energy_saved: initial_power * reduction_factor,
            power_reduction: initial_power - new_power,
            performance_impact: reduction_factor * to_t_or(0.5, T::zero()),
            thermal_impact: initial_power - new_power,
            optimization_overhead: to_t_or(0.15, T::zero()),
        })
    }

    /// Ratio of new to old power (`P_new / P_old`) under a simplified CMOS
    /// dynamic power model `P ∝ V²·f`. Equals 1.0 only when voltage and
    /// frequency are genuinely unchanged; any real DVFS transition yields a
    /// ratio strictly different from 1.0 (F17).
    fn calculate_power_reduction(&self, v_old: T, f_old: T, v_new: T, f_new: T) -> T {
        let denom = v_old * v_old * f_old;
        if denom <= T::zero() {
            return T::one();
        }
        (v_new * v_new * f_new) / denom
    }

    /// Calculate performance impact of a frequency change:
    /// `(old_freq - new_freq) / old_freq`.
    fn calculate_performance_impact(&self, old_frequency: T, new_frequency: T) -> T {
        if old_frequency <= T::zero() {
            return T::zero();
        }
        (old_frequency - new_frequency) / old_frequency
    }

    /// Calculate thermal impact (°C-equivalent reduction) of a power
    /// change, via the thermal model's resistance: `ΔP · R_thermal`.
    fn calculate_thermal_impact(&self, old_power: T, newpower: T) -> T {
        let power_reduction = old_power - newpower;
        power_reduction * self.thermal_manager.thermal_model.thermal_resistance
    }

    /// Evaluate strategy effectiveness
    fn evaluate_strategy_effectiveness(&mut self, result: &EnergyOptimizationResult<T>) {
        // Calculate effectiveness score
        let effectiveness =
            result.energy_saved / (result.optimization_overhead + to_t_or(1e-6, T::zero()));

        // Update strategy effectiveness history
        *self
            .strategy_effectiveness
            .entry(result.strategy_used)
            .or_insert(T::zero()) = effectiveness;
    }

    /// Consider switching optimization strategy
    fn consider_strategy_switch(&mut self) -> Result<()> {
        if let Some(&current_effectiveness) =
            self.strategy_effectiveness.get(&self.current_strategy)
        {
            // Find best alternative strategy
            if let Some((&best_strategy, &best_effectiveness)) = self
                .strategy_effectiveness
                .iter()
                .max_by(|a, b| a.1.partial_cmp(b.1).unwrap_or(std::cmp::Ordering::Equal))
            {
                // Switch if improvement exceeds threshold (guarded against
                // division by a zero/negative baseline effectiveness).
                if current_effectiveness > T::zero() {
                    let improvement =
                        (best_effectiveness - current_effectiveness) / current_effectiveness;
                    if improvement > self.config.strategy_switching_threshold {
                        self.current_strategy = best_strategy;
                    }
                } else if best_effectiveness > T::zero() {
                    self.current_strategy = best_strategy;
                }
            }
        }

        Ok(())
    }

    /// Update optimization metrics
    fn update_metrics(&mut self, _result: &EnergyOptimizationResult<T>) {
        self.metrics.energy_consumption = self.system_state.current_energy;
        self.metrics.power_consumption = self.system_state.current_power;
        let ambient = to_t_or(25.0, T::one());
        self.metrics.thermal_efficiency = if self.system_state.temperature > T::zero() {
            ambient / self.system_state.temperature
        } else {
            T::one()
        };
    }

    /// Get current energy budget status
    pub fn get_energy_budget_status(&self) -> EnergyBudgetStatus<T> {
        let remaining_budget =
            self.config.energy_budget.total_budget - self.system_state.current_energy;
        let budget_utilization =
            self.system_state.current_energy / self.config.energy_budget.total_budget;

        EnergyBudgetStatus {
            total_budget: self.config.energy_budget.total_budget,
            current_consumption: self.system_state.current_energy,
            remaining_budget,
            budget_utilization,
            emergency_reserve_available: remaining_budget
                > self.config.energy_budget.emergency_reserves,
        }
    }

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

    /// Get current system state
    /// Number of power domains currently power-gated.
    ///
    /// The gating decision is computed per optimization step from the
    /// workload's idle fraction; before this accessor existed the result was
    /// recorded and never read, so callers had no way to see whether power
    /// gating had actually engaged.
    pub fn gated_domain_count(&self) -> usize {
        self.power_gating_controller
            .gated_groups
            .values()
            .filter(|group| group.is_gated)
            .count()
    }

    pub fn get_system_state(&self) -> &EnergySystemState<T> {
        &self.system_state
    }
}

/// Energy optimization result
#[derive(Debug, Clone)]
pub struct EnergyOptimizationResult<T: Float + Debug + Send + Sync + 'static> {
    /// Strategy that was used
    pub strategy_used: EnergyOptimizationStrategy,

    /// Energy saved (nJ)
    pub energy_saved: T,

    /// Power reduction (nW)
    pub power_reduction: T,

    /// Performance impact (ratio)
    pub performance_impact: T,

    /// Thermal impact (°C reduction)
    pub thermal_impact: T,

    /// Optimization overhead (nJ)
    pub optimization_overhead: T,
}

/// Energy budget status
#[derive(Debug, Clone)]
pub struct EnergyBudgetStatus<T: Float + Debug + Send + Sync + 'static> {
    /// Total energy budget (nJ)
    pub total_budget: T,

    /// Current energy consumption (nJ)
    pub current_consumption: T,

    /// Remaining budget (nJ)
    pub remaining_budget: T,

    /// Budget utilization (0.0 to 1.0)
    pub budget_utilization: T,

    /// Emergency reserve available
    pub emergency_reserve_available: bool,
}

impl<
        T: Float
            + Debug
            + Send
            + Sync
            + scirs2_core::ndarray::ScalarOperand
            + std::fmt::Debug
            + std::iter::Sum,
    > EnergyMonitor<T>
{
    fn new(_monitoringfrequency: Duration) -> Self {
        Self {
            consumption_history: VecDeque::new(),
            power_history: VecDeque::new(),
            current_power: T::zero(),
            peak_power: T::zero(),
            average_power: T::zero(),
            last_update: Instant::now(),
            window_size: Duration::from_secs(1),
        }
    }

    fn update(&mut self, systemstate: &EnergySystemState<T>) -> Result<()> {
        let now = Instant::now();
        self.consumption_history
            .push_back((now, systemstate.current_energy));
        self.power_history
            .push_back((now, systemstate.current_power));

        // Clean old entries out of both histories (F59: `power_history` was
        // previously never trimmed and grew without bound).
        while let Some(&(time_, _)) = self.consumption_history.front() {
            if now.duration_since(time_) > self.window_size {
                self.consumption_history.pop_front();
            } else {
                break;
            }
        }
        while let Some(&(time_, _)) = self.power_history.front() {
            if now.duration_since(time_) > self.window_size {
                self.power_history.pop_front();
            } else {
                break;
            }
        }

        // Update current metrics
        self.current_power = systemstate.current_power;
        self.peak_power = self.peak_power.max(systemstate.current_power);

        // Update average power
        if !self.power_history.is_empty() {
            let sum: T = self.power_history.iter().map(|(_, power)| *power).sum();
            self.average_power = sum / to_t_or(self.power_history.len() as f64, T::one());
        }

        self.last_update = now;
        Ok(())
    }
}

#[cfg(test)]
#[path = "energy_efficient_tests.rs"]
mod tests;