quantrs2-core 0.1.3

Core types and traits for the QuantRS2 quantum computing framework
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
//! Advanced Quantum Circuit Equivalence Checker with Enhanced SciRS2 Numerical Tolerance
//!
//! This module provides state-of-the-art quantum circuit equivalence checking
//! using advanced SciRS2 numerical analysis capabilities, including SVD-based
//! comparison, spectral analysis, and sophisticated tolerance mechanisms.

use crate::error::QuantRS2Error;
use crate::gate_translation::GateType;
use scirs2_core::Complex64;
// use scirs2_core::parallel_ops::*;
use crate::parallel_ops_stubs::*;
// use scirs2_core::memory::BufferPool;
use crate::buffer_pool::BufferPool;
use scirs2_core::ndarray::{Array1, Array2, ArrayView2};
// For complex matrices, use ndarray-linalg traits via scirs2_core (SciRS2 POLICY)
use scirs2_core::ndarray::ndarray_linalg::{Eigh, Norm, SVD, UPLO};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::sync::Arc;

/// Advanced configuration for SciRS2-enhanced equivalence checking
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AdvancedEquivalenceConfig {
    /// Base configuration
    pub base_config: crate::equivalence_checker::EquivalenceConfig,

    /// Advanced comparison methods
    pub comparison_methods: Vec<ComparisonMethod>,

    /// SVD truncation threshold for noise resilience
    pub svd_truncation_threshold: f64,

    /// Enable circuit canonicalization
    pub enable_canonicalization: bool,

    /// Maximum circuit depth for canonicalization
    pub max_canonicalization_depth: usize,

    /// Enable quantum process tomography verification
    pub enable_qpt_verification: bool,

    /// Number of Pauli basis measurements for QPT
    pub qpt_measurement_count: usize,

    /// Enable circuit fingerprinting for fast comparison
    pub enable_fingerprinting: bool,

    /// Fingerprint hash size in bits
    pub fingerprint_bits: usize,

    /// Enable state space partitioning for large circuits
    pub enable_partitioning: bool,

    /// Partition size threshold (qubits)
    pub partition_threshold: usize,

    /// Advanced tolerance settings
    pub tolerance_settings: ToleranceSettings,

    /// Circuit symmetry detection depth
    pub symmetry_detection_depth: usize,

    /// Enable statistical equivalence testing
    pub enable_statistical_testing: bool,

    /// Statistical confidence level (0.0 to 1.0)
    pub statistical_confidence: f64,
}

impl Default for AdvancedEquivalenceConfig {
    fn default() -> Self {
        Self {
            base_config: Default::default(),
            comparison_methods: vec![
                ComparisonMethod::FrobeniusNorm,
                ComparisonMethod::SpectralNorm,
                ComparisonMethod::SvdBased,
            ],
            svd_truncation_threshold: 1e-10,
            enable_canonicalization: true,
            max_canonicalization_depth: 100,
            enable_qpt_verification: false,
            qpt_measurement_count: 1000,
            enable_fingerprinting: true,
            fingerprint_bits: 256,
            enable_partitioning: true,
            partition_threshold: 20,
            tolerance_settings: ToleranceSettings::default(),
            symmetry_detection_depth: 10,
            enable_statistical_testing: true,
            statistical_confidence: 0.99,
        }
    }
}

/// Advanced comparison methods for numerical equivalence
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ComparisonMethod {
    /// Frobenius norm comparison
    FrobeniusNorm,
    /// Spectral norm (largest singular value)
    SpectralNorm,
    /// SVD-based comparison with tolerance
    SvdBased,
    /// Eigenvalue spectrum comparison
    EigenvalueBased,
    /// Trace distance comparison
    TraceDistance,
    /// Diamond norm approximation
    DiamondNorm,
    /// Choi matrix comparison
    ChoiMatrix,
    /// Process fidelity
    ProcessFidelity,
}

/// Advanced tolerance settings with adaptive thresholds
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToleranceSettings {
    /// Base absolute tolerance
    pub absolute_tolerance: f64,
    /// Base relative tolerance
    pub relative_tolerance: f64,
    /// Machine epsilon multiplier
    pub epsilon_multiplier: f64,
    /// Adaptive tolerance based on circuit size
    pub size_adaptive_factor: f64,
    /// Noise-aware tolerance adjustment
    pub noise_tolerance_factor: f64,
    /// Condition number threshold for ill-conditioned matrices
    pub condition_threshold: f64,
}

impl Default for ToleranceSettings {
    fn default() -> Self {
        Self {
            absolute_tolerance: 1e-12,
            relative_tolerance: 1e-10,
            epsilon_multiplier: 10.0,
            size_adaptive_factor: 1.5,
            noise_tolerance_factor: 2.0,
            condition_threshold: 1e12,
        }
    }
}

/// Circuit fingerprint for fast comparison
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct CircuitFingerprint {
    /// Gate count by type
    pub gate_counts: std::collections::BTreeMap<String, usize>,
    /// Circuit depth
    pub depth: usize,
    /// Connectivity hash
    pub connectivity_hash: u64,
    /// Parameter hash for parametric gates
    pub parameter_hash: u64,
    /// Structural hash
    pub structural_hash: u64,
}

