optirs-learned 0.3.2

OptiRS learned optimizers and meta-learning
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
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
// Few-Shot Learning Enhancement for Optimizer Meta-Learning
//
// This module implements advanced few-shot learning techniques specifically designed
// for quickly adapting optimizers to new tasks with minimal data. It includes
// prototypical networks, meta-learning approaches, and rapid adaptation mechanisms.

use scirs2_core::ndarray::{Array1, Array2};
use scirs2_core::numeric::Float;
use std::collections::{HashMap, VecDeque};
use std::fmt::Debug;
use std::time::{Duration, Instant};

use super::OptimizerState;
use crate::error::{OptimError, Result};

pub mod prototypical;

pub use prototypical::{activate, xavier_encoder_layer};

/// Few-shot learning coordinator for optimizer adaptation
pub struct FewShotLearningSystem<T: Float + Debug + Send + Sync + 'static> {
    /// Base meta-learned optimizer
    base_optimizer: Box<dyn FewShotOptimizer<T>>,

    /// Prototypical network for task representation
    prototype_network: PrototypicalNetwork<T>,

    /// Memory bank for storing task experiences
    memory_bank: EpisodicMemoryBank<T>,

    /// Fast adaptation engine
    fast_adaptation: FastAdaptationEngine<T>,

    /// Performance tracker
    performance_tracker: FewShotPerformanceTracker<T>,
}

/// Base trait for few-shot optimizers
pub trait FewShotOptimizer<T: Float + Debug + Send + Sync + 'static>: Send + Sync {
    /// Adapt to new task with few examples
    fn adapt_few_shot(
        &mut self,
        support_set: &SupportSet<T>,
        query_set: &QuerySet<T>,
        adaptation_config: &AdaptationConfig,
    ) -> Result<AdaptationResult<T>>;

    /// Get task representation
    fn get_task_representation(&self, taskdata: &TaskData<T>) -> Result<Array1<T>>;

    /// Compute adaptation loss
    fn compute_adaptation_loss(
        &self,
        support_set: &SupportSet<T>,
        query_set: &QuerySet<T>,
    ) -> Result<T>;

    /// Update meta-parameters
    fn update_meta_parameters(&mut self, metagradients: &MetaGradients<T>) -> Result<()>;

    /// Get current state for transfer
    fn get_transfer_state(&self) -> TransferState<T>;

    /// Load transfer state
    fn load_transfer_state(&mut self, state: TransferState<T>) -> Result<()>;
}

/// Support set for few-shot learning
#[derive(Debug, Clone)]
pub struct SupportSet<T: Float + Debug + Send + Sync + 'static> {
    /// Support examples
    pub examples: Vec<SupportExample<T>>,

    /// Task metadata
    pub task_metadata: TaskMetadata,

    /// Support _set statistics
    pub statistics: SupportSetStatistics<T>,

    /// Temporal ordering (if applicable)
    pub temporal_order: Option<Vec<usize>>,
}

/// Individual support example
#[derive(Debug, Clone)]
pub struct SupportExample<T: Float + Debug + Send + Sync + 'static> {
    /// Input features
    pub features: Array1<T>,

    /// Target output
    pub target: T,

    /// Example weight/importance
    pub weight: T,

    /// Context information
    pub context: HashMap<String, T>,

    /// Example metadata
    pub metadata: ExampleMetadata,
}

/// Query set for evaluation
#[derive(Debug, Clone)]
pub struct QuerySet<T: Float + Debug + Send + Sync + 'static> {
    /// Query examples
    pub examples: Vec<QueryExample<T>>,

    /// Query statistics
    pub statistics: QuerySetStatistics<T>,

    /// Evaluation metrics
    pub eval_metrics: Vec<EvaluationMetric>,
}

/// Individual query example
#[derive(Debug, Clone)]
pub struct QueryExample<T: Float + Debug + Send + Sync + 'static> {
    /// Input features
    pub features: Array1<T>,

    /// True target (for evaluation)
    pub true_target: Option<T>,

    /// Query weight
    pub weight: T,

    /// Query context
    pub context: HashMap<String, T>,
}

/// Task data container
#[derive(Debug, Clone)]
pub struct TaskData<T: Float + Debug + Send + Sync + 'static> {
    /// Task identifier
    pub task_id: String,

    /// Support set
    pub support_set: SupportSet<T>,

    /// Query set
    pub query_set: QuerySet<T>,

    /// Task-specific parameters
    pub task_params: HashMap<String, T>,

    /// Task domain information
    pub domain_info: DomainInfo,
}

/// Domain information
#[derive(Debug, Clone)]
pub struct DomainInfo {
    /// Domain type
    pub domain_type: DomainType,

    /// Domain characteristics
    pub characteristics: DomainCharacteristics,

    /// Expected difficulty
    pub difficulty_level: DifficultyLevel,

    /// Domain-specific constraints
    pub constraints: Vec<DomainConstraint>,
}

/// Domain types
#[derive(Debug, Clone, Copy)]
pub enum DomainType {
    ComputerVision,
    NaturalLanguageProcessing,
    ReinforcementLearning,
    TimeSeriesForecasting,
    ScientificComputing,
    Optimization,
    ControlSystems,
    GamePlaying,
    Robotics,
    Healthcare,
}

/// Domain characteristics
#[derive(Debug, Clone)]
pub struct DomainCharacteristics {
    /// Input dimensionality
    pub input_dim: usize,

    /// Output dimensionality
    pub output_dim: usize,

    /// Temporal dependencies
    pub temporal: bool,

    /// Stochasticity level
    pub stochasticity: f64,

    /// Noise level
    pub noise_level: f64,

    /// Data sparsity
    pub sparsity: f64,
}

/// Difficulty levels
#[derive(Debug, Clone, Copy)]
pub enum DifficultyLevel {
    Trivial,
    Easy,
    Medium,
    Hard,
    Expert,
    Extreme,
}

/// Domain constraints
#[derive(Debug, Clone)]
pub struct DomainConstraint {
    /// Constraint type
    pub constraint_type: ConstraintType,

    /// Constraint description
    pub description: String,

    /// Enforcement level
    pub enforcement: ConstraintEnforcement,
}

/// Constraint types
#[derive(Debug, Clone, Copy)]
pub enum ConstraintType {
    ResourceLimit,
    TemporalConstraint,
    AccuracyRequirement,
    LatencyRequirement,
    MemoryConstraint,
    EnergyConstraint,
    SafetyConstraint,
}

/// Constraint enforcement levels
#[derive(Debug, Clone, Copy)]
pub enum ConstraintEnforcement {
    Hard,
    Soft,
    Advisory,
}

/// Adaptation configuration
#[derive(Debug, Clone)]
pub struct AdaptationConfig {
    /// Number of adaptation steps
    pub adaptation_steps: usize,

    /// Learning rate for adaptation
    pub adaptation_lr: f64,

    /// Adaptation strategy
    pub strategy: AdaptationStrategyType,

    /// Early stopping configuration
    pub early_stopping: Option<EarlyStoppingConfig>,

    /// Regularization parameters
    pub regularization: RegularizationConfig,

    /// Resource constraints
    pub resource_constraints: ResourceConstraints,
}

/// Adaptation strategy types
#[derive(Debug, Clone, Copy)]
pub enum AdaptationStrategyType {
    /// Model-Agnostic Meta-Learning (MAML)
    MAML,

