quantrs2-symengine-pure 0.2.0

Pure Rust symbolic mathematics for quantum computing - a replacement for C++-based symengine
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
//! Expression caching and memoization.
//!
//! This module provides caching mechanisms for expensive operations
//! like evaluation, simplification, and complex number operations.
//!
//! ## Features
//!
//! - **`EvalCache`**: Thread-safe cache for real-valued evaluation results with LRU eviction
//! - **`ComplexEvalCache`**: Thread-safe cache for complex-valued evaluations (quantum amplitudes)
//! - **`SimplificationCache`**: Cache for expression simplification results
//! - **`BatchEvalCache`**: Optimized for VQE optimization loops with parameter sweeps
//! - **`CachedEvaluator`**: Convenient wrapper with all caching features integrated
//! - **`ExpressionCache`**: Hash consing for structural sharing of expressions
//!
//! ## Performance Benefits
//!
//! Expression caching is critical for quantum computing applications:
//!
//! - **VQE/QAOA loops**: Same expressions evaluated thousands of times with different parameters
//! - **Gradient computation**: Derivatives computed repeatedly during optimization
//! - **Circuit simulation**: Gate matrices cached after first computation
//!
//! ## Example
//!
//! ```ignore
//! use quantrs2_symengine_pure::cache::{CachedEvaluator, hash_params};
//! use quantrs2_symengine_pure::Expression;
//! use std::collections::HashMap;
//!
//! let evaluator = CachedEvaluator::new();
//! let expr = Expression::symbol("x").sin();
//!
//! // First evaluation computes the result
//! let mut params = HashMap::new();
//! params.insert("x".to_string(), 0.5);
//! let result1 = evaluator.eval(&expr, &params).unwrap();
//!
//! // Second evaluation retrieves from cache
//! let result2 = evaluator.eval(&expr, &params).unwrap();
//! assert!((result1 - result2).abs() < 1e-10);
//!
//! // Check hit rate
//! let stats = evaluator.stats();
//! println!("Cache hit rate: {:.1}%", stats.overall_hit_rate() * 100.0);
//! ```

use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::sync::Arc;

use dashmap::DashMap;
use rustc_hash::FxHasher;
use scirs2_core::Complex64;

use crate::error::SymEngineResult;
use crate::expr::Expression;

/// Default maximum cache size (entries)
pub const DEFAULT_MAX_CACHE_SIZE: usize = 10_000;

/// Thread-safe cache for expression evaluation results with LRU eviction.
///
/// Uses DashMap for concurrent access and FxHasher for fast hashing.
pub struct EvalCache {
    cache: DashMap<(u64, u64), CachedValue<f64>, std::hash::BuildHasherDefault<FxHasher>>,
    max_size: usize,
    access_counter: AtomicU64,
    hits: AtomicUsize,
    misses: AtomicUsize,
}

/// A cached value with access tracking for LRU eviction
#[derive(Clone)]
struct CachedValue<T> {
    value: T,
    last_access: u64,
}

impl EvalCache {
    /// Create a new evaluation cache with default size
    #[must_use]
    pub fn new() -> Self {
        Self::with_capacity(DEFAULT_MAX_CACHE_SIZE)
    }

    /// Create a new evaluation cache with specified maximum size
    #[must_use]
    pub fn with_capacity(max_size: usize) -> Self {
        Self {
            cache: DashMap::with_hasher(std::hash::BuildHasherDefault::<FxHasher>::default()),
            max_size,
            access_counter: AtomicU64::new(0),
            hits: AtomicUsize::new(0),
            misses: AtomicUsize::new(0),
        }
    }

    /// Get or compute an evaluation result
    pub fn get_or_compute<F>(&self, expr_hash: u64, params_hash: u64, compute: F) -> f64
    where
        F: FnOnce() -> f64,
    {
        let key = (expr_hash, params_hash);
        let access_time = self.access_counter.fetch_add(1, Ordering::Relaxed);

        if let Some(mut entry) = self.cache.get_mut(&key) {
            self.hits.fetch_add(1, Ordering::Relaxed);
            entry.last_access = access_time;
            return entry.value;
        }

        self.misses.fetch_add(1, Ordering::Relaxed);
        let result = compute();

        // Check if we need to evict
        if self.cache.len() >= self.max_size {
            self.evict_lru();
        }

        self.cache.insert(
            key,
            CachedValue {
                value: result,
                last_access: access_time,
            },
        );
        result
    }