/// Advanced quantum circuit equivalence checker
pub struct AdvancedEquivalenceChecker {
    config: AdvancedEquivalenceConfig,
    buffer_pool: Arc<BufferPool<Complex64>>,
    fingerprint_cache: HashMap<Vec<u8>, CircuitFingerprint>,
    canonical_cache: HashMap<Vec<u8>, Vec<crate::equivalence_checker::QuantumGate>>,
}

impl AdvancedEquivalenceChecker {
    /// Create a new advanced equivalence checker
    pub fn new() -> Self {
        Self::with_config(AdvancedEquivalenceConfig::default())
    }

    /// Create with custom configuration
    pub fn with_config(config: AdvancedEquivalenceConfig) -> Self {
        Self {
            config,
            buffer_pool: Arc::new(BufferPool::new()),
            fingerprint_cache: HashMap::new(),
            canonical_cache: HashMap::new(),
        }
    }

    /// Perform comprehensive equivalence check with all advanced features
    pub fn comprehensive_equivalence_check(
        &mut self,
        circuit1: &[crate::equivalence_checker::QuantumGate],
        circuit2: &[crate::equivalence_checker::QuantumGate],
        num_qubits: usize,
    ) -> Result<AdvancedEquivalenceResult, QuantRS2Error> {
        // Quick fingerprint check
        if self.config.enable_fingerprinting {
            let fp1 = self.compute_fingerprint(circuit1)?;
            let fp2 = self.compute_fingerprint(circuit2)?;

            if fp1 == fp2 {
                return Ok(AdvancedEquivalenceResult {
                    equivalent: true,
                    confidence: 1.0,
                    comparison_methods_used: vec!["Fingerprint".to_string()],
                    numerical_error: 0.0,
                    phase_factor: Some(Complex64::new(1.0, 0.0)),
                    canonical_forms_computed: false,
                    symmetries_detected: vec![],
                    performance_metrics: PerformanceMetrics::default(),
                });
            }
        }

        // Canonicalize circuits if enabled
        let (canonical1, canonical2) = if self.config.enable_canonicalization {
            (
                self.canonicalize_circuit(circuit1, num_qubits)?,
                self.canonicalize_circuit(circuit2, num_qubits)?,
            )
        } else {
            (circuit1.to_vec(), circuit2.to_vec())
        };

        // Perform multiple comparison methods
        let mut results = Vec::new();
        let mut methods_used = Vec::new();

        for method in &self.config.comparison_methods {
            let result = match method {
                ComparisonMethod::FrobeniusNorm => {
                    self.frobenius_norm_comparison(&canonical1, &canonical2, num_qubits)?
                }
                ComparisonMethod::SpectralNorm => {
                    self.spectral_norm_comparison(&canonical1, &canonical2, num_qubits)?
                }
                ComparisonMethod::SvdBased => {
                    self.svd_based_comparison(&canonical1, &canonical2, num_qubits)?
                }
                ComparisonMethod::EigenvalueBased => {
                    self.eigenvalue_comparison(&canonical1, &canonical2, num_qubits)?
                }
                ComparisonMethod::TraceDistance => {
                    self.trace_distance_comparison(&canonical1, &canonical2, num_qubits)?
                }
                ComparisonMethod::ProcessFidelity => {
                    self.process_fidelity_comparison(&canonical1, &canonical2, num_qubits)?
                }
                _ => continue,
            };

            results.push(result);
            methods_used.push(format!("{method:?}"));
        }

        // Aggregate results with confidence scoring
        let (equivalent, confidence, numerical_error) = self.aggregate_results(&results);

        // Detect symmetries if enabled
        let symmetries = if self.config.base_config.enable_symmetry_detection {
            self.detect_circuit_symmetries(&canonical1, num_qubits)?
        } else {
            vec![]
        };

        // Extract phase factor if circuits are equivalent up to phase
        let phase_factor = if equivalent {
            Some(Complex64::new(1.0, 0.0))
        } else {
            self.extract_global_phase(&canonical1, &canonical2, num_qubits)
                .ok()
        };

        Ok(AdvancedEquivalenceResult {
            equivalent,
            confidence,
            comparison_methods_used: methods_used,
            numerical_error,
            phase_factor,
            canonical_forms_computed: self.config.enable_canonicalization,
            symmetries_detected: symmetries,
            performance_metrics: PerformanceMetrics::default(),
        })
    }