    /// First-Order MAML (FOMAML)
    FOMAML,

    /// Prototypical Networks
    Prototypical,

    /// Matching Networks
    Matching,

    /// Relation Networks
    Relation,

    /// Meta-SGD
    MetaSGD,

    /// Learned optimizer approach
    LearnedOptimizer,

    /// Gradient-based meta-learning
    GradientBased,

    /// Memory-augmented networks
    MemoryAugmented,
}

/// Early stopping configuration
#[derive(Debug, Clone)]
pub struct EarlyStoppingConfig {
    /// Patience (steps without improvement)
    pub patience: usize,

    /// Minimum improvement threshold
    pub min_improvement: f64,

    /// Validation frequency
    pub validation_frequency: usize,
}

/// Regularization configuration
#[derive(Debug, Clone)]
pub struct RegularizationConfig {
    /// L2 regularization strength
    pub l2_strength: f64,

    /// Dropout rate
    pub dropout_rate: f64,

    /// Gradient clipping threshold
    pub gradient_clip: Option<f64>,

    /// Task-specific regularization
    pub task_regularization: HashMap<String, f64>,
}

/// Resource constraints for adaptation
#[derive(Debug, Clone)]
pub struct ResourceConstraints {
    /// Maximum adaptation time
    pub max_time: Duration,

    /// Maximum memory usage (MB)
    pub max_memory_mb: usize,

    /// Maximum computational budget
    pub max_compute_budget: f64,
}

/// Adaptation result
#[derive(Debug, Clone)]
pub struct AdaptationResult<T: Float + Debug + Send + Sync + 'static> {
    /// Adapted optimizer state
    pub adapted_state: OptimizerState<T>,

    /// Adaptation performance
    pub performance: AdaptationPerformance<T>,

    /// Task representation learned
    pub task_representation: Array1<T>,

    /// Adaptation trajectory
    pub adaptation_trajectory: Vec<AdaptationStep<T>>,

    /// Resource usage
    pub resource_usage: ResourceUsage<T>,
}

/// Adaptation performance metrics
#[derive(Debug, Clone)]
pub struct AdaptationPerformance<T: Float + Debug + Send + Sync + 'static> {
    /// Query set performance
    pub query_performance: T,

    /// Support set performance
    pub support_performance: T,

    /// Adaptation speed (steps to convergence)
    pub adaptation_speed: usize,

    /// Final loss
    pub final_loss: T,

    /// Performance improvement
    pub improvement: T,

    /// Stability measure
    pub stability: T,
}

/// Individual adaptation step
#[derive(Debug, Clone)]
pub struct AdaptationStep<T: Float + Debug + Send + Sync + 'static> {
    /// Step number
    pub step: usize,

    /// Loss at this step
    pub loss: T,

    /// Performance at this step
    pub performance: T,

    /// Gradient norm
    pub gradient_norm: T,

    /// Step time
    pub step_time: Duration,
}

/// Resource usage tracking
#[derive(Debug, Clone)]
pub struct ResourceUsage<T: Float + Debug + Send + Sync + 'static> {
    /// Total time taken
    pub total_time: Duration,

    /// Peak memory usage (MB)
    pub peak_memory_mb: T,

    /// Computational cost
    pub compute_cost: T,

    /// Energy consumption
    pub energy_consumption: T,
}

/// Meta-gradients for updating meta-parameters
#[derive(Debug, Clone)]
pub struct MetaGradients<T: Float + Debug + Send + Sync + 'static> {
    /// Parameter gradients
    pub param_gradients: HashMap<String, Array1<T>>,

    /// Learning rate gradients
    pub lr_gradients: HashMap<String, T>,

    /// Architecture gradients
    pub arch_gradients: HashMap<String, Array1<T>>,

    /// Meta-gradient norm
    pub gradient_norm: T,
}

/// Transfer state for cross-task transfer
#[derive(Debug, Clone)]
pub struct TransferState<T: Float + Debug + Send + Sync + 'static> {
    /// Learned representations
    pub representations: HashMap<String, Array1<T>>,

    /// Meta-parameters
    pub meta_parameters: HashMap<String, Array1<T>>,

    /// Task embeddings
    pub task_embeddings: Array2<T>,

    /// Transfer statistics
    pub transfer_stats: TransferStatistics<T>,
}

/// Transfer statistics
#[derive(Debug, Clone)]
pub struct TransferStatistics<T: Float + Debug + Send + Sync + 'static> {
    /// Source task performance
    pub source_performance: T,

    /// Target task performance
    pub target_performance: T,

    /// Transfer efficiency
    pub transfer_efficiency: T,

    /// Adaptation steps saved
    pub steps_saved: usize,
}

/// Prototypical network for task representation
pub struct PrototypicalNetwork<T: Float + Debug + Send + Sync + 'static> {
    /// Encoder network. Visible to the `prototypical` child module, which owns
    /// the encoder's initialization and forward pass.
    pub(super) encoder: EncoderNetwork<T>,

    /// Prototype storage
    prototypes: HashMap<String, Prototype<T>>,

    /// Distance metric
    distance_metric: DistanceMetric,

    /// Network parameters
    parameters: PrototypicalNetworkParams<T>,
}

/// Encoder network for feature extraction
#[derive(Debug)]
pub struct EncoderNetwork<T: Float + Debug + Send + Sync + 'static> {
    /// Network layers
    layers: Vec<EncoderLayer<T>>,

    /// Activation function
    activation: ActivationFunction,
}

/// Individual encoder layer
#[derive(Debug)]
pub struct EncoderLayer<T: Float + Debug + Send + Sync + 'static> {
    /// Weight matrix
    pub weights: Array2<T>,

    /// Bias vector
    pub bias: Array1<T>,

    /// Layer type
    pub layer_type: LayerType,
}

/// Layer types
#[derive(Debug, Clone, Copy)]
pub enum LayerType {
    Linear,
    Convolutional,
    Recurrent,
    Attention,
    Residual,
}

/// Activation functions
#[derive(Debug, Clone, Copy)]
pub enum ActivationFunction {
    ReLU,
    Tanh,
    Sigmoid,
    Swish,
    GELU,
    Mish,
}

/// Task prototypes
#[derive(Debug, Clone)]
pub struct Prototype<T: Float + Debug + Send + Sync + 'static> {
    /// Prototype vector
    pub vector: Array1<T>,

    /// Prototype confidence
    pub confidence: T,

    /// Number of examples used
    pub example_count: usize,

    /// Last update time
    pub last_updated: std::time::SystemTime,

    /// Prototype metadata
    pub metadata: PrototypeMetadata,
}

/// Prototype metadata
#[derive(Debug, Clone)]
pub struct PrototypeMetadata {
    /// Task category
    pub task_category: String,

    /// Domain type
    pub domain: DomainType,

    /// Creation timestamp
    pub created_at: std::time::SystemTime,

    /// Update count
    pub update_count: usize,
}

/// Distance metrics for prototype comparison
#[derive(Debug, Clone, Copy)]
pub enum DistanceMetric {
    Euclidean,
    Cosine,
    Manhattan,
    Mahalanobis,
    Learned,
}