    /// Try to get a cached value without computing
    #[must_use]
    pub fn get(&self, expr_hash: u64, params_hash: u64) -> Option<f64> {
        let key = (expr_hash, params_hash);
        let access_time = self.access_counter.fetch_add(1, Ordering::Relaxed);

        self.cache.get_mut(&key).map(|mut entry| {
            entry.last_access = access_time;
            entry.value
        })
    }

    /// Get or compute with Result return type
    pub fn get_or_try_compute<F, E>(
        &self,
        expr_hash: u64,
        params_hash: u64,
        compute: F,
    ) -> Result<f64, E>
    where
        F: FnOnce() -> Result<f64, E>,
    {
        let key = (expr_hash, params_hash);
        let access_time = self.access_counter.fetch_add(1, Ordering::Relaxed);

        if let Some(mut entry) = self.cache.get_mut(&key) {
            self.hits.fetch_add(1, Ordering::Relaxed);
            entry.last_access = access_time;
            return Ok(entry.value);
        }

        self.misses.fetch_add(1, Ordering::Relaxed);
        let result = compute()?;

        if self.cache.len() >= self.max_size {
            self.evict_lru();
        }

        self.cache.insert(
            key,
            CachedValue {
                value: result,
                last_access: access_time,
            },
        );
        Ok(result)
    }

    /// Insert a value into the cache
    pub fn insert(&self, expr_hash: u64, params_hash: u64, value: f64) {
        let key = (expr_hash, params_hash);
        let access_time = self.access_counter.fetch_add(1, Ordering::Relaxed);

        if self.cache.len() >= self.max_size {
            self.evict_lru();
        }

        self.cache.insert(
            key,
            CachedValue {
                value,
                last_access: access_time,
            },
        );
    }

    /// Evict the least recently used entries (removes ~10% of cache)
    fn evict_lru(&self) {
        let evict_count = self.max_size / 10;
        if evict_count == 0 {
            return;
        }

        // Collect entries sorted by access time
        let mut entries: Vec<_> = self
            .cache
            .iter()
            .map(|e| (*e.key(), e.value().last_access))
            .collect();
        entries.sort_by_key(|(_, access)| *access);

        // Remove oldest entries
        for (key, _) in entries.into_iter().take(evict_count) {
            self.cache.remove(&key);
        }
    }

    /// Clear the cache
    pub fn clear(&self) {
        self.cache.clear();
        self.hits.store(0, Ordering::Relaxed);
        self.misses.store(0, Ordering::Relaxed);
    }

    /// Get the number of cached entries
    #[must_use]
    pub fn len(&self) -> usize {
        self.cache.len()
    }

    /// Check if the cache is empty
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.cache.is_empty()
    }

    /// Get cache statistics
    #[must_use]
    pub fn stats(&self) -> CacheStats {
        let hits = self.hits.load(Ordering::Relaxed);
        let misses = self.misses.load(Ordering::Relaxed);
        CacheStats {
            size: self.cache.len(),
            max_size: self.max_size,
            hits,
            misses,
            hit_rate: if hits + misses > 0 {
                hits as f64 / (hits + misses) as f64
            } else {
                0.0
            },
        }
    }
}

/// Cache statistics
#[derive(Debug, Clone)]
pub struct CacheStats {
    /// Current number of entries
    pub size: usize,
    /// Maximum allowed entries
    pub max_size: usize,
    /// Number of cache hits
    pub hits: usize,
    /// Number of cache misses
    pub misses: usize,
    /// Hit rate (0.0 to 1.0)
    pub hit_rate: f64,
}

impl Default for EvalCache {
    fn default() -> Self {
        Self::new()
    }
}

/// Hash consing for structural sharing of expressions
pub struct ExpressionCache {
    cache: DashMap<u64, Arc<Expression>, std::hash::BuildHasherDefault<FxHasher>>,
}

impl ExpressionCache {
    /// Create a new expression cache
    #[must_use]
    pub fn new() -> Self {
        Self {
            cache: DashMap::with_hasher(std::hash::BuildHasherDefault::<FxHasher>::default()),
        }
    }

    /// Get or insert an expression, returning a shared reference
    pub fn get_or_insert(&self, expr: Expression) -> Arc<Expression> {
        let hash = compute_hash(&expr);
        self.cache
            .entry(hash)
            .or_insert_with(|| Arc::new(expr))
            .clone()
    }