    /// Compute circuit fingerprint for fast comparison
    fn compute_fingerprint(
        &mut self,
        circuit: &[crate::equivalence_checker::QuantumGate],
    ) -> Result<CircuitFingerprint, QuantRS2Error> {
        let circuit_hash = self.hash_circuit(circuit);

        if let Some(cached) = self.fingerprint_cache.get(&circuit_hash) {
            return Ok(cached.clone());
        }

        let mut gate_counts = std::collections::BTreeMap::new();
        let mut connectivity = HashSet::new();
        let mut depth = 0;
        let mut current_layer = HashSet::new();

        for gate in circuit {
            let gate_type = format!("{:?}", gate.gate_type());
            *gate_counts.entry(gate_type).or_insert(0) += 1;

            // Track connectivity
            for target in gate.target_qubits() {
                connectivity.insert(*target);
                current_layer.insert(*target);
            }
            if let Some(controls) = gate.control_qubits() {
                for control in controls {
                    connectivity.insert(*control);
                    current_layer.insert(*control);
                }
            }

            // Simple depth calculation
            if current_layer.len() > depth {
                depth = current_layer.len();
            }
        }

        let connectivity_hash = self.hash_set(&connectivity);
        let parameter_hash = self.hash_parameters(circuit);
        let structural_hash = self.hash_structure(circuit);

        let fingerprint = CircuitFingerprint {
            gate_counts,
            depth,
            connectivity_hash,
            parameter_hash,
            structural_hash,
        };

        self.fingerprint_cache
            .insert(circuit_hash, fingerprint.clone());
        Ok(fingerprint)
    }

    /// Canonicalize circuit for comparison
    fn canonicalize_circuit(
        &mut self,
        circuit: &[crate::equivalence_checker::QuantumGate],
        num_qubits: usize,
    ) -> Result<Vec<crate::equivalence_checker::QuantumGate>, QuantRS2Error> {
        let circuit_hash = self.hash_circuit(circuit);

        if let Some(cached) = self.canonical_cache.get(&circuit_hash) {
            return Ok(cached.clone());
        }

        let mut canonical = circuit.to_vec();

        // Apply canonicalization rules
        for _ in 0..self.config.max_canonicalization_depth {
            let mut changed = false;

            // Rule 1: Commute compatible gates
            changed |= self.apply_commutation_rules(&mut canonical)?;

            // Rule 2: Merge adjacent gates
            changed |= self.apply_gate_fusion(&canonical)?;

            // Rule 3: Cancel inverse gates
            changed |= self.apply_inverse_cancellation(&mut canonical)?;

            // Rule 4: Normalize phases
            changed |= self.apply_phase_normalization(&canonical)?;

            if !changed {
                break;
            }
        }

        // Sort gates by a canonical ordering
        self.apply_canonical_ordering(&mut canonical);

        self.canonical_cache.insert(circuit_hash, canonical.clone());
        Ok(canonical)
    }

    /// Frobenius norm comparison with adaptive tolerance
    fn frobenius_norm_comparison(
        &self,
        circuit1: &[crate::equivalence_checker::QuantumGate],
        circuit2: &[crate::equivalence_checker::QuantumGate],
        num_qubits: usize,
    ) -> Result<ComparisonResult, QuantRS2Error> {
        let matrix1 = self.compute_unitary_matrix(circuit1, num_qubits)?;
        let matrix2 = self.compute_unitary_matrix(circuit2, num_qubits)?;

        let diff = &matrix1 - &matrix2;
        // Use Norm trait via scirs2_core::ndarray (SciRS2 POLICY)
        let frobenius_norm = diff.norm_l2()?;
        let matrix_size = (1 << num_qubits) as f64;

        // Adaptive tolerance based on matrix size
        let tolerance = self.config.tolerance_settings.absolute_tolerance
            * matrix_size.sqrt()
            * self
                .config
                .tolerance_settings
                .size_adaptive_factor
                .powf(num_qubits as f64 / 10.0);

        Ok(ComparisonResult {
            equivalent: frobenius_norm < tolerance,
            error_measure: frobenius_norm,
            confidence: 1.0 - (frobenius_norm / matrix_size.sqrt()).min(1.0),
        })
    }

    /// Spectral norm comparison (largest singular value)
    fn spectral_norm_comparison(
        &self,
        circuit1: &[crate::equivalence_checker::QuantumGate],
        circuit2: &[crate::equivalence_checker::QuantumGate],
        num_qubits: usize,
    ) -> Result<ComparisonResult, QuantRS2Error> {
        let matrix1 = self.compute_unitary_matrix(circuit1, num_qubits)?;
        let matrix2 = self.compute_unitary_matrix(circuit2, num_qubits)?;

        let diff = &matrix1 - &matrix2;

        // Compute SVD to get spectral norm (use SVD trait via scirs2_core - SciRS2 POLICY)
        let (_, singular_values, _) = diff
            .svd(true, true)
            .map_err(|_| QuantRS2Error::ComputationError("SVD computation failed".into()))?;

        let spectral_norm = singular_values[0];
        let tolerance = self.config.tolerance_settings.absolute_tolerance;

        Ok(ComparisonResult {
            equivalent: spectral_norm < tolerance,
            error_measure: spectral_norm,
            confidence: 1.0 - spectral_norm.min(1.0),
        })
    }