/// Prototypical network parameters
#[derive(Debug, Clone)]
pub struct PrototypicalNetworkParams<T: Float + Debug + Send + Sync + 'static> {
    /// Embedding dimension
    pub embedding_dim: usize,

    /// Learning rate
    pub learning_rate: T,

    /// Temperature parameter
    pub temperature: T,

    /// Prototype update rate
    pub prototype_update_rate: T,
}

/// Support set manager.
///
/// Currently a validated holder for [`SupportSetManagerConfig`]: the support-set
/// store and selection strategy it declared were never written to or consulted
/// by anything, so they have been removed rather than left as write-only state.
pub struct SupportSetManager<T: Float + Debug + Send + Sync + 'static> {
    /// Manager configuration
    config: SupportSetManagerConfig,

    _element: std::marker::PhantomData<T>,
}

/// Support set manager configuration
#[derive(Debug, Clone)]
pub struct SupportSetManagerConfig {
    /// Minimum support set size
    pub min_support_size: usize,

    /// Maximum support set size
    pub max_support_size: usize,

    /// Quality threshold
    pub quality_threshold: f64,

    /// Enable augmentation
    pub enable_augmentation: bool,

    /// Cache support sets
    pub cache_support_sets: bool,
}

/// Adaptation strategy trait
pub trait AdaptationStrategy<T: Float + Debug + Send + Sync + 'static>: Send + Sync {
    /// Perform adaptation
    fn adapt(
        &mut self,
        optimizer: &mut dyn FewShotOptimizer<T>,
        task_data: &TaskData<T>,
        config: &AdaptationConfig,
    ) -> Result<AdaptationResult<T>>;

    /// Get strategy name
    fn name(&self) -> &str;

    /// Get strategy parameters
    fn parameters(&self) -> HashMap<String, f64>;

    /// Update strategy parameters
    fn update_parameters(&mut self, params: HashMap<String, f64>) -> Result<()>;
}

/// Task similarity calculator
pub struct TaskSimilarityCalculator<T: Float + Debug + Send + Sync + 'static> {
    /// Similarity cache
    similarity_cache: HashMap<(String, String), T>,

    /// Calculator configuration
    config: SimilarityCalculatorConfig<T>,
}

/// Similarity metric trait
pub trait SimilarityMetric<T: Float + Debug + Send + Sync + 'static>: Send + Sync {
    /// Calculate similarity between tasks
    fn calculate_similarity(&self, task1: &TaskData<T>, task2: &TaskData<T>) -> Result<T>;

    /// Get metric name
    fn name(&self) -> &str;

    /// Get metric weight
    fn weight(&self) -> T;
}

/// Similarity calculator configuration
#[derive(Debug, Clone)]
pub struct SimilarityCalculatorConfig<T: Float + Debug + Send + Sync + 'static> {
    /// Enable caching
    pub enable_caching: bool,

    /// Cache size limit
    pub cache_size_limit: usize,

    /// Similarity threshold
    pub similarity_threshold: T,

    /// Use task metadata
    pub use_metadata: bool,
}

/// Episodic memory bank for storing task experiences
pub struct EpisodicMemoryBank<T: Float + Debug + Send + Sync + 'static> {
    /// Memory episodes
    episodes: VecDeque<MemoryEpisode<T>>,

    /// Memory configuration
    config: MemoryBankConfig<T>,

    /// Usage statistics
    usage_stats: MemoryUsageStats,
}

/// Memory episode
#[derive(Debug, Clone)]
pub struct MemoryEpisode<T: Float + Debug + Send + Sync + 'static> {
    /// Episode ID
    pub episode_id: String,

    /// Task data
    pub task_data: TaskData<T>,

    /// Adaptation result
    pub adaptation_result: AdaptationResult<T>,

    /// Episode timestamp
    pub timestamp: std::time::SystemTime,

    /// Episode metadata
    pub metadata: EpisodeMetadata,

    /// Access count
    pub access_count: usize,
}

/// Episode metadata
#[derive(Debug, Clone)]
pub struct EpisodeMetadata {
    /// Task difficulty
    pub difficulty: DifficultyLevel,

    /// Domain type
    pub domain: DomainType,

    /// Success rate
    pub success_rate: f64,

    /// Tags
    pub tags: Vec<String>,
}

/// Memory bank configuration
#[derive(Debug, Clone)]
pub struct MemoryBankConfig<T: Float + Debug + Send + Sync + 'static> {
    /// Maximum memory size
    pub max_memory_size: usize,

    /// Eviction policy
    pub eviction_policy: EvictionPolicy,

    /// Similarity threshold for retrieval
    pub similarity_threshold: T,

    /// Enable compression
    pub enable_compression: bool,
}

/// Memory eviction policies
#[derive(Debug, Clone, Copy)]
pub enum EvictionPolicy {
    LRU,         // Least Recently Used
    LFU,         // Least Frequently Used
    Performance, // Worst Performing
    Age,         // Oldest First
    Random,
}

/// Memory bank statistics (summary view)
#[derive(Debug, Clone)]
pub struct MemoryBankStats<T: Float + Debug + Send + Sync + 'static> {
    /// Number of stored episodes
    pub count: usize,

    /// Average performance across episodes
    pub avg_performance: T,

    /// Capacity used as a fraction
    pub capacity_used: f64,

    /// Total capacity
    pub total_capacity: usize,
}

/// Memory usage statistics
#[derive(Debug, Clone)]
pub struct MemoryUsageStats {
    /// Total episodes stored
    pub total_episodes: usize,

    /// Memory utilization
    pub memory_utilization: f64,

    /// Hit rate
    pub hit_rate: f64,

    /// Average retrieval time
    pub avg_retrieval_time: Duration,
}

/// Fast adaptation engine
pub struct FastAdaptationEngine<T: Float + Debug + Send + Sync + 'static> {
    /// Adaptation algorithms
    algorithms: Vec<Box<dyn FastAdaptationAlgorithm<T>>>,

    /// Engine configuration
    config: FastAdaptationConfig,
}

/// Fast adaptation algorithm trait
pub trait FastAdaptationAlgorithm<T: Float + Debug + Send + Sync + 'static>: Send + Sync {
    /// Perform fast adaptation
    fn adapt_fast(
        &mut self,
        optimizer: &mut dyn FewShotOptimizer<T>,
        task_data: &TaskData<T>,
        target_performance: Option<T>,
    ) -> Result<AdaptationResult<T>>;

    /// Estimate adaptation time
    fn estimate_adaptation_time(&self, taskdata: &TaskData<T>) -> Duration;

    /// Get algorithm name
    fn name(&self) -> &str;
}

/// Fast adaptation configuration
#[derive(Debug, Clone)]
pub struct FastAdaptationConfig {
    /// Enable caching
    pub enable_caching: bool,

    /// Enable prediction
    pub enable_prediction: bool,

    /// Maximum adaptation time
    pub max_adaptation_time: Duration,

    /// Performance threshold
    pub _performance_threshold: f64,
}

/// Performance tracker for few-shot learning
pub struct FewShotPerformanceTracker<T: Float + Debug + Send + Sync + 'static> {
    /// Performance history
    performance_history: VecDeque<PerformanceRecord<T>>,

    /// Tracking configuration
    config: TrackingConfig,

    /// Performance statistics
    stats: PerformanceStats<T>,
}