    /// Clear the cache
    pub fn clear(&self) {
        self.cache.clear();
    }
}

impl Default for ExpressionCache {
    fn default() -> Self {
        Self::new()
    }
}

// =========================================================================
// Complex Evaluation Cache
// =========================================================================

/// Thread-safe cache for complex number evaluation results.
///
/// Used for caching quantum amplitude calculations and complex-valued
/// expression evaluations.
pub struct ComplexEvalCache {
    cache: DashMap<(u64, u64), CachedValue<Complex64>, std::hash::BuildHasherDefault<FxHasher>>,
    max_size: usize,
    access_counter: AtomicU64,
    hits: AtomicUsize,
    misses: AtomicUsize,
}

impl ComplexEvalCache {
    /// Create a new complex evaluation cache with default size
    #[must_use]
    pub fn new() -> Self {
        Self::with_capacity(DEFAULT_MAX_CACHE_SIZE)
    }

    /// Create a new complex evaluation cache with specified maximum size
    #[must_use]
    pub fn with_capacity(max_size: usize) -> Self {
        Self {
            cache: DashMap::with_hasher(std::hash::BuildHasherDefault::<FxHasher>::default()),
            max_size,
            access_counter: AtomicU64::new(0),
            hits: AtomicUsize::new(0),
            misses: AtomicUsize::new(0),
        }
    }

    /// Get or compute a complex evaluation result
    pub fn get_or_compute<F>(&self, expr_hash: u64, params_hash: u64, compute: F) -> Complex64
    where
        F: FnOnce() -> Complex64,
    {
        let key = (expr_hash, params_hash);
        let access_time = self.access_counter.fetch_add(1, Ordering::Relaxed);

        if let Some(mut entry) = self.cache.get_mut(&key) {
            self.hits.fetch_add(1, Ordering::Relaxed);
            entry.last_access = access_time;
            return entry.value;
        }

        self.misses.fetch_add(1, Ordering::Relaxed);
        let result = compute();

        if self.cache.len() >= self.max_size {
            self.evict_lru();
        }

        self.cache.insert(
            key,
            CachedValue {
                value: result,
                last_access: access_time,
            },
        );
        result
    }

    /// Get or compute with Result return type
    pub fn get_or_try_compute<F, E>(
        &self,
        expr_hash: u64,
        params_hash: u64,
        compute: F,
    ) -> Result<Complex64, E>
    where
        F: FnOnce() -> Result<Complex64, E>,
    {
        let key = (expr_hash, params_hash);
        let access_time = self.access_counter.fetch_add(1, Ordering::Relaxed);

        if let Some(mut entry) = self.cache.get_mut(&key) {
            self.hits.fetch_add(1, Ordering::Relaxed);
            entry.last_access = access_time;
            return Ok(entry.value);
        }

        self.misses.fetch_add(1, Ordering::Relaxed);
        let result = compute()?;

        if self.cache.len() >= self.max_size {
            self.evict_lru();
        }

        self.cache.insert(
            key,
            CachedValue {
                value: result,
                last_access: access_time,
            },
        );
        Ok(result)
    }

    /// Evict the least recently used entries
    fn evict_lru(&self) {
        let evict_count = self.max_size / 10;
        if evict_count == 0 {
            return;
        }

        let mut entries: Vec<_> = self
            .cache
            .iter()
            .map(|e| (*e.key(), e.value().last_access))
            .collect();
        entries.sort_by_key(|(_, access)| *access);

        for (key, _) in entries.into_iter().take(evict_count) {
            self.cache.remove(&key);
        }
    }

    /// Clear the cache
    pub fn clear(&self) {
        self.cache.clear();
        self.hits.store(0, Ordering::Relaxed);
        self.misses.store(0, Ordering::Relaxed);
    }

    /// Get the number of cached entries
    #[must_use]
    pub fn len(&self) -> usize {
        self.cache.len()
    }

    /// Check if the cache is empty
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.cache.is_empty()
    }

    /// Get cache statistics
    #[must_use]
    pub fn stats(&self) -> CacheStats {
        let hits = self.hits.load(Ordering::Relaxed);
        let misses = self.misses.load(Ordering::Relaxed);
        CacheStats {
            size: self.cache.len(),
            max_size: self.max_size,
            hits,
            misses,
            hit_rate: if hits + misses > 0 {
                hits as f64 / (hits + misses) as f64
            } else {
                0.0
            },
        }
    }
}