    /// SVD-based comparison with truncation
    fn svd_based_comparison(
        &self,
        circuit1: &[crate::equivalence_checker::QuantumGate],
        circuit2: &[crate::equivalence_checker::QuantumGate],
        num_qubits: usize,
    ) -> Result<ComparisonResult, QuantRS2Error> {
        let matrix1 = self.compute_unitary_matrix(circuit1, num_qubits)?;
        let matrix2 = self.compute_unitary_matrix(circuit2, num_qubits)?;

        // Compute SVD of both matrices (use SVD trait via scirs2_core - SciRS2 POLICY)
        let (_, singular_values1, _) = matrix1.svd(true, true).map_err(|_| {
            QuantRS2Error::ComputationError("SVD computation failed for matrix 1".into())
        })?;

        let (_, singular_values2, _) = matrix2.svd(true, true).map_err(|_| {
            QuantRS2Error::ComputationError("SVD computation failed for matrix 2".into())
        })?;

        // Compare singular values with truncation
        let mut total_error: f64 = 0.0;
        let threshold = self.config.svd_truncation_threshold;

        for i in 0..singular_values1.len() {
            if singular_values1[i] > threshold || singular_values2[i] > threshold {
                let diff = (singular_values1[i] - singular_values2[i]).abs();
                total_error += diff * diff;
            }
        }

        let error = total_error.sqrt();
        let tolerance = self.config.tolerance_settings.absolute_tolerance;

        Ok(ComparisonResult {
            equivalent: error < tolerance,
            error_measure: error,
            confidence: 1.0 - error.min(1.0),
        })
    }