/// Performance record
#[derive(Debug, Clone)]
pub struct PerformanceRecord<T: Float + Debug + Send + Sync + 'static> {
    /// Task ID
    pub task_id: String,

    /// Performance value
    pub performance: T,

    /// Adaptation time
    pub adaptation_time: Duration,

    /// Strategy used
    pub strategy_used: String,

    /// Timestamp
    pub timestamp: std::time::SystemTime,

    /// Additional metrics
    pub additional_metrics: HashMap<String, T>,
}

/// Performance metric trait
pub trait PerformanceMetric<T: Float + Debug + Send + Sync + 'static>: Send + Sync {
    /// Calculate performance metric
    fn calculate(&self, records: &[PerformanceRecord<T>]) -> Result<T>;

    /// Get metric name
    fn name(&self) -> &str;

    /// Is higher better
    fn higher_is_better(&self) -> bool;
}

/// Tracking configuration
#[derive(Debug, Clone)]
pub struct TrackingConfig {
    /// Maximum history size
    pub max_history_size: usize,

    /// Update frequency
    pub update_frequency: Duration,

    /// Enable detailed tracking
    pub detailed_tracking: bool,

    /// Export results
    pub export_results: bool,
}

/// Performance statistics
#[derive(Debug)]
pub struct PerformanceStats<T: Float + Debug + Send + Sync + 'static> {
    /// Best performance
    pub best_performance: T,

    /// Average performance
    pub average_performance: T,

    /// Performance variance
    pub performance_variance: T,

    /// Improvement rate
    pub improvement_rate: T,

    /// Success rate
    pub success_rate: T,
}

// Implementation stubs for key structures
impl<T: Float + Debug + Send + Sync + 'static> FewShotLearningSystem<T> {
    /// Create new few-shot learning system
    pub fn new(
        base_optimizer: Box<dyn FewShotOptimizer<T>>,
        config: FewShotConfig<T>,
    ) -> Result<Self> {
        Ok(Self {
            base_optimizer,
            prototype_network: PrototypicalNetwork::new(config.prototype_config)?,
            memory_bank: EpisodicMemoryBank::new(config.memory_config)?,
            fast_adaptation: FastAdaptationEngine::new(config.adaptation_config)?,
            performance_tracker: FewShotPerformanceTracker::new(config.tracking_config)?,
        })
    }

    /// Learn from few examples
    pub fn learn_few_shot(
        &mut self,
        task_data: TaskData<T>,
        adaptation_config: AdaptationConfig,
    ) -> Result<AdaptationResult<T>> {
        // Comprehensive few-shot learning implementation
        let _start_time = Instant::now();

        // 1. Extract task representation using prototypical network
        let task_representation = self.prototype_network.encode_task(&task_data)?;

        // 2. Retrieve similar tasks from memory
        let similar_tasks = self.memory_bank.retrieve_similar(&task_data, 5)?;

        // 3. Select best adaptation strategy based on task characteristics
        let strategy = self.select_adaptation_strategy(&task_data, &similar_tasks)?;

        // 4. Perform fast adaptation
        let mut adaptation_result = self.fast_adaptation.adapt_fast(
            &mut *self.base_optimizer,
            &task_data,
            strategy,
            &adaptation_config,
        )?;

        // 5. Update task representation
        adaptation_result.task_representation = task_representation;

        // 6. Store experience in memory bank
        self.memory_bank
            .store_episode(task_data.clone(), adaptation_result.clone())?;

        // 7. Update performance tracker
        self.performance_tracker
            .record_performance(&adaptation_result)?;

        // 8. Update prototypical network with new experience
        self.prototype_network
            .update_prototypes(&task_data, &adaptation_result)?;

        Ok(adaptation_result)
    }

    fn select_adaptation_strategy(
        &self,
        task_data: &TaskData<T>,
        _similar_tasks: &[MemoryEpisode<T>],
    ) -> Result<AdaptationStrategyType> {
        // Strategy selection based on task characteristics and historical performance
        match task_data.domain_info.difficulty_level {
            DifficultyLevel::Trivial | DifficultyLevel::Easy => Ok(AdaptationStrategyType::FOMAML),
            DifficultyLevel::Medium => Ok(AdaptationStrategyType::MAML),
            DifficultyLevel::Hard | DifficultyLevel::Expert => {
                Ok(AdaptationStrategyType::Prototypical)
            }
            DifficultyLevel::Extreme => Ok(AdaptationStrategyType::MemoryAugmented),
        }
    }
}

/// Few-shot learning system configuration
#[derive(Debug, Clone)]
pub struct FewShotConfig<T: Float + Debug + Send + Sync + 'static> {
    /// Prototypical network configuration
    pub prototype_config: PrototypicalNetworkConfig<T>,

    /// Support set management configuration
    pub support_set_config: SupportSetManagerConfig,

    /// Similarity calculation configuration
    pub similarity_config: SimilarityCalculatorConfig<T>,

    /// Memory bank configuration
    pub memory_config: MemoryBankConfig<T>,

    /// Fast adaptation configuration
    pub adaptation_config: FastAdaptationConfig,

    /// Performance tracking configuration
    pub tracking_config: TrackingConfig,
}

/// Prototypical network configuration
#[derive(Debug, Clone)]
pub struct PrototypicalNetworkConfig<T: Float + Debug + Send + Sync + 'static> {
    /// Embedding dimension
    pub embedding_dim: usize,

    /// Learning rate
    pub learning_rate: T,

    /// Number of encoder layers
    pub num_layers: usize,

    /// Hidden dimension
    pub hidden_dim: usize,
}