impl Default for ComplexEvalCache {
    fn default() -> Self {
        Self::new()
    }
}

// =========================================================================
// Simplification Cache
// =========================================================================

/// Thread-safe cache for expression simplification results.
///
/// Caches the result of expensive simplification operations to avoid
/// re-running e-graph saturation for the same expressions.
pub struct SimplificationCache {
    cache: DashMap<u64, CachedValue<Expression>, std::hash::BuildHasherDefault<FxHasher>>,
    max_size: usize,
    access_counter: AtomicU64,
    hits: AtomicUsize,
    misses: AtomicUsize,
}

impl SimplificationCache {
    /// Create a new simplification cache with default size
    #[must_use]
    pub fn new() -> Self {
        Self::with_capacity(DEFAULT_MAX_CACHE_SIZE)
    }

    /// Create a new simplification cache with specified maximum size
    #[must_use]
    pub fn with_capacity(max_size: usize) -> Self {
        Self {
            cache: DashMap::with_hasher(std::hash::BuildHasherDefault::<FxHasher>::default()),
            max_size,
            access_counter: AtomicU64::new(0),
            hits: AtomicUsize::new(0),
            misses: AtomicUsize::new(0),
        }
    }

    /// Get or compute a simplified expression
    pub fn get_or_simplify<F>(&self, expr: &Expression, simplify: F) -> Expression
    where
        F: FnOnce() -> Expression,
    {
        let expr_hash = compute_hash(expr);
        let access_time = self.access_counter.fetch_add(1, Ordering::Relaxed);

        if let Some(mut entry) = self.cache.get_mut(&expr_hash) {
            self.hits.fetch_add(1, Ordering::Relaxed);
            entry.last_access = access_time;
            return entry.value.clone();
        }

        self.misses.fetch_add(1, Ordering::Relaxed);
        let result = simplify();

        if self.cache.len() >= self.max_size {
            self.evict_lru();
        }

        self.cache.insert(
            expr_hash,
            CachedValue {
                value: result.clone(),
                last_access: access_time,
            },
        );
        result
    }

    /// Evict the least recently used entries
    fn evict_lru(&self) {
        let evict_count = self.max_size / 10;
        if evict_count == 0 {
            return;
        }

        let mut entries: Vec<_> = self
            .cache
            .iter()
            .map(|e| (*e.key(), e.value().last_access))
            .collect();
        entries.sort_by_key(|(_, access)| *access);

        for (key, _) in entries.into_iter().take(evict_count) {
            self.cache.remove(&key);
        }
    }

    /// Clear the cache
    pub fn clear(&self) {
        self.cache.clear();
        self.hits.store(0, Ordering::Relaxed);
        self.misses.store(0, Ordering::Relaxed);
    }

    /// Get the number of cached entries
    #[must_use]
    pub fn len(&self) -> usize {
        self.cache.len()
    }

    /// Check if the cache is empty
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.cache.is_empty()
    }

    /// Get cache statistics
    #[must_use]
    pub fn stats(&self) -> CacheStats {
        let hits = self.hits.load(Ordering::Relaxed);
        let misses = self.misses.load(Ordering::Relaxed);
        CacheStats {
            size: self.cache.len(),
            max_size: self.max_size,
            hits,
            misses,
            hit_rate: if hits + misses > 0 {
                hits as f64 / (hits + misses) as f64
            } else {
                0.0
            },
        }
    }
}

impl Default for SimplificationCache {
    fn default() -> Self {
        Self::new()
    }
}

// =========================================================================
// Batch Evaluation Cache
// =========================================================================

/// Cache for batch evaluation results in VQE optimization loops.
///
/// Optimized for scenarios where the same expression is evaluated many times
/// with slightly different parameter sets (e.g., parameter sweeps).
pub struct BatchEvalCache {
    /// Expression hash -> (params_hash -> result)
    cache: DashMap<
        u64,
        DashMap<u64, f64, std::hash::BuildHasherDefault<FxHasher>>,
        std::hash::BuildHasherDefault<FxHasher>,
    >,
    max_expressions: usize,
    max_params_per_expr: usize,
}

impl BatchEvalCache {
    /// Create a new batch evaluation cache
    #[must_use]
    pub fn new() -> Self {
        Self::with_capacity(1000, 1000)
    }