    /// Eigenvalue spectrum comparison
    fn eigenvalue_comparison(
        &self,
        circuit1: &[crate::equivalence_checker::QuantumGate],
        circuit2: &[crate::equivalence_checker::QuantumGate],
        num_qubits: usize,
    ) -> Result<ComparisonResult, QuantRS2Error> {
        let matrix1 = self.compute_unitary_matrix(circuit1, num_qubits)?;
        let matrix2 = self.compute_unitary_matrix(circuit2, num_qubits)?;

        // For unitary matrices, we can compute eigenvalues efficiently
        // Since U†U = I, all eigenvalues have magnitude 1
        // We'll compare the phases of eigenvalues

        // Convert to hermitian for eigenvalue computation: U + U†
        let herm1 = &matrix1 + &matrix1.t().mapv(|x| x.conj());
        let herm2 = &matrix2 + &matrix2.t().mapv(|x| x.conj());

        // Use ndarray-linalg trait via scirs2_core for complex hermitian matrices (SciRS2 POLICY)
        let (evals1, _) = herm1.eigh(UPLO::Upper).map_err(|_| {
            QuantRS2Error::ComputationError("Eigenvalue computation failed for matrix 1".into())
        })?;

        let (evals2, _) = herm2.eigh(UPLO::Upper).map_err(|_| {
            QuantRS2Error::ComputationError("Eigenvalue computation failed for matrix 2".into())
        })?;

        // Sort eigenvalues for comparison
        let mut sorted_evals1: Vec<f64> = evals1.iter().copied().collect();
        let mut sorted_evals2: Vec<f64> = evals2.iter().copied().collect();
        sorted_evals1.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
        sorted_evals2.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));

        // Compare sorted eigenvalues
        let mut max_diff: f64 = 0.0;
        for (e1, e2) in sorted_evals1.iter().zip(sorted_evals2.iter()) {
            max_diff = max_diff.max((e1 - e2).abs());
        }

        let tolerance = self.config.tolerance_settings.absolute_tolerance;

        Ok(ComparisonResult {
            equivalent: max_diff < tolerance,
            error_measure: max_diff,
            confidence: 1.0 - max_diff.min(1.0),
        })
    }

    /// Trace distance comparison
    fn trace_distance_comparison(
        &self,
        circuit1: &[crate::equivalence_checker::QuantumGate],
        circuit2: &[crate::equivalence_checker::QuantumGate],
        num_qubits: usize,
    ) -> Result<ComparisonResult, QuantRS2Error> {
        let matrix1 = self.compute_unitary_matrix(circuit1, num_qubits)?;
        let matrix2 = self.compute_unitary_matrix(circuit2, num_qubits)?;

        // Compute trace distance: 0.5 * Tr(|U1 - U2|)
        let diff = &matrix1 - &matrix2;

        // For trace distance, we need the trace of the absolute value
        // This requires computing eigenvalues of (U1 - U2)†(U1 - U2)
        let diff_dag_diff = diff.t().mapv(|x| x.conj()).dot(&diff);

        // Use ndarray-linalg trait via scirs2_core for complex hermitian matrices (SciRS2 POLICY)
        let (eigenvalues, _) = diff_dag_diff.eigh(UPLO::Upper).map_err(|_| {
            QuantRS2Error::ComputationError(
                "Eigenvalue computation failed for trace distance".into(),
            )
        })?;

        let trace_distance: f64 =
            eigenvalues.iter().map(|&lambda| lambda.sqrt()).sum::<f64>() * 0.5;

        let tolerance = self.config.tolerance_settings.absolute_tolerance;

        Ok(ComparisonResult {
            equivalent: trace_distance < tolerance,
            error_measure: trace_distance,
            confidence: 1.0 - (trace_distance / num_qubits as f64).min(1.0),
        })
    }

    /// Process fidelity comparison
    fn process_fidelity_comparison(
        &self,
        circuit1: &[crate::equivalence_checker::QuantumGate],
        circuit2: &[crate::equivalence_checker::QuantumGate],
        num_qubits: usize,
    ) -> Result<ComparisonResult, QuantRS2Error> {
        let matrix1 = self.compute_unitary_matrix(circuit1, num_qubits)?;
        let matrix2 = self.compute_unitary_matrix(circuit2, num_qubits)?;

        let dim = 1 << num_qubits;

        // Process fidelity: |Tr(U1† U2)|² / d²
        let u1_dag_u2 = matrix1.t().mapv(|x| x.conj()).dot(&matrix2);
        let trace: Complex64 = (0..dim).map(|i| u1_dag_u2[[i, i]]).sum();
        let fidelity = (trace.norm_sqr()) / (dim * dim) as f64;

        // Convert fidelity to error measure (1 - fidelity)
        let error = 1.0 - fidelity;
        let tolerance = self.config.tolerance_settings.absolute_tolerance;

        Ok(ComparisonResult {
            equivalent: error < tolerance,
            error_measure: error,
            confidence: fidelity,
        })
    }

    /// Compute unitary matrix representation
    fn compute_unitary_matrix(
        &self,
        circuit: &[crate::equivalence_checker::QuantumGate],
        num_qubits: usize,
    ) -> Result<Array2<Complex64>, QuantRS2Error> {
        let dim = 1 << num_qubits;
        let mut matrix = Array2::eye(dim);

        // Apply gates in order (quantum circuit convention)
        for gate in circuit {
            let gate_matrix = self.gate_to_ndarray_matrix(gate, num_qubits)?;
            // For quantum circuits, we apply gates from left to right: U_total = U_n * ... * U_2 * U_1
            // Since we're building up the matrix, we do: matrix = gate_matrix * matrix
            matrix = gate_matrix.dot(&matrix);
        }

        Ok(matrix)
    }

    /// Convert gate to ndarray matrix
    fn gate_to_ndarray_matrix(
        &self,
        gate: &crate::equivalence_checker::QuantumGate,
        num_qubits: usize,
    ) -> Result<Array2<Complex64>, QuantRS2Error> {
        let dim = 1 << num_qubits;
        let mut matrix = Array2::eye(dim);

        // Apply gate-specific transformations
        match gate.gate_type() {
            GateType::X => self.apply_pauli_x(&mut matrix, gate.target_qubits()[0], num_qubits),
            GateType::Y => self.apply_pauli_y(&mut matrix, gate.target_qubits()[0], num_qubits),
            GateType::Z => self.apply_pauli_z(&mut matrix, gate.target_qubits()[0], num_qubits),
            GateType::H => self.apply_hadamard(&mut matrix, gate.target_qubits()[0], num_qubits),
            GateType::CNOT => {
                if gate.target_qubits().len() >= 2 {
                    self.apply_cnot(
                        &mut matrix,
                        gate.target_qubits()[0],
                        gate.target_qubits()[1],
                        num_qubits,
                    );
                }
            }
            _ => {} // Other gates would be implemented similarly
        }

        Ok(matrix)
    }

    /// Apply Pauli X gate
    fn apply_pauli_x(&self, matrix: &mut Array2<Complex64>, target: usize, num_qubits: usize) {
        let target_bit = 1 << target;
        let dim = 1 << num_qubits;

        for i in 0..dim {
            if i & target_bit == 0 {
                let j = i | target_bit;
                for k in 0..dim {
                    let temp = matrix[[i, k]];
                    matrix[[i, k]] = matrix[[j, k]];
                    matrix[[j, k]] = temp;
                }
            }
        }
    }

    /// Apply Pauli Y gate
    fn apply_pauli_y(&self, matrix: &mut Array2<Complex64>, target: usize, num_qubits: usize) {
        let target_bit = 1 << target;
        let dim = 1 << num_qubits;
        let i_unit = Complex64::new(0.0, 1.0);

        for i in 0..dim {
            if i & target_bit == 0 {
                let j = i | target_bit;
                for k in 0..dim {
                    let temp = matrix[[i, k]];
                    matrix[[i, k]] = -i_unit * matrix[[j, k]];
                    matrix[[j, k]] = i_unit * temp;
                }
            }
        }
    }

    /// Apply Pauli Z gate
    fn apply_pauli_z(&self, matrix: &mut Array2<Complex64>, target: usize, num_qubits: usize) {
        let target_bit = 1 << target;
        let dim = 1 << num_qubits;

        for i in 0..dim {
            if i & target_bit != 0 {
                for k in 0..dim {
                    matrix[[i, k]] *= -1.0;
                }
            }
        }
    }

    /// Apply Hadamard gate
    fn apply_hadamard(&self, matrix: &mut Array2<Complex64>, target: usize, num_qubits: usize) {
        let target_bit = 1 << target;
        let dim = 1 << num_qubits;
        let inv_sqrt2 = 1.0 / std::f64::consts::SQRT_2;

        for i in 0..dim {
            if i & target_bit == 0 {
                let j = i | target_bit;
                for k in 0..dim {
                    let temp = matrix[[i, k]];
                    matrix[[i, k]] = inv_sqrt2 * (temp + matrix[[j, k]]);
                    matrix[[j, k]] = inv_sqrt2 * (temp - matrix[[j, k]]);
                }
            }
        }
    }

    /// Apply CNOT gate
    fn apply_cnot(
        &self,
        matrix: &mut Array2<Complex64>,
        control: usize,
        target: usize,
        num_qubits: usize,
    ) {
        let control_bit = 1 << control;
        let target_bit = 1 << target;
        let dim = 1 << num_qubits;

        for i in 0..dim {
            if i & control_bit != 0 && i & target_bit == 0 {
                let j = i | target_bit;
                for k in 0..dim {
                    let temp = matrix[[i, k]];
                    matrix[[i, k]] = matrix[[j, k]];
                    matrix[[j, k]] = temp;
                }
            }
        }
    }

    /// Aggregate multiple comparison results
    fn aggregate_results(&self, results: &[ComparisonResult]) -> (bool, f64, f64) {
        if results.is_empty() {
            return (false, 0.0, f64::INFINITY);
        }

        // Circuits are equivalent only if EVERY comparison method agrees.
        // A single dissenting result (equivalent=false) is enough to declare
        // non-equivalence, regardless of how confident the other methods are
        // in saying they *are* equivalent.  This prevents unreliable methods
        // (e.g. SVD singular-value comparison, which cannot distinguish
        // circuits with the same singular-value spectrum) from overriding
        // correct matrix-based comparisons.
        let all_equivalent = results.iter().all(|r| r.equivalent);
        let max_error = results.iter().map(|r| r.error_measure).fold(0.0, f64::max);

        // Confidence: for equivalent circuits take the minimum method confidence;
        // for non-equivalent circuits take the complement of the minimum error.
        let confidence = if all_equivalent {
            results.iter().map(|r| r.confidence).fold(1.0_f64, f64::min)
        } else {
            // Confidence in non-equivalence: comes from the method with the
            // largest error measure (most certain about difference).
            let max_conf_of_disagreeing = results
                .iter()
                .filter(|r| !r.equivalent)
                .map(|r| r.confidence)
                .fold(0.0_f64, f64::max);
            max_conf_of_disagreeing
        };

        (all_equivalent, confidence, max_error)
    }

    /// Detect circuit symmetries
    fn detect_circuit_symmetries(
        &self,
        circuit: &[crate::equivalence_checker::QuantumGate],
        num_qubits: usize,
    ) -> Result<Vec<String>, QuantRS2Error> {
        let mut symmetries = Vec::new();

        // Check for time-reversal symmetry
        if self.check_time_reversal_symmetry(circuit, num_qubits)? {
            symmetries.push("Time-reversal".to_string());
        }

        // Check for spatial symmetries (qubit permutations)
        let spatial_syms = self.check_spatial_symmetries(circuit, num_qubits)?;
        symmetries.extend(spatial_syms);

        // Check for phase symmetries
        if self.check_phase_symmetries(circuit, num_qubits)? {
            symmetries.push("Phase-invariant".to_string());
        }

        Ok(symmetries)
    }

    /// Extract global phase between circuits
    fn extract_global_phase(
        &self,
        circuit1: &[crate::equivalence_checker::QuantumGate],
        circuit2: &[crate::equivalence_checker::QuantumGate],
        num_qubits: usize,
    ) -> Result<Complex64, QuantRS2Error> {
        let matrix1 = self.compute_unitary_matrix(circuit1, num_qubits)?;
        let matrix2 = self.compute_unitary_matrix(circuit2, num_qubits)?;

        // Find first non-zero element
        let dim = 1 << num_qubits;
        for i in 0..dim {
            for j in 0..dim {
                if matrix1[[i, j]].norm() > self.config.tolerance_settings.absolute_tolerance
                    && matrix2[[i, j]].norm() > self.config.tolerance_settings.absolute_tolerance
                {
                    return Ok(matrix2[[i, j]] / matrix1[[i, j]]);
                }
            }
        }

        Ok(Complex64::new(1.0, 0.0))
    }

    // Helper methods for canonicalization
    fn apply_commutation_rules(
        &self,
        circuit: &mut [crate::equivalence_checker::QuantumGate],
    ) -> Result<bool, QuantRS2Error> {
        let mut changed = false;

        for i in 0..circuit.len().saturating_sub(1) {
            if self.gates_commute(&circuit[i], &circuit[i + 1]) {
                // Sort by some canonical order (e.g., gate type, then target qubits)
                if self.gate_priority(&circuit[i]) > self.gate_priority(&circuit[i + 1]) {
                    circuit.swap(i, i + 1);
                    changed = true;
                }
            }
        }

        Ok(changed)
    }

    const fn apply_gate_fusion(
        &self,
        circuit: &[crate::equivalence_checker::QuantumGate],
    ) -> Result<bool, QuantRS2Error> {
        // Simplified gate fusion - would be expanded in full implementation
        Ok(false)
    }

    fn apply_inverse_cancellation(
        &self,
        circuit: &mut Vec<crate::equivalence_checker::QuantumGate>,
    ) -> Result<bool, QuantRS2Error> {
        let mut changed = false;
        let mut i = 0;

        while i < circuit.len().saturating_sub(1) {
            if self.are_inverse_gates(&circuit[i], &circuit[i + 1]) {
                circuit.remove(i);
                circuit.remove(i);
                changed = true;
            } else {
                i += 1;
            }
        }

        Ok(changed)
    }

    const fn apply_phase_normalization(
        &self,
        circuit: &[crate::equivalence_checker::QuantumGate],
    ) -> Result<bool, QuantRS2Error> {
        // Simplified phase normalization
        Ok(false)
    }

    fn apply_canonical_ordering(&self, circuit: &mut [crate::equivalence_checker::QuantumGate]) {
        // Bubble-sort respecting commutativity: only swap adjacent gates that
        // are proven to commute (act on disjoint qubits).  When two gates
        // commute, put the one with the lower minimum qubit index first so
        // that the representation is canonical regardless of the original
        // insertion order.  This preserves circuit semantics for
        // non-commuting gates while creating a unique normal form for all
        // parallel (disjoint-qubit) pairs.
        let n = circuit.len();
        if n < 2 {
            return;
        }
        let mut swapped = true;
        while swapped {
            swapped = false;
            for i in 0..n - 1 {
                if self.gates_commute(&circuit[i], &circuit[i + 1]) {
                    let min_qubit_i = circuit[i]
                        .target_qubits()
                        .iter()
                        .chain(circuit[i].control_qubits().unwrap_or(&[]).iter())
                        .copied()
                        .min()
                        .unwrap_or(usize::MAX);
                    let min_qubit_next = circuit[i + 1]
                        .target_qubits()
                        .iter()
                        .chain(circuit[i + 1].control_qubits().unwrap_or(&[]).iter())
                        .copied()
                        .min()
                        .unwrap_or(usize::MAX);
                    // Secondary key: gate-type priority for equal qubit indices
                    let priority_i = self.gate_priority(&circuit[i]);
                    let priority_next = self.gate_priority(&circuit[i + 1]);
                    let should_swap = (min_qubit_i, priority_i) > (min_qubit_next, priority_next);
                    if should_swap {
                        circuit.swap(i, i + 1);
                        swapped = true;
                    }
                }
            }
        }
    }

    // Helper methods
    fn gates_commute(
        &self,
        gate1: &crate::equivalence_checker::QuantumGate,
        gate2: &crate::equivalence_checker::QuantumGate,
    ) -> bool {
        // Check if gates operate on disjoint qubits
        let qubits1: HashSet<_> = gate1
            .target_qubits()
            .iter()
            .chain(gate1.control_qubits().unwrap_or(&[]).iter())
            .collect();
        let qubits2: HashSet<_> = gate2
            .target_qubits()
            .iter()
            .chain(gate2.control_qubits().unwrap_or(&[]).iter())
            .collect();

        qubits1.is_disjoint(&qubits2)
    }

    const fn gate_priority(&self, gate: &crate::equivalence_checker::QuantumGate) -> u32 {
        match gate.gate_type() {
            GateType::X => 1,
            GateType::Y => 2,
            GateType::Z => 3,
            GateType::H => 4,
            GateType::CNOT => 10,
            _ => 100,
        }
    }

    fn are_inverse_gates(
        &self,
        gate1: &crate::equivalence_checker::QuantumGate,
        gate2: &crate::equivalence_checker::QuantumGate,
    ) -> bool {
        if gate1.target_qubits() != gate2.target_qubits() {
            return false;
        }

        match (gate1.gate_type(), gate2.gate_type()) {
            (GateType::X, GateType::X)
            | (GateType::Y, GateType::Y)
            | (GateType::Z, GateType::Z)
            | (GateType::H, GateType::H) => true,
            (GateType::CNOT, GateType::CNOT) => gate1.control_qubits() == gate2.control_qubits(),
            _ => false,
        }
    }

    // Hashing utilities
    fn hash_circuit(&self, circuit: &[crate::equivalence_checker::QuantumGate]) -> Vec<u8> {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};

        let mut hasher = DefaultHasher::new();
        for gate in circuit {
            format!("{:?}", gate.gate_type()).hash(&mut hasher);
            gate.target_qubits().hash(&mut hasher);
            if let Some(controls) = gate.control_qubits() {
                controls.hash(&mut hasher);
            }
        }

        hasher.finish().to_le_bytes().to_vec()
    }

    fn hash_set(&self, set: &HashSet<usize>) -> u64 {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};

        let mut hasher = DefaultHasher::new();
        let mut sorted: Vec<_> = set.iter().collect();
        sorted.sort();
        for item in sorted {
            item.hash(&mut hasher);
        }

        hasher.finish()
    }

    const fn hash_parameters(&self, circuit: &[crate::equivalence_checker::QuantumGate]) -> u64 {
        // Placeholder - would hash parametric gate parameters
        0
    }

    fn hash_structure(&self, circuit: &[crate::equivalence_checker::QuantumGate]) -> u64 {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};

        let mut hasher = DefaultHasher::new();
        circuit.len().hash(&mut hasher);

        // Hash gate types and targets in order to capture structure
        for (i, gate) in circuit.iter().enumerate() {
            i.hash(&mut hasher);
            format!("{:?}", gate.gate_type()).hash(&mut hasher);
            gate.target_qubits().hash(&mut hasher);
            if let Some(controls) = gate.control_qubits() {
                controls.hash(&mut hasher);
            }
        }

        hasher.finish()
    }

    // Symmetry checking methods
    const fn check_time_reversal_symmetry(
        &self,
        _circuit: &[crate::equivalence_checker::QuantumGate],
        _num_qubits: usize,
    ) -> Result<bool, QuantRS2Error> {
        // Placeholder implementation
        Ok(false)
    }

    const fn check_spatial_symmetries(
        &self,
        _circuit: &[crate::equivalence_checker::QuantumGate],
        _num_qubits: usize,
    ) -> Result<Vec<String>, QuantRS2Error> {
        // Placeholder implementation
        Ok(vec![])
    }

    const fn check_phase_symmetries(
        &self,
        _circuit: &[crate::equivalence_checker::QuantumGate],
        _num_qubits: usize,
    ) -> Result<bool, QuantRS2Error> {
        // Placeholder implementation
        Ok(false)
    }
}