// Constructors and core methods for major components
impl<T: Float + Debug + Send + Sync + 'static> PrototypicalNetwork<T> {
    /// Create a new prototypical network from configuration
    pub fn new(config: PrototypicalNetworkConfig<T>) -> Result<Self> {
        if config.embedding_dim == 0 {
            return Err(OptimError::InvalidConfig(
                "embedding_dim must be > 0".to_string(),
            ));
        }
        // Build a single-layer encoder: input_dim -> embedding_dim.
        // Xavier-initialized, not zeros: a zero-weight encoder outputs the zero
        // vector for every input and has a zero gradient, so it can never learn.
        let input_dim = config.hidden_dim.max(config.embedding_dim);
        let layer = xavier_encoder_layer::<T>(input_dim, config.embedding_dim, LayerType::Linear)?;
        Ok(Self {
            encoder: EncoderNetwork {
                layers: vec![layer],
                activation: ActivationFunction::ReLU,
            },
            prototypes: HashMap::new(),
            distance_metric: DistanceMetric::Euclidean,
            parameters: PrototypicalNetworkParams {
                embedding_dim: config.embedding_dim,
                learning_rate: config.learning_rate,
                temperature: T::one(),
                prototype_update_rate: scirs2_core::numeric::NumCast::from(0.1)
                    .unwrap_or_else(|| T::one()),
            },
        })
    }

    /// Create from embedding dimension and number of classes (convenience)
    pub fn from_dims(embedding_dim: usize, _num_classes: usize) -> Result<Self> {
        if embedding_dim == 0 {
            return Err(OptimError::InvalidConfig(
                "embedding_dim must be > 0".to_string(),
            ));
        }
        let layer = xavier_encoder_layer::<T>(embedding_dim, embedding_dim, LayerType::Linear)?;
        Ok(Self {
            encoder: EncoderNetwork {
                layers: vec![layer],
                activation: ActivationFunction::ReLU,
            },
            prototypes: HashMap::new(),
            distance_metric: DistanceMetric::Euclidean,
            parameters: PrototypicalNetworkParams {
                embedding_dim,
                learning_rate: scirs2_core::numeric::NumCast::from(0.01)
                    .unwrap_or_else(|| T::one()),
                temperature: T::one(),
                prototype_update_rate: scirs2_core::numeric::NumCast::from(0.1)
                    .unwrap_or_else(|| T::one()),
            },
        })
    }

    /// Get the embedding dimension
    pub fn embedding_dim(&self) -> usize {
        self.parameters.embedding_dim
    }

    /// Get encoder layers (for projection)
    pub fn encoder_layers(&self) -> &[EncoderLayer<T>] {
        &self.encoder.layers
    }

    /// Get mutable access to prototypes
    pub fn prototypes_mut(&mut self) -> &mut HashMap<String, Prototype<T>> {
        &mut self.prototypes
    }

    /// Get read access to prototypes
    pub fn prototypes(&self) -> &HashMap<String, Prototype<T>> {
        &self.prototypes
    }

    /// Get the distance metric
    pub fn distance_metric(&self) -> &DistanceMetric {
        &self.distance_metric
    }

    /// Encode a task into an embedding vector.
    ///
    /// Standard prototypical-network form (Snell et al. 2017): every support
    /// example is passed through the learned encoder `f_φ` and the prototype is
    /// the **mean of the embeddings**. Previously this computed a truncated
    /// coordinate-wise mean of the *raw* features and never touched
    /// `self.encoder` at all, so the encoder was dead weight and the
    /// "embedding" was just the input.
    ///
    /// # Errors
    /// Returns `Err` when the support set is empty or the encoder rejects the
    /// feature width.
    pub fn encode_task(&self, task_data: &TaskData<T>) -> Result<Array1<T>> {
        if task_data.support_set.examples.is_empty() {
            return Err(OptimError::InsufficientData(
                "No support examples for encoding".to_string(),
            ));
        }

        let width = self.encoder.embedding_width()?;
        let mut sum = Array1::<T>::zeros(width);
        let count = task_data.support_set.examples.len();
        for ex in &task_data.support_set.examples {
            let embedded = self.encoder.forward(&ex.features)?;
            for i in 0..width {
                sum[i] = sum[i] + embedded[i];
            }
        }
        let count_t = scirs2_core::numeric::NumCast::from(count).unwrap_or_else(|| T::one());
        for slot in sum.iter_mut() {
            *slot = *slot / count_t;
        }
        Ok(sum)
    }

    /// Width of the embedding [`Self::encode_task`] produces.
    ///
    /// # Errors
    /// Returns `Err` when the encoder has no layers.
    pub fn embedding_width(&self) -> Result<usize> {
        self.encoder.embedding_width()
    }

    /// Update prototypes with new experience
    pub fn update_prototypes(
        &mut self,
        task_data: &TaskData<T>,
        _result: &AdaptationResult<T>,
    ) -> Result<()> {
        let task_repr = self.encode_task(task_data)?;
        let task_id = task_data.task_id.clone();
        let update_rate = self.parameters.prototype_update_rate;
        let one_minus = T::one() - update_rate;

        if let Some(proto) = self.prototypes.get_mut(&task_id) {
            // Exponential moving average update
            let dim = proto.vector.len().min(task_repr.len());
            for i in 0..dim {
                proto.vector[i] = one_minus * proto.vector[i] + update_rate * task_repr[i];
            }
            proto.example_count += task_data.support_set.examples.len();
            proto.last_updated = std::time::SystemTime::now();
            proto.metadata.update_count += 1;
        } else {
            let proto = Prototype {
                vector: task_repr,
                confidence: T::one(),
                example_count: task_data.support_set.examples.len(),
                last_updated: std::time::SystemTime::now(),
                metadata: PrototypeMetadata {
                    task_category: task_id.clone(),
                    domain: task_data.domain_info.domain_type,
                    created_at: std::time::SystemTime::now(),
                    update_count: 1,
                },
            };
            self.prototypes.insert(task_id, proto);
        }
        Ok(())
    }
}

impl<T: Float + Debug + Send + Sync + 'static> SupportSetManager<T> {
    /// Create a new support set manager
    pub fn new(config: SupportSetManagerConfig) -> Result<Self> {
        if config.max_support_size == 0 {
            return Err(OptimError::InvalidConfig(
                "max_support_size must be > 0".to_string(),
            ));
        }
        Ok(Self {
            config,
            _element: std::marker::PhantomData,
        })
    }

    /// Create from max support size (convenience)
    pub fn from_max_size(max_support_size: usize) -> Result<Self> {
        Self::new(SupportSetManagerConfig {
            min_support_size: 1,
            max_support_size,
            quality_threshold: 0.5,
            enable_augmentation: true,
            cache_support_sets: true,
        })
    }

    /// Get the max support size
    pub fn max_support_size(&self) -> usize {
        self.config.max_support_size
    }

    /// Get the config
    pub fn config(&self) -> &SupportSetManagerConfig {
        &self.config
    }
}

impl<T: Float + Debug + Send + Sync + 'static> TaskSimilarityCalculator<T> {
    /// Create a new task similarity calculator
    pub fn new(config: SimilarityCalculatorConfig<T>) -> Result<Self> {
        Ok(Self {
            similarity_cache: HashMap::new(),
            config,
        })
    }

    /// Create with default configuration
    pub fn default_new() -> Result<Self> {
        Self::new(SimilarityCalculatorConfig {
            enable_caching: true,
            cache_size_limit: 1000,
            similarity_threshold: scirs2_core::numeric::NumCast::from(0.5)
                .unwrap_or_else(|| T::zero()),
            use_metadata: true,
        })
    }

    /// Get mutable access to the similarity cache
    pub fn similarity_cache_mut(&mut self) -> &mut HashMap<(String, String), T> {
        &mut self.similarity_cache
    }

    /// Get whether caching is enabled
    pub fn caching_enabled(&self) -> bool {
        self.config.enable_caching
    }
}