    /// Create a new batch evaluation cache with specified capacities
    #[must_use]
    pub fn with_capacity(max_expressions: usize, max_params_per_expr: usize) -> Self {
        Self {
            cache: DashMap::with_hasher(std::hash::BuildHasherDefault::<FxHasher>::default()),
            max_expressions,
            max_params_per_expr,
        }
    }

    /// Get or compute a batch of evaluation results
    pub fn get_or_compute_batch<F>(
        &self,
        expr_hash: u64,
        param_hashes: &[u64],
        compute: F,
    ) -> Vec<f64>
    where
        F: FnOnce(&[usize]) -> Vec<f64>,
    {
        // Find which parameter sets we need to compute
        let expr_cache = self.cache.entry(expr_hash).or_insert_with(|| {
            DashMap::with_hasher(std::hash::BuildHasherDefault::<FxHasher>::default())
        });

        let mut results = vec![0.0; param_hashes.len()];
        let mut missing_indices = Vec::new();

        for (i, &ph) in param_hashes.iter().enumerate() {
            if let Some(val) = expr_cache.get(&ph) {
                results[i] = *val;
            } else {
                missing_indices.push(i);
            }
        }

        // Compute missing values
        if !missing_indices.is_empty() {
            let computed = compute(&missing_indices);

            for (j, &i) in missing_indices.iter().enumerate() {
                results[i] = computed[j];
                let ph = param_hashes[i];

                // Check if we need to evict from per-expression cache
                if expr_cache.len() >= self.max_params_per_expr {
                    // Simple random eviction (for speed)
                    // Extract key first to avoid holding the iterator lock
                    let first_key = expr_cache.iter().next().map(|e| *e.key());
                    if let Some(key) = first_key {
                        expr_cache.remove(&key);
                    }
                }

                expr_cache.insert(ph, computed[j]);
            }
        }

        results
    }

    /// Clear the cache
    pub fn clear(&self) {
        self.cache.clear();
    }

    /// Get the number of cached expressions
    #[must_use]
    pub fn len(&self) -> usize {
        self.cache.len()
    }

    /// Check if the cache is empty
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.cache.is_empty()
    }

    /// Get total number of cached parameter sets across all expressions
    #[must_use]
    pub fn total_params_cached(&self) -> usize {
        self.cache.iter().map(|e| e.value().len()).sum()
    }
}

impl Default for BatchEvalCache {
    fn default() -> Self {
        Self::new()
    }
}

// =========================================================================
// Cached Expression Evaluator
// =========================================================================

/// An expression evaluator with integrated caching.
///
/// This provides a convenient interface for evaluating expressions with
/// automatic caching of results.
#[allow(clippy::struct_field_names)]
pub struct CachedEvaluator {
    eval_cache: EvalCache,
    complex_cache: ComplexEvalCache,
    simplification_cache: SimplificationCache,
}

impl CachedEvaluator {
    /// Create a new cached evaluator
    #[must_use]
    pub fn new() -> Self {
        Self {
            eval_cache: EvalCache::new(),
            complex_cache: ComplexEvalCache::new(),
            simplification_cache: SimplificationCache::new(),
        }
    }

    /// Create a new cached evaluator with specified cache sizes
    #[must_use]
    pub fn with_capacity(eval_size: usize, complex_size: usize, simplify_size: usize) -> Self {
        Self {
            eval_cache: EvalCache::with_capacity(eval_size),
            complex_cache: ComplexEvalCache::with_capacity(complex_size),
            simplification_cache: SimplificationCache::with_capacity(simplify_size),
        }
    }

    /// Evaluate an expression with caching
    pub fn eval(&self, expr: &Expression, values: &HashMap<String, f64>) -> SymEngineResult<f64> {
        let expr_hash = compute_hash(expr);
        let params_hash = hash_params(values);

        // Use get_or_try_compute to properly track hits/misses
        self.eval_cache
            .get_or_try_compute(expr_hash, params_hash, || expr.eval(values))
    }

    /// Evaluate an expression as complex with caching
    pub fn eval_complex(
        &self,
        expr: &Expression,
        values: &HashMap<String, f64>,
    ) -> SymEngineResult<Complex64> {
        let expr_hash = compute_hash(expr);
        let params_hash = hash_params(values);

        self.complex_cache
            .get_or_try_compute(expr_hash, params_hash, || expr.eval_complex(values))
    }