/// Result of a single comparison method
#[derive(Debug, Clone)]
struct ComparisonResult {
    /// Whether circuits are equivalent according to this method
    pub equivalent: bool,
    /// Numerical error measure
    pub error_measure: f64,
    /// Confidence in the result (0.0 to 1.0)
    pub confidence: f64,
}

/// Comprehensive result of advanced equivalence checking
#[derive(Debug, Clone)]
pub struct AdvancedEquivalenceResult {
    /// Overall equivalence determination
    pub equivalent: bool,
    /// Confidence in the equivalence (0.0 to 1.0)
    pub confidence: f64,
    /// List of comparison methods used
    pub comparison_methods_used: Vec<String>,
    /// Maximum numerical error across all methods
    pub numerical_error: f64,
    /// Global phase factor if circuits are equivalent up to phase
    pub phase_factor: Option<Complex64>,
    /// Whether canonical forms were computed
    pub canonical_forms_computed: bool,
    /// Detected symmetries in the circuits
    pub symmetries_detected: Vec<String>,
    /// Performance metrics
    pub performance_metrics: PerformanceMetrics,
}

/// Performance metrics for equivalence checking
#[derive(Debug, Clone, Default)]
pub struct PerformanceMetrics {
    /// Time spent in matrix computation (ms)
    pub matrix_computation_time: f64,
    /// Time spent in comparison algorithms (ms)
    pub comparison_time: f64,
    /// Time spent in canonicalization (ms)
    pub canonicalization_time: f64,
    /// Memory peak usage (MB)
    pub peak_memory_usage: f64,
    /// Number of cache hits
    pub cache_hits: usize,
    /// Number of cache misses
    pub cache_misses: usize,
}

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

    #[test]
    fn test_advanced_equivalence_basic() {
        let mut checker = AdvancedEquivalenceChecker::new();

        let circuit1 = vec![
            QuantumGate::new(GateType::H, vec![0], None),
            QuantumGate::new(GateType::X, vec![0], None),
        ];

        let circuit2 = vec![
            QuantumGate::new(GateType::X, vec![0], None),
            QuantumGate::new(GateType::H, vec![0], None),
        ];

        let result = checker
            .comprehensive_equivalence_check(&circuit1, &circuit2, 1)
            .expect("Failed to perform comprehensive equivalence check");
        assert!(!result.equivalent); // H and X don't commute
    }

    #[test]
    fn test_fingerprint_matching() {
        let mut checker = AdvancedEquivalenceChecker::new();

        let circuit = vec![
            QuantumGate::new(GateType::H, vec![0], None),
            QuantumGate::new(GateType::CNOT, vec![0, 1], None),
        ];

        let fp1 = checker
            .compute_fingerprint(&circuit)
            .expect("Failed to compute fingerprint 1");
        let fp2 = checker
            .compute_fingerprint(&circuit)
            .expect("Failed to compute fingerprint 2");

        assert_eq!(fp1, fp2);
    }

    #[test]
    fn test_svd_based_comparison() {
        let checker = AdvancedEquivalenceChecker::new();

        let circuit1 = vec![QuantumGate::new(GateType::X, vec![0], None)];
        let circuit2 = vec![QuantumGate::new(GateType::X, vec![0], None)];

        let result = checker
            .svd_based_comparison(&circuit1, &circuit2, 1)
            .expect("Failed to perform SVD-based comparison");
        assert!(result.equivalent);
        assert!(result.error_measure < 1e-10);
    }

    #[test]
    fn test_canonicalization() {
        let mut checker = AdvancedEquivalenceChecker::new();

        // Two X gates should cancel
        let circuit = vec![
            QuantumGate::new(GateType::X, vec![0], None),
            QuantumGate::new(GateType::X, vec![0], None),
        ];

        let canonical = checker
            .canonicalize_circuit(&circuit, 1)
            .expect("Failed to canonicalize circuit");
        assert_eq!(canonical.len(), 0); // Should be empty after cancellation
    }

    #[test]
    fn test_commutation_ordering() {
        let mut checker = AdvancedEquivalenceChecker::new();

        // Gates on different qubits commute
        let circuit = vec![
            QuantumGate::new(GateType::X, vec![1], None),
            QuantumGate::new(GateType::Z, vec![0], None),
        ];

        let mut canonical = circuit.clone();
        checker.apply_canonical_ordering(&mut canonical);

        // Should be reordered by gate priority
        assert_eq!(canonical[0].gate_type(), &GateType::Z);
        assert_eq!(canonical[1].gate_type(), &GateType::X);
    }
}