impl<T: Float + Debug + Send + Sync + 'static> EpisodicMemoryBank<T> {
    /// Create a new episodic memory bank
    pub fn new(config: MemoryBankConfig<T>) -> Result<Self> {
        if config.max_memory_size == 0 {
            return Err(OptimError::InvalidConfig(
                "max_memory_size must be > 0".to_string(),
            ));
        }
        Ok(Self {
            episodes: VecDeque::new(),
            config,
            usage_stats: MemoryUsageStats {
                total_episodes: 0,
                memory_utilization: 0.0,
                hit_rate: 0.0,
                avg_retrieval_time: Duration::from_secs(0),
            },
        })
    }

    /// Create from capacity (convenience)
    pub fn from_capacity(capacity: usize) -> Result<Self> {
        Self::new(MemoryBankConfig {
            max_memory_size: capacity,
            eviction_policy: EvictionPolicy::Performance,
            similarity_threshold: scirs2_core::numeric::NumCast::from(0.3)
                .unwrap_or_else(|| T::zero()),
            enable_compression: false,
        })
    }

    /// Get the capacity
    pub fn capacity(&self) -> usize {
        self.config.max_memory_size
    }

    /// Get episode count
    pub fn len(&self) -> usize {
        self.episodes.len()
    }

    /// Check if empty
    pub fn is_empty(&self) -> bool {
        self.episodes.is_empty()
    }

    /// Get mutable access to episodes
    pub fn episodes_mut(&mut self) -> &mut VecDeque<MemoryEpisode<T>> {
        &mut self.episodes
    }

    /// Get read access to episodes
    pub fn episodes(&self) -> &VecDeque<MemoryEpisode<T>> {
        &self.episodes
    }

    /// Get mutable access to usage stats
    pub fn usage_stats_mut(&mut self) -> &mut MemoryUsageStats {
        &mut self.usage_stats
    }

    /// Get usage stats
    pub fn usage_stats(&self) -> &MemoryUsageStats {
        &self.usage_stats
    }

    /// Get eviction policy
    pub fn eviction_policy(&self) -> EvictionPolicy {
        self.config.eviction_policy
    }

    /// Retrieve similar episodes to a task
    pub fn retrieve_similar(
        &self,
        task_data: &TaskData<T>,
        k: usize,
    ) -> Result<Vec<MemoryEpisode<T>>> {
        if self.episodes.is_empty() {
            return Ok(Vec::new());
        }
        // Simple retrieval: return up to k most recent episodes
        // (full similarity-based retrieval is in episodic_memory_impl)
        let count = k.min(self.episodes.len());
        let result: Vec<MemoryEpisode<T>> =
            self.episodes.iter().rev().take(count).cloned().collect();
        let _ = task_data; // suppress unused warning
        Ok(result)
    }

    /// Store a new episode
    pub fn store_episode(
        &mut self,
        task_data: TaskData<T>,
        result: AdaptationResult<T>,
    ) -> Result<()> {
        let episode = MemoryEpisode {
            episode_id: format!("ep_{}", self.usage_stats.total_episodes),
            task_data,
            adaptation_result: result,
            timestamp: std::time::SystemTime::now(),
            metadata: EpisodeMetadata {
                difficulty: DifficultyLevel::Medium,
                domain: DomainType::Optimization,
                success_rate: 0.0,
                tags: Vec::new(),
            },
            access_count: 0,
        };

        if self.episodes.len() >= self.config.max_memory_size {
            self.episodes.pop_front();
        }
        self.episodes.push_back(episode);
        self.usage_stats.total_episodes += 1;
        self.usage_stats.memory_utilization =
            self.episodes.len() as f64 / self.config.max_memory_size as f64;
        Ok(())
    }
}

impl<T: Float + Debug + Send + Sync + 'static> FastAdaptationEngine<T> {
    /// Create a new fast adaptation engine
    pub fn new(config: FastAdaptationConfig) -> Result<Self> {
        Ok(Self {
            algorithms: Vec::new(),
            config,
        })
    }

    /// Register a concrete adaptation algorithm, dispatched to by
    /// [`Self::adapt_fast`] when its [`FastAdaptationAlgorithm::name`] matches
    /// the requested [`AdaptationStrategyType`]'s `{:?}` label.
    pub fn register_algorithm(&mut self, algorithm: Box<dyn FastAdaptationAlgorithm<T>>) {
        self.algorithms.push(algorithm);
    }

    /// Number of algorithms currently registered.
    pub fn algorithm_count(&self) -> usize {
        self.algorithms.len()
    }

    /// Create from inner learning rate and adaptation steps (convenience)
    pub fn from_params(inner_lr: T, adaptation_steps: usize) -> Result<Self> {
        let _ = (inner_lr, adaptation_steps);
        Self::new(FastAdaptationConfig {
            enable_caching: true,
            enable_prediction: true,
            max_adaptation_time: Duration::from_secs(60),
            _performance_threshold: 0.8,
        })
    }

    /// Get the configuration
    pub fn config(&self) -> &FastAdaptationConfig {
        &self.config
    }

    /// Perform fast adaptation.
    ///
    /// Dispatches to a registered [`FastAdaptationAlgorithm`] whose
    /// [`FastAdaptationAlgorithm::name`] matches `strategy`'s `{:?}` label
    /// (registered via [`Self::register_algorithm`]); when none matches -- the
    /// common case, since the crate ships no built-in algorithms -- falls back
    /// to `optimizer`'s own [`FewShotOptimizer::adapt_few_shot`], which every
    /// `FewShotOptimizer` implementation must provide. Either way the
    /// returned [`AdaptationResult`] reflects what actually happened, not a
    /// fixed placeholder.
    pub fn adapt_fast(
        &mut self,
        optimizer: &mut dyn FewShotOptimizer<T>,
        task_data: &TaskData<T>,
        strategy: AdaptationStrategyType,
        config: &AdaptationConfig,
    ) -> Result<AdaptationResult<T>> {
        let start = Instant::now();
        let label = format!("{strategy:?}");

        let mut result =
            if let Some(algorithm) = self.algorithms.iter_mut().find(|a| a.name() == label) {
                algorithm.adapt_fast(optimizer, task_data, None)?
            } else {
                optimizer.adapt_few_shot(&task_data.support_set, &task_data.query_set, config)?
            };

        // A delegate that did not learn an explicit task representation still
        // gets a real one from the optimizer, instead of leaving it empty.
        if result.task_representation.is_empty() {
            result.task_representation = optimizer.get_task_representation(task_data)?;
        }
        // Wall-clock time for this call (including dispatch overhead)
        // supersedes whatever -- if anything -- the delegate measured itself.
        result.resource_usage.total_time = start.elapsed();

        Ok(result)
    }
}

impl<T: Float + Debug + Send + Sync + 'static> FewShotPerformanceTracker<T> {
    /// Create a new performance tracker
    pub fn new(config: TrackingConfig) -> Result<Self> {
        Ok(Self {
            performance_history: VecDeque::new(),
            config,
            stats: PerformanceStats {
                best_performance: T::zero(),
                average_performance: T::zero(),
                performance_variance: T::zero(),
                improvement_rate: T::zero(),
                success_rate: T::zero(),
            },
        })
    }

    /// Record a performance result
    pub fn record_performance(&mut self, result: &AdaptationResult<T>) -> Result<()> {
        let record = PerformanceRecord {
            task_id: String::new(),
            performance: result.performance.query_performance,
            adaptation_time: result.resource_usage.total_time,
            strategy_used: String::new(),
            timestamp: std::time::SystemTime::now(),
            additional_metrics: HashMap::new(),
        };

        if self.performance_history.len() >= self.config.max_history_size {
            self.performance_history.pop_front();
        }
        self.performance_history.push_back(record);

        // Update stats
        if !self.performance_history.is_empty() {
            let mut sum = T::zero();
            let mut best = T::neg_infinity();
            for r in &self.performance_history {
                sum = sum + r.performance;
                if r.performance > best {
                    best = r.performance;
                }
            }
            let count_t = scirs2_core::numeric::NumCast::from(self.performance_history.len())
                .unwrap_or_else(|| T::one());
            self.stats.average_performance = sum / count_t;
            self.stats.best_performance = best;
        }
        Ok(())
    }
}

// Task metadata and example metadata
#[derive(Debug, Clone)]
pub struct TaskMetadata {
    pub task_name: String,
    pub domain: DomainType,
    pub difficulty: DifficultyLevel,
    pub created_at: std::time::SystemTime,
}