    /// Simplify an expression with caching
    pub fn simplify(&self, expr: &Expression) -> Expression {
        self.simplification_cache
            .get_or_simplify(expr, || expr.simplify())
    }

    /// Clear all caches
    pub fn clear(&self) {
        self.eval_cache.clear();
        self.complex_cache.clear();
        self.simplification_cache.clear();
    }

    /// Get combined cache statistics
    #[must_use]
    pub fn stats(&self) -> CombinedCacheStats {
        CombinedCacheStats {
            eval: self.eval_cache.stats(),
            complex: self.complex_cache.stats(),
            simplification: self.simplification_cache.stats(),
        }
    }
}

impl Default for CachedEvaluator {
    fn default() -> Self {
        Self::new()
    }
}

/// Combined statistics for all cache types
#[derive(Debug, Clone)]
pub struct CombinedCacheStats {
    /// Real evaluation cache stats
    pub eval: CacheStats,
    /// Complex evaluation cache stats
    pub complex: CacheStats,
    /// Simplification cache stats
    pub simplification: CacheStats,
}

impl CombinedCacheStats {
    /// Get the total number of cached entries
    #[must_use]
    pub const fn total_size(&self) -> usize {
        self.eval.size + self.complex.size + self.simplification.size
    }

    /// Get the total number of cache hits
    #[must_use]
    pub const fn total_hits(&self) -> usize {
        self.eval.hits + self.complex.hits + self.simplification.hits
    }

    /// Get the total number of cache misses
    #[must_use]
    pub const fn total_misses(&self) -> usize {
        self.eval.misses + self.complex.misses + self.simplification.misses
    }

    /// Get the overall hit rate
    #[must_use]
    pub fn overall_hit_rate(&self) -> f64 {
        let total = self.total_hits() + self.total_misses();
        if total > 0 {
            self.total_hits() as f64 / total as f64
        } else {
            0.0
        }
    }
}

// =========================================================================
// Hash Functions
// =========================================================================

/// Compute a hash for an expression
pub fn compute_hash(expr: &Expression) -> u64 {
    use std::hash::{Hash, Hasher};
    let mut hasher = FxHasher::default();
    expr.to_string().hash(&mut hasher);
    hasher.finish()
}

/// Compute a hash for a set of real parameters
pub fn hash_params(params: &HashMap<String, f64>) -> u64 {
    use std::hash::{Hash, Hasher};
    let mut hasher = FxHasher::default();

    // Sort keys for consistent hashing
    let mut keys: Vec<_> = params.keys().collect();
    keys.sort();

    for key in keys {
        key.hash(&mut hasher);
        if let Some(value) = params.get(key) {
            value.to_bits().hash(&mut hasher);
        }
    }

    hasher.finish()
}

/// Compute a hash for complex parameters
pub fn hash_complex_params(params: &HashMap<String, Complex64>) -> u64 {
    use std::hash::{Hash, Hasher};
    let mut hasher = FxHasher::default();

    let mut keys: Vec<_> = params.keys().collect();
    keys.sort();

    for key in keys {
        key.hash(&mut hasher);
        if let Some(value) = params.get(key) {
            value.re.to_bits().hash(&mut hasher);
            value.im.to_bits().hash(&mut hasher);
        }
    }

    hasher.finish()
}

/// Compute a hash for a parameter array (for batch operations)
pub fn hash_param_array(params: &[f64]) -> u64 {
    use std::hash::{Hash, Hasher};
    let mut hasher = FxHasher::default();

    for value in params {
        value.to_bits().hash(&mut hasher);
    }

    hasher.finish()
}

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

    #[test]
    fn test_eval_cache() {
        let cache = EvalCache::new();

        let result1 = cache.get_or_compute(1, 1, || 42.0);
        assert!((result1 - 42.0).abs() < 1e-10);

        // Should return cached value
        let result2 = cache.get_or_compute(1, 1, || 100.0);
        assert!((result2 - 42.0).abs() < 1e-10);

        assert_eq!(cache.len(), 1);
    }

    #[test]
    fn test_eval_cache_stats() {
        let cache = EvalCache::new();

        // Miss then hit
        cache.get_or_compute(1, 1, || 42.0);
        cache.get_or_compute(1, 1, || 42.0);

        let stats = cache.stats();
        assert_eq!(stats.hits, 1);
        assert_eq!(stats.misses, 1);
        assert!((stats.hit_rate - 0.5).abs() < 1e-10);
    }

    #[test]
    fn test_eval_cache_lru_eviction() {
        let cache = EvalCache::with_capacity(10);

        // Fill cache beyond capacity
        for i in 0..15u64 {
            cache.get_or_compute(i, 0, || i as f64);
        }

        // Should have evicted some entries
        assert!(cache.len() <= 10);
    }

    #[test]
    fn test_complex_eval_cache() {
        let cache = ComplexEvalCache::new();

        let result1 = cache.get_or_compute(1, 1, || Complex64::new(3.0, 4.0));
        assert!((result1.re - 3.0).abs() < 1e-10);
        assert!((result1.im - 4.0).abs() < 1e-10);

        // Should return cached value
        let result2 = cache.get_or_compute(1, 1, || Complex64::new(100.0, 200.0));
        assert!((result2.re - 3.0).abs() < 1e-10);
        assert!((result2.im - 4.0).abs() < 1e-10);
    }

    #[test]
    fn test_complex_eval_cache_try_compute() {
        let cache = ComplexEvalCache::new();

        let result: Result<_, &str> =
            cache.get_or_try_compute(1, 1, || Ok(Complex64::new(1.0, 2.0)));
        assert!(result.is_ok());

        let stats = cache.stats();
        assert_eq!(stats.misses, 1);

        // Second call should hit cache
        let result2: Result<_, &str> =
            cache.get_or_try_compute(1, 1, || Err("should not be called"));
        assert!(result2.is_ok());

        let stats = cache.stats();
        assert_eq!(stats.hits, 1);
    }

    #[test]
    fn test_simplification_cache() {
        let cache = SimplificationCache::new();

        let expr = Expression::symbol("x") + Expression::symbol("x");
        let simplified = cache.get_or_simplify(&expr, || {
            // This simulates simplification
            Expression::int(2) * Expression::symbol("x")
        });

        // Should have cached
        assert_eq!(cache.len(), 1);

        // Second call should return cached
        let simplified2 = cache.get_or_simplify(&expr, || {
            // This should not be called
            Expression::symbol("should_not_appear")
        });

        // Both should be equivalent
        assert_eq!(simplified.to_string(), simplified2.to_string());

        let stats = cache.stats();
        assert_eq!(stats.hits, 1);
        assert_eq!(stats.misses, 1);
    }

    #[test]
    fn test_batch_eval_cache() {
        let cache = BatchEvalCache::new();

        let expr_hash = 12345u64;
        let param_hashes = vec![1, 2, 3, 4, 5];

        let mut compute_count = 0;
        let results = cache.get_or_compute_batch(expr_hash, &param_hashes, |missing| {
            compute_count = missing.len();
            missing.iter().map(|&i| i as f64 * 10.0).collect()
        });

        assert_eq!(compute_count, 5); // All were missing
        assert!((results[0] - 0.0).abs() < 1e-10);
        assert!((results[1] - 10.0).abs() < 1e-10);

        // Second call - all should be cached
        let mut compute_count2 = 0;
        let results2 = cache.get_or_compute_batch(expr_hash, &param_hashes, |missing| {
            compute_count2 = missing.len();
            missing.iter().map(|&i| i as f64 * 100.0).collect()
        });

        assert_eq!(compute_count2, 0); // All were cached
        assert!((results2[0] - 0.0).abs() < 1e-10);
        assert!((results2[1] - 10.0).abs() < 1e-10);
    }

    #[test]
    fn test_batch_eval_cache_partial_hit() {
        let cache = BatchEvalCache::new();

        let expr_hash = 12345u64;

        // First call with params 1, 2, 3
        cache.get_or_compute_batch(expr_hash, &[1, 2, 3], |missing| {
            missing.iter().map(|&i| i as f64).collect()
        });

        // Second call with params 2, 3, 4, 5 - 2 and 3 should be cached
        let mut computed_indices = Vec::new();
        cache.get_or_compute_batch(expr_hash, &[2, 3, 4, 5], |missing| {
            computed_indices = missing.to_vec();
            missing.iter().map(|&i| i as f64).collect()
        });

        // Only indices 2 and 3 (params 4 and 5) should be computed
        assert_eq!(computed_indices, vec![2, 3]);
    }

    #[test]
    fn test_cached_evaluator() {
        let evaluator = CachedEvaluator::new();

        let expr = Expression::symbol("x");
        let mut values = HashMap::new();
        values.insert("x".to_string(), 5.0);

        let result1 = evaluator.eval(&expr, &values).expect("should eval");
        assert!((result1 - 5.0).abs() < 1e-10);

        // Second call should use cache
        let result2 = evaluator.eval(&expr, &values).expect("should eval");
        assert!((result2 - 5.0).abs() < 1e-10);

        let stats = evaluator.stats();
        assert_eq!(stats.eval.misses, 1);
        assert_eq!(stats.eval.hits, 1);
    }

    #[test]
    fn test_cached_evaluator_complex() {
        let evaluator = CachedEvaluator::new();

        // Expression: 1 + I (imaginary unit)
        let expr = Expression::int(1) + Expression::symbol("I");
        let values = HashMap::new();

        let result = evaluator.eval_complex(&expr, &values).expect("should eval");
        assert!((result.re - 1.0).abs() < 1e-10);
        assert!((result.im - 1.0).abs() < 1e-10);

        let stats = evaluator.stats();
        assert_eq!(stats.complex.misses, 1);
    }

    #[test]
    fn test_cached_evaluator_simplify() {
        let evaluator = CachedEvaluator::new();

        let expr = Expression::symbol("x") + Expression::int(0);
        let simplified = evaluator.simplify(&expr);

        // x + 0 should simplify to just x
        assert!(simplified.is_symbol() || simplified.to_string().contains('x'));

        // Second call should use cache
        let simplified2 = evaluator.simplify(&expr);
        assert_eq!(simplified.to_string(), simplified2.to_string());

        let stats = evaluator.stats();
        assert_eq!(stats.simplification.misses, 1);
        assert_eq!(stats.simplification.hits, 1);
    }

    #[test]
    fn test_combined_cache_stats() {
        let evaluator = CachedEvaluator::new();

        // Generate some hits and misses
        let expr = Expression::symbol("x");
        let mut values = HashMap::new();
        values.insert("x".to_string(), 1.0);

        // Miss, hit, hit
        for _ in 0..3 {
            let _ = evaluator.eval(&expr, &values);
        }

        let stats = evaluator.stats();
        assert_eq!(stats.total_size(), 1);
        assert_eq!(stats.total_hits(), 2);
        assert_eq!(stats.total_misses(), 1);
        assert!((stats.overall_hit_rate() - 2.0 / 3.0).abs() < 1e-10);
    }

    #[test]
    fn test_hash_params() {
        let mut params1 = HashMap::new();
        params1.insert("x".to_string(), 1.0);
        params1.insert("y".to_string(), 2.0);

        let mut params2 = HashMap::new();
        params2.insert("y".to_string(), 2.0);
        params2.insert("x".to_string(), 1.0);

        // Order shouldn't matter
        assert_eq!(hash_params(&params1), hash_params(&params2));
    }

    #[test]
    fn test_hash_complex_params() {
        let mut params1 = HashMap::new();
        params1.insert("a".to_string(), Complex64::new(1.0, 2.0));
        params1.insert("b".to_string(), Complex64::new(3.0, 4.0));

        let mut params2 = HashMap::new();
        params2.insert("b".to_string(), Complex64::new(3.0, 4.0));
        params2.insert("a".to_string(), Complex64::new(1.0, 2.0));

        // Order shouldn't matter
        assert_eq!(hash_complex_params(&params1), hash_complex_params(&params2));
    }

    #[test]
    fn test_hash_param_array() {
        let params1 = [1.0, 2.0, 3.0];
        let params2 = [1.0, 2.0, 3.0];
        let params3 = [1.0, 2.0, 4.0];

        assert_eq!(hash_param_array(&params1), hash_param_array(&params2));
        assert_ne!(hash_param_array(&params1), hash_param_array(&params3));
    }

    #[test]
    fn test_expression_cache() {
        let cache = ExpressionCache::new();

        let expr1 = Expression::symbol("x");
        let arc1 = cache.get_or_insert(expr1.clone());
        let arc2 = cache.get_or_insert(expr1);

        // Should be the same Arc
        assert!(Arc::ptr_eq(&arc1, &arc2));
    }

    #[test]
    fn test_cache_clear() {
        let cache = EvalCache::new();
        cache.get_or_compute(1, 1, || 42.0);
        assert_eq!(cache.len(), 1);

        cache.clear();
        assert!(cache.is_empty());

        let stats = cache.stats();
        assert_eq!(stats.hits, 0);
        assert_eq!(stats.misses, 0);
    }
}