#[derive(Debug, Clone)]
pub struct ExampleMetadata {
    pub source: String,
    pub quality_score: f64,
    pub created_at: std::time::SystemTime,
}

#[derive(Debug, Clone)]
pub struct SupportSetStatistics<T: Float + Debug + Send + Sync + 'static> {
    pub mean: Array1<T>,
    pub variance: Array1<T>,
    pub size: usize,
    pub diversity_score: T,
}

#[derive(Debug, Clone)]
pub struct QuerySetStatistics<T: Float + Debug + Send + Sync + 'static> {
    pub mean: Array1<T>,
    pub variance: Array1<T>,
    pub size: usize,
}

/// Evaluation metrics for few-shot learning
#[derive(Debug, Clone, Copy)]
pub enum EvaluationMetric {
    Accuracy,
    Loss,
    F1Score,
    Precision,
    Recall,
    AUC,
    MSE,
    MAE,
    FinalPerformance,
    Efficiency,
    TrainingTime,
}

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

    #[test]
    fn test_support_set_creation() {
        let support_set = SupportSet::<f64> {
            examples: vec![SupportExample {
                features: Array1::from_vec(vec![1.0, 2.0, 3.0]),
                target: 0.5,
                weight: 1.0,
                context: HashMap::new(),
                metadata: ExampleMetadata {
                    source: "test".to_string(),
                    quality_score: 0.9,
                    created_at: std::time::SystemTime::now(),
                },
            }],
            task_metadata: TaskMetadata {
                task_name: "test_task".to_string(),
                domain: DomainType::Optimization,
                difficulty: DifficultyLevel::Easy,
                created_at: std::time::SystemTime::now(),
            },
            statistics: SupportSetStatistics {
                mean: Array1::from_vec(vec![1.0, 2.0, 3.0]),
                variance: Array1::from_vec(vec![0.1, 0.1, 0.1]),
                size: 1,
                diversity_score: 0.8,
            },
            temporal_order: None,
        };

        assert_eq!(support_set.examples.len(), 1);
        assert_eq!(support_set.statistics.size, 1);
    }

    #[test]
    fn test_adaptation_config() {
        let config = AdaptationConfig {
            adaptation_steps: 10,
            adaptation_lr: 0.01,
            strategy: AdaptationStrategyType::MAML,
            early_stopping: None,
            regularization: RegularizationConfig {
                l2_strength: 0.001,
                dropout_rate: 0.1,
                gradient_clip: Some(1.0),
                task_regularization: HashMap::new(),
            },
            resource_constraints: ResourceConstraints {
                max_time: Duration::from_secs(60),
                max_memory_mb: 1024,
                max_compute_budget: 100.0,
            },
        };

        assert_eq!(config.adaptation_steps, 10);
        assert_eq!(config.adaptation_lr, 0.01);
        assert!(matches!(config.strategy, AdaptationStrategyType::MAML));
    }

    #[test]
    fn test_domain_info() {
        let domain_info = DomainInfo {
            domain_type: DomainType::ComputerVision,
            characteristics: DomainCharacteristics {
                input_dim: 784,
                output_dim: 10,
                temporal: false,
                stochasticity: 0.1,
                noise_level: 0.05,
                sparsity: 0.0,
            },
            difficulty_level: DifficultyLevel::Medium,
            constraints: vec![DomainConstraint {
                constraint_type: ConstraintType::LatencyRequirement,
                description: "Max 100ms inference time".to_string(),
                enforcement: ConstraintEnforcement::Hard,
            }],
        };

        assert!(matches!(
            domain_info.domain_type,
            DomainType::ComputerVision
        ));
        assert_eq!(domain_info.characteristics.input_dim, 784);
        assert_eq!(domain_info.constraints.len(), 1);
    }

    /// A minimal [`FewShotOptimizer`] that records whether it was invoked and
    /// returns values distinguishable from `FastAdaptationEngine::adapt_fast`'s
    /// old fabricated constants (0.85 / 0.90 / 5 steps / 0.1 / 0.25 / 0.95), so
    /// a passing test can only mean the real delegation path ran.
    struct RecordingOptimizer {
        adapt_calls: usize,
    }

    impl FewShotOptimizer<f64> for RecordingOptimizer {
        fn adapt_few_shot(
            &mut self,
            support_set: &SupportSet<f64>,
            _query_set: &QuerySet<f64>,
            _adaptation_config: &AdaptationConfig,
        ) -> Result<AdaptationResult<f64>> {
            self.adapt_calls += 1;
            let width = support_set
                .examples
                .first()
                .map(|e| e.features.len())
                .unwrap_or(1);
            Ok(AdaptationResult {
                adapted_state: OptimizerState {
                    parameters: Array1::zeros(width),
                    gradients: Array1::zeros(width),
                    momentum: None,
                    hidden_states: HashMap::new(),
                    memory_buffers: HashMap::new(),
                    step: 1,
                    step_count: 1,
                    loss: Some(0.05),
                    learning_rate: 0.01,
                    metadata: crate::StateMetadata::default(),
                },
                performance: AdaptationPerformance {
                    query_performance: 0.42,
                    support_performance: 0.37,
                    adaptation_speed: 2,
                    final_loss: 0.05,
                    improvement: 0.11,
                    stability: 0.5,
                },
                // Deliberately left empty: `adapt_fast` must fall back to
                // `get_task_representation` rather than leaving it empty.
                task_representation: Array1::zeros(0),
                adaptation_trajectory: Vec::new(),
                resource_usage: ResourceUsage {
                    // Deliberately a marker value: `adapt_fast` must overwrite
                    // this with real wall-clock time, not pass it through.
                    total_time: Duration::from_secs(999),
                    peak_memory_mb: 1.0,
                    compute_cost: 1.0,
                    energy_consumption: 1.0,
                },
            })
        }

        fn get_task_representation(&self, _taskdata: &TaskData<f64>) -> Result<Array1<f64>> {
            Ok(Array1::from_vec(vec![7.0, 8.0, 9.0]))
        }

        fn compute_adaptation_loss(
            &self,
            _support_set: &SupportSet<f64>,
            _query_set: &QuerySet<f64>,
        ) -> Result<f64> {
            Ok(0.1)
        }

        fn update_meta_parameters(&mut self, _metagradients: &MetaGradients<f64>) -> Result<()> {
            Ok(())
        }

        fn get_transfer_state(&self) -> TransferState<f64> {
            TransferState {
                representations: HashMap::new(),
                meta_parameters: HashMap::new(),
                task_embeddings: Array2::zeros((1, 1)),
                transfer_stats: TransferStatistics {
                    source_performance: 0.0,
                    target_performance: 0.0,
                    transfer_efficiency: 0.0,
                    steps_saved: 0,
                },
            }
        }

        fn load_transfer_state(&mut self, _state: TransferState<f64>) -> Result<()> {
            Ok(())
        }
    }

    fn make_task_data() -> TaskData<f64> {
        TaskData {
            task_id: "t".to_string(),
            support_set: SupportSet {
                examples: vec![SupportExample {
                    features: Array1::from_vec(vec![1.0, 2.0, 3.0]),
                    target: 0.5,
                    weight: 1.0,
                    context: HashMap::new(),
                    metadata: ExampleMetadata {
                        source: "test".to_string(),
                        quality_score: 0.9,
                        created_at: std::time::SystemTime::now(),
                    },
                }],
                task_metadata: TaskMetadata {
                    task_name: "test_task".to_string(),
                    domain: DomainType::Optimization,
                    difficulty: DifficultyLevel::Easy,
                    created_at: std::time::SystemTime::now(),
                },
                statistics: SupportSetStatistics {
                    mean: Array1::from_vec(vec![1.0, 2.0, 3.0]),
                    variance: Array1::from_vec(vec![0.1, 0.1, 0.1]),
                    size: 1,
                    diversity_score: 0.8,
                },
                temporal_order: None,
            },
            query_set: QuerySet {
                examples: vec![QueryExample {
                    features: Array1::from_vec(vec![1.0, 2.0, 3.0]),
                    true_target: Some(0.4),
                    weight: 1.0,
                    context: HashMap::new(),
                }],
                statistics: QuerySetStatistics {
                    mean: Array1::from_vec(vec![1.0, 2.0, 3.0]),
                    variance: Array1::from_vec(vec![0.1, 0.1, 0.1]),
                    size: 1,
                },
                eval_metrics: vec![EvaluationMetric::MSE],
            },
            task_params: HashMap::new(),
            domain_info: DomainInfo {
                domain_type: DomainType::Optimization,
                characteristics: DomainCharacteristics {
                    input_dim: 3,
                    output_dim: 1,
                    temporal: false,
                    stochasticity: 0.0,
                    noise_level: 0.0,
                    sparsity: 0.0,
                },
                difficulty_level: DifficultyLevel::Easy,
                constraints: vec![],
            },
        }
    }

    fn make_adaptation_config() -> AdaptationConfig {
        AdaptationConfig {
            adaptation_steps: 5,
            adaptation_lr: 0.01,
            strategy: AdaptationStrategyType::MAML,
            early_stopping: None,
            regularization: RegularizationConfig {
                l2_strength: 0.0,
                dropout_rate: 0.0,
                gradient_clip: None,
                task_regularization: HashMap::new(),
            },
            resource_constraints: ResourceConstraints {
                max_time: Duration::from_secs(1),
                max_memory_mb: 64,
                max_compute_budget: 1.0,
            },
        }
    }

    /// F15 regression: `adapt_fast` must delegate to the real optimizer
    /// (falling back to `FewShotOptimizer::adapt_few_shot` when, as by
    /// default, no algorithm is registered) instead of returning fabricated,
    /// input-independent constants.
    #[test]
    fn test_adapt_fast_delegates_instead_of_fabricating() {
        let mut engine = FastAdaptationEngine::<f64>::new(FastAdaptationConfig {
            enable_caching: true,
            enable_prediction: true,
            max_adaptation_time: Duration::from_secs(1),
            _performance_threshold: 0.8,
        })
        .expect("engine");
        assert_eq!(
            engine.algorithm_count(),
            0,
            "no algorithm registered by default"
        );

        let mut optimizer = RecordingOptimizer { adapt_calls: 0 };
        let task_data = make_task_data();
        let config = make_adaptation_config();

        let result = engine
            .adapt_fast(
                &mut optimizer,
                &task_data,
                AdaptationStrategyType::MAML,
                &config,
            )
            .expect("adapt_fast should succeed");

        assert_eq!(
            optimizer.adapt_calls, 1,
            "adapt_fast must actually call the optimizer, not ignore it"
        );
        // Values from `RecordingOptimizer`, not the old fabricated constants
        // (query_performance 0.85, support_performance 0.90, adaptation_speed
        // 5, final_loss 0.1, improvement 0.25, stability 0.95).
        approx::assert_abs_diff_eq!(result.performance.query_performance, 0.42, epsilon = 1e-12);
        approx::assert_abs_diff_eq!(
            result.performance.support_performance,
            0.37,
            epsilon = 1e-12
        );
        assert_eq!(result.performance.adaptation_speed, 2);
        // The delegate's parameters (width 3, matching the support example),
        // not the old hard-coded `Array1::zeros(1)`.
        assert_eq!(result.adapted_state.parameters.len(), 3);
        // An empty delegate task representation is filled in from the
        // optimizer, not left as the old hard-coded `Array1::zeros(128)`.
        assert_eq!(
            result.task_representation.as_slice(),
            Some(&[7.0, 8.0, 9.0][..])
        );
        // Real wall-clock time replaces the delegate's marker value.
        assert!(result.resource_usage.total_time < Duration::from_secs(999));
    }

    /// F15 regression: a registered algorithm matching the requested strategy
    /// takes priority over the optimizer fallback.
    #[test]
    fn test_adapt_fast_prefers_a_registered_algorithm() {
        struct AlwaysProto {
            calls: usize,
        }
        impl FastAdaptationAlgorithm<f64> for AlwaysProto {
            fn adapt_fast(
                &mut self,
                _optimizer: &mut dyn FewShotOptimizer<f64>,
                _task_data: &TaskData<f64>,
                _target_performance: Option<f64>,
            ) -> Result<AdaptationResult<f64>> {
                self.calls += 1;
                Ok(AdaptationResult {
                    adapted_state: OptimizerState {
                        parameters: Array1::zeros(2),
                        gradients: Array1::zeros(2),
                        momentum: None,
                        hidden_states: HashMap::new(),
                        memory_buffers: HashMap::new(),
                        step: 0,
                        step_count: 0,
                        loss: None,
                        learning_rate: 0.02,
                        metadata: crate::StateMetadata::default(),
                    },
                    performance: AdaptationPerformance {
                        query_performance: 0.77,
                        support_performance: 0.66,
                        adaptation_speed: 1,
                        final_loss: 0.2,
                        improvement: 0.3,
                        stability: 0.4,
                    },
                    task_representation: Array1::from_vec(vec![1.0]),
                    adaptation_trajectory: Vec::new(),
                    resource_usage: ResourceUsage {
                        total_time: Duration::from_secs(0),
                        peak_memory_mb: 0.0,
                        compute_cost: 0.0,
                        energy_consumption: 0.0,
                    },
                })
            }

            fn estimate_adaptation_time(&self, _taskdata: &TaskData<f64>) -> Duration {
                Duration::from_millis(1)
            }

            fn name(&self) -> &str {
                "Prototypical"
            }
        }

        let mut engine = FastAdaptationEngine::<f64>::new(FastAdaptationConfig {
            enable_caching: false,
            enable_prediction: false,
            max_adaptation_time: Duration::from_secs(1),
            _performance_threshold: 0.5,
        })
        .expect("engine");
        engine.register_algorithm(Box::new(AlwaysProto { calls: 0 }));
        assert_eq!(engine.algorithm_count(), 1);

        let mut optimizer = RecordingOptimizer { adapt_calls: 0 };
        let task_data = make_task_data();
        let config = make_adaptation_config();

        let result = engine
            .adapt_fast(
                &mut optimizer,
                &task_data,
                AdaptationStrategyType::Prototypical,
                &config,
            )
            .expect("adapt_fast should succeed");

        assert_eq!(
            optimizer.adapt_calls, 0,
            "the registered algorithm should have been used instead of the optimizer fallback"
        );
        approx::assert_abs_diff_eq!(result.performance.query_performance, 0.77, epsilon = 1e-12);
    }
}