quantrs2-sim 0.1.3

Quantum circuit simulators for the QuantRS2 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
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
//! Quantum supremacy verification algorithms and benchmarks.
//!
//! This module implements various algorithms and statistical tests for verifying
//! quantum supremacy claims, including cross-entropy benchmarking, Porter-Thomas
//! distribution analysis, and linear cross-entropy benchmarking (Linear XEB).

use scirs2_core::ndarray::Array1;
use scirs2_core::random::prelude::*;
use scirs2_core::random::ChaCha8Rng;
use scirs2_core::random::{RngExt, SeedableRng};
use scirs2_core::Complex64;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::f64::consts::PI;

use crate::error::{Result, SimulatorError};
use crate::scirs2_integration::SciRS2Backend;

/// Cross-entropy benchmarking result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CrossEntropyResult {
    /// Linear cross-entropy benchmarking (XEB) fidelity
    pub linear_xeb_fidelity: f64,
    /// Cross-entropy difference
    pub cross_entropy_difference: f64,
    /// Number of samples used
    pub num_samples: usize,
    /// Statistical confidence (p-value)
    pub confidence: f64,
    /// Porter-Thomas test results
    pub porter_thomas: PorterThomasResult,
    /// Heavy output generation (HOG) score
    pub hog_score: f64,
    /// Computational cost comparison
    pub cost_comparison: CostComparison,
}

/// Porter-Thomas distribution analysis
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PorterThomasResult {
    /// Chi-squared statistic
    pub chi_squared: f64,
    /// Degrees of freedom
    pub degrees_freedom: usize,
    /// P-value of the test
    pub p_value: f64,
    /// Whether distribution matches Porter-Thomas
    pub is_porter_thomas: bool,
    /// Kolmogorov-Smirnov test statistic
    pub ks_statistic: f64,
    /// Mean of the distribution
    pub mean: f64,
    /// Variance of the distribution
    pub variance: f64,
}

/// Heavy Output Generation analysis
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HOGAnalysis {
    /// Fraction of heavy outputs
    pub heavy_fraction: f64,
    /// Expected heavy fraction for random circuit
    pub expected_heavy_fraction: f64,
    /// Threshold for heavy outputs
    pub threshold: f64,
    /// Total outputs analyzed
    pub total_outputs: usize,
    /// Heavy outputs count
    pub heavy_count: usize,
}

/// Computational cost comparison
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CostComparison {
    /// Classical simulation time (seconds)
    pub classical_time: f64,
    /// Quantum execution time estimate (seconds)
    pub quantum_time: f64,
    /// Memory usage for classical simulation (bytes)
    pub classical_memory: usize,
    /// Speedup factor
    pub speedup_factor: f64,
    /// Number of operations
    pub operation_count: usize,
}

/// Quantum supremacy verifier
pub struct QuantumSupremacyVerifier {
    /// Number of qubits
    num_qubits: usize,
    /// Random number generator
    rng: ChaCha8Rng,
    /// `SciRS2` backend for optimization
    backend: Option<SciRS2Backend>,
    /// Verification parameters
    params: VerificationParams,
}

/// Parameters for quantum supremacy verification
#[derive(Debug, Clone)]
pub struct VerificationParams {
    /// Number of random circuits to test
    pub num_circuits: usize,
    /// Number of samples per circuit
    pub samples_per_circuit: usize,
    /// Circuit depth
    pub circuit_depth: usize,
    /// Gate set to use
    pub gate_set: GateSet,
    /// Significance level for statistical tests
    pub significance_level: f64,
    /// Porter-Thomas test bins
    pub pt_bins: usize,
    /// Heavy output threshold percentile
    pub heavy_threshold_percentile: f64,
}

/// Gate set for random circuit generation
#[derive(Debug, Clone)]
pub enum GateSet {
    /// Sycamore-like gate set (√X, √Y, √W, CZ)
    Sycamore,
    /// Google's quantum supremacy gate set
    GoogleSupremacy,
    /// Universal gate set (H, T, CNOT)
    Universal,
    /// IBM-like gate set (RZ, SX, CNOT)
    IBM,
    /// Custom gate set
    Custom(Vec<String>),
}

impl Default for VerificationParams {
    fn default() -> Self {
        Self {
            num_circuits: 100,
            samples_per_circuit: 1000,
            circuit_depth: 20,
            gate_set: GateSet::Sycamore,
            significance_level: 0.05,
            pt_bins: 100,
            heavy_threshold_percentile: 50.0,
        }
    }
}

impl QuantumSupremacyVerifier {
    /// Create new quantum supremacy verifier
    pub fn new(num_qubits: usize, params: VerificationParams) -> Result<Self> {
        Ok(Self {
            num_qubits,
            rng: ChaCha8Rng::from_rng(&mut thread_rng()),
            backend: None,
            params,
        })
    }

    /// Initialize with `SciRS2` backend
    pub fn with_scirs2_backend(mut self) -> Result<Self> {
        self.backend = Some(SciRS2Backend::new());
        Ok(self)
    }

    /// Set random seed for reproducibility
    #[must_use]
    pub fn with_seed(mut self, seed: u64) -> Self {
        self.rng = ChaCha8Rng::seed_from_u64(seed);
        self
    }

    /// Perform comprehensive quantum supremacy verification
    pub fn verify_quantum_supremacy(&mut self) -> Result<CrossEntropyResult> {
        let start_time = std::time::Instant::now();

        // Generate random quantum circuits
        let circuits = self.generate_random_circuits()?;

        // Compute ideal amplitudes (classical simulation)
        let ideal_amplitudes = self.compute_ideal_amplitudes(&circuits)?;

        // Simulate quantum sampling using ideal state amplitudes as the probability distribution
        let quantum_samples = self.simulate_quantum_sampling(&ideal_amplitudes)?;

        // Perform cross-entropy benchmarking
        let linear_xeb = self.compute_linear_xeb(&ideal_amplitudes, &quantum_samples)?;

        // Analyze Porter-Thomas distribution
        let porter_thomas = self.analyze_porter_thomas(&ideal_amplitudes)?;

        // Compute Heavy Output Generation score
        let hog_score = self.compute_hog_score(&ideal_amplitudes, &quantum_samples)?;

        // Cross-entropy difference
        let cross_entropy_diff =
            self.compute_cross_entropy_difference(&ideal_amplitudes, &quantum_samples)?;

        // Statistical confidence
        let confidence =
            self.compute_statistical_confidence(&ideal_amplitudes, &quantum_samples)?;

        let classical_time = start_time.elapsed().as_secs_f64();

        // Cost comparison
        let cost_comparison = CostComparison {
            classical_time,
            quantum_time: self.estimate_quantum_time()?,
            classical_memory: self.estimate_classical_memory(),
            speedup_factor: classical_time / self.estimate_quantum_time()?,
            operation_count: circuits.len() * self.params.circuit_depth,
        };

        Ok(CrossEntropyResult {
            linear_xeb_fidelity: linear_xeb,
            cross_entropy_difference: cross_entropy_diff,
            num_samples: self.params.samples_per_circuit,
            confidence,
            porter_thomas,
            hog_score,
            cost_comparison,
        })
    }

    /// Generate random quantum circuits
    fn generate_random_circuits(&mut self) -> Result<Vec<RandomCircuit>> {
        let mut circuits = Vec::with_capacity(self.params.num_circuits);

        for _ in 0..self.params.num_circuits {
            let circuit = self.generate_single_random_circuit()?;
            circuits.push(circuit);
        }

        Ok(circuits)
    }

    /// Generate a single random circuit
    fn generate_single_random_circuit(&mut self) -> Result<RandomCircuit> {
        let mut layers = Vec::with_capacity(self.params.circuit_depth);

        for layer_idx in 0..self.params.circuit_depth {
            let layer = match &self.params.gate_set {
                GateSet::Sycamore => self.generate_sycamore_layer(layer_idx)?,
                GateSet::GoogleSupremacy => self.generate_google_supremacy_layer(layer_idx)?,
                GateSet::Universal => self.generate_universal_layer(layer_idx)?,
                GateSet::IBM => self.generate_ibm_layer(layer_idx)?,
                GateSet::Custom(gates) => {
                    let gates_clone = gates.clone();
                    self.generate_custom_layer(layer_idx, &gates_clone)?
                }
            };
            layers.push(layer);
        }

        Ok(RandomCircuit {
            num_qubits: self.num_qubits,
            layers,
            measurement_pattern: self.generate_measurement_pattern(),
        })
    }

    /// Generate Sycamore-style layer
    fn generate_sycamore_layer(&mut self, layer_idx: usize) -> Result<CircuitLayer> {
        let mut gates = Vec::new();

        // Single-qubit gates
        for qubit in 0..self.num_qubits {
            let gate_type = match self.rng.random_range(0..3) {
                0 => "SqrtX",
                1 => "SqrtY",
                _ => "SqrtW",
            };

            gates.push(QuantumGate {
                gate_type: gate_type.to_string(),
                qubits: vec![qubit],
                parameters: vec![],
            });
        }

        // Two-qubit gates (CZ gates with connectivity pattern)
        let offset = layer_idx % 2;
        for row in 0..((self.num_qubits as f64).sqrt() as usize) {
            for col in (offset..((self.num_qubits as f64).sqrt() as usize)).step_by(2) {
                let qubit1 = row * ((self.num_qubits as f64).sqrt() as usize) + col;
                let qubit2 = qubit1 + 1;

                if qubit2 < self.num_qubits {
                    gates.push(QuantumGate {
                        gate_type: "CZ".to_string(),
                        qubits: vec![qubit1, qubit2],
                        parameters: vec![],
                    });
                }
            }
        }

        Ok(CircuitLayer { gates })
    }

    /// Generate Google quantum supremacy layer
    fn generate_google_supremacy_layer(&mut self, layer_idx: usize) -> Result<CircuitLayer> {
        // Similar to Sycamore but with specific gate rotations
        self.generate_sycamore_layer(layer_idx)
    }

    /// Generate universal gate set layer
    fn generate_universal_layer(&mut self, _layer_idx: usize) -> Result<CircuitLayer> {
        let mut gates = Vec::new();

        // Random single-qubit gates
        for qubit in 0..self.num_qubits {
            let gate_type = match self.rng.random_range(0..3) {
                0 => "H",
                1 => "T",
                _ => "S",
            };

            gates.push(QuantumGate {
                gate_type: gate_type.to_string(),
                qubits: vec![qubit],
                parameters: vec![],
            });
        }

        // Random CNOT gates
        let num_cnots = self.rng.random_range(1..=self.num_qubits / 2);
        for _ in 0..num_cnots {
            let control = self.rng.random_range(0..self.num_qubits);
            let target = self.rng.random_range(0..self.num_qubits);

            if control != target {
                gates.push(QuantumGate {
                    gate_type: "CNOT".to_string(),
                    qubits: vec![control, target],
                    parameters: vec![],
                });
            }
        }

        Ok(CircuitLayer { gates })
    }

    /// Generate IBM gate set layer
    fn generate_ibm_layer(&mut self, _layer_idx: usize) -> Result<CircuitLayer> {
        let mut gates = Vec::new();

        // RZ and SX gates
        for qubit in 0..self.num_qubits {
            // Random RZ rotation
            let angle = self.rng.random::<f64>() * 2.0 * PI;
            gates.push(QuantumGate {
                gate_type: "RZ".to_string(),
                qubits: vec![qubit],
                parameters: vec![angle],
            });

            // SX gate with probability 0.5
            if self.rng.random::<bool>() {
                gates.push(QuantumGate {
                    gate_type: "SX".to_string(),
                    qubits: vec![qubit],
                    parameters: vec![],
                });
            }
        }

        Ok(CircuitLayer { gates })
    }

    /// Generate custom gate set layer
    const fn generate_custom_layer(
        &self,
        _layer_idx: usize,
        _gates: &[String],
    ) -> Result<CircuitLayer> {
        // Implement custom gate generation
        Ok(CircuitLayer { gates: Vec::new() })
    }

    /// Generate measurement pattern
    fn generate_measurement_pattern(&self) -> Vec<usize> {
        // For now, measure all qubits in computational basis
        (0..self.num_qubits).collect()
    }

    /// Compute ideal amplitudes using classical state-vector simulation
    fn compute_ideal_amplitudes(
        &self,
        circuits: &[RandomCircuit],
    ) -> Result<Vec<Array1<Complex64>>> {
        let mut amplitudes = Vec::with_capacity(circuits.len());

        for circuit in circuits {
            let dim = 1usize << self.num_qubits;
            // Initialise to |0...0⟩
            let mut state = vec![Complex64::new(0.0, 0.0); dim];
            state[0] = Complex64::new(1.0, 0.0);

            // Apply circuit layers
            for layer in &circuit.layers {
                for gate in &layer.gates {
                    self.apply_gate_to_state(&mut state, gate)?;
                }
            }

            let final_state = Array1::from_vec(state);
            amplitudes.push(final_state);
        }

        Ok(amplitudes)
    }

    /// Apply a single gate to a raw state-vector slice.
    ///
    /// All gate matrices are given in the standard computational-basis order.
    fn apply_gate_to_state(&self, state: &mut Vec<Complex64>, gate: &QuantumGate) -> Result<()> {
        let n = self.num_qubits;
        let dim = state.len();

        /// Apply a 2×2 single-qubit gate matrix `m` (row-major, len 4) to `state`
        /// at `target_bit` (0 = least-significant qubit).
        fn apply_1q(state: &mut [Complex64], m: &[Complex64; 4], target_bit: usize, dim: usize) {
            for i in 0..dim {
                if (i >> target_bit) & 1 == 0 {
                    let j = i | (1 << target_bit);
                    let a = state[i];
                    let b = state[j];
                    state[i] = m[0] * a + m[1] * b;
                    state[j] = m[2] * a + m[3] * b;
                }
            }
        }

        /// Apply a 4×4 two-qubit gate matrix `m` (row-major, len 16) to `state`
        /// for (`ctrl_bit`, `tgt_bit`).  The matrix is ordered |00⟩,|01⟩,|10⟩,|11⟩
        /// where the first index is `ctrl_bit` and the second is `tgt_bit`.
        fn apply_2q(
            state: &mut [Complex64],
            m: &[Complex64; 16],
            ctrl_bit: usize,
            tgt_bit: usize,
            dim: usize,
        ) {
            for i in 0..dim {
                // Only process the "00" representative of each 4-element group
                if (i >> ctrl_bit) & 1 == 0 && (i >> tgt_bit) & 1 == 0 {
                    let i00 = i;
                    let i01 = i | (1 << tgt_bit);
                    let i10 = i | (1 << ctrl_bit);
                    let i11 = i | (1 << ctrl_bit) | (1 << tgt_bit);
                    let s00 = state[i00];
                    let s01 = state[i01];
                    let s10 = state[i10];
                    let s11 = state[i11];
                    state[i00] = m[0] * s00 + m[1] * s01 + m[2] * s10 + m[3] * s11;
                    state[i01] = m[4] * s00 + m[5] * s01 + m[6] * s10 + m[7] * s11;
                    state[i10] = m[8] * s00 + m[9] * s01 + m[10] * s10 + m[11] * s11;
                    state[i11] = m[12] * s00 + m[13] * s01 + m[14] * s10 + m[15] * s11;
                }
            }
        }

        match gate.gate_type.as_str() {
            // ─── single-qubit gates ───────────────────────────────────────
            "H" => {
                let q = *gate.qubits.first().ok_or_else(|| {
                    SimulatorError::InvalidInput("H gate requires a qubit argument".to_string())
                })?;
                if q >= n {
                    return Err(SimulatorError::InvalidInput(format!(
                        "Qubit index {q} out of range ({n} qubits)"
                    )));
                }
                let f = std::f64::consts::FRAC_1_SQRT_2;
                let c = Complex64::new(f, 0.0);
                let m = [c, c, c, -c];
                apply_1q(state, &m, q, dim);
            }
            "X" | "PauliX" => {
                let q = *gate.qubits.first().ok_or_else(|| {
                    SimulatorError::InvalidInput("X gate requires a qubit argument".to_string())
                })?;
                if q >= n {
                    return Err(SimulatorError::InvalidInput(format!(
                        "Qubit index {q} out of range ({n} qubits)"
                    )));
                }
                let m = [
                    Complex64::new(0.0, 0.0),
                    Complex64::new(1.0, 0.0),
                    Complex64::new(1.0, 0.0),
                    Complex64::new(0.0, 0.0),
                ];
                apply_1q(state, &m, q, dim);
            }
            "Y" | "PauliY" => {
                let q = *gate.qubits.first().ok_or_else(|| {
                    SimulatorError::InvalidInput("Y gate requires a qubit argument".to_string())
                })?;
                if q >= n {
                    return Err(SimulatorError::InvalidInput(format!(
                        "Qubit index {q} out of range ({n} qubits)"
                    )));
                }
                let m = [
                    Complex64::new(0.0, 0.0),
                    Complex64::new(0.0, -1.0),
                    Complex64::new(0.0, 1.0),
                    Complex64::new(0.0, 0.0),
                ];
                apply_1q(state, &m, q, dim);
            }
            "Z" | "PauliZ" => {
                let q = *gate.qubits.first().ok_or_else(|| {
                    SimulatorError::InvalidInput("Z gate requires a qubit argument".to_string())
                })?;
                if q >= n {
                    return Err(SimulatorError::InvalidInput(format!(
                        "Qubit index {q} out of range ({n} qubits)"
                    )));
                }
                let m = [
                    Complex64::new(1.0, 0.0),
                    Complex64::new(0.0, 0.0),
                    Complex64::new(0.0, 0.0),
                    Complex64::new(-1.0, 0.0),
                ];
                apply_1q(state, &m, q, dim);
            }
            "S" => {
                let q = *gate.qubits.first().ok_or_else(|| {
                    SimulatorError::InvalidInput("S gate requires a qubit argument".to_string())
                })?;
                if q >= n {
                    return Err(SimulatorError::InvalidInput(format!(
                        "Qubit index {q} out of range ({n} qubits)"
                    )));
                }
                let m = [
                    Complex64::new(1.0, 0.0),
                    Complex64::new(0.0, 0.0),
                    Complex64::new(0.0, 0.0),
                    Complex64::new(0.0, 1.0),
                ];
                apply_1q(state, &m, q, dim);
            }
            "T" => {
                let q = *gate.qubits.first().ok_or_else(|| {
                    SimulatorError::InvalidInput("T gate requires a qubit argument".to_string())
                })?;
                if q >= n {
                    return Err(SimulatorError::InvalidInput(format!(
                        "Qubit index {q} out of range ({n} qubits)"
                    )));
                }
                let f = std::f64::consts::FRAC_1_SQRT_2;
                let m = [
                    Complex64::new(1.0, 0.0),
                    Complex64::new(0.0, 0.0),
                    Complex64::new(0.0, 0.0),
                    Complex64::new(f, f),
                ];
                apply_1q(state, &m, q, dim);
            }
            "SX" | "SqrtX" => {
                // √X = ½ [[1+i, 1-i], [1-i, 1+i]]
                let q = *gate.qubits.first().ok_or_else(|| {
                    SimulatorError::InvalidInput("SX gate requires a qubit argument".to_string())
                })?;
                if q >= n {
                    return Err(SimulatorError::InvalidInput(format!(
                        "Qubit index {q} out of range ({n} qubits)"
                    )));
                }
                let pp = Complex64::new(0.5, 0.5);
                let pm = Complex64::new(0.5, -0.5);
                let m = [pp, pm, pm, pp];
                apply_1q(state, &m, q, dim);
            }
            "SqrtY" => {
                // √Y = ½ [[1+i, -1-i], [1+i,  1+i]]
                let q = *gate.qubits.first().ok_or_else(|| {
                    SimulatorError::InvalidInput("SqrtY gate requires a qubit argument".to_string())
                })?;
                if q >= n {
                    return Err(SimulatorError::InvalidInput(format!(
                        "Qubit index {q} out of range ({n} qubits)"
                    )));
                }
                let pp = Complex64::new(0.5, 0.5);
                let nm = Complex64::new(-0.5, -0.5);
                let m = [pp, nm, pp, pp];
                apply_1q(state, &m, q, dim);
            }
            "SqrtW" => {
                // √W where W = (X+Y)/√2; matrix = [[cos(π/4), -i·sin(π/4)·e^(-iπ/4)], [i·sin(π/4)·e^(iπ/4), cos(π/4)]]
                // A common definition for √W used in Sycamore benchmarking:
                // √W = [[1, -√(i)/√2], [√(-i)/√2, 1]] / √2, simplified to a unitary below.
                let q = *gate.qubits.first().ok_or_else(|| {
                    SimulatorError::InvalidInput("SqrtW gate requires a qubit argument".to_string())
                })?;
                if q >= n {
                    return Err(SimulatorError::InvalidInput(format!(
                        "Qubit index {q} out of range ({n} qubits)"
                    )));
                }
                // Use: W = (X+Y)/√2, so W matrix = 1/√2 * [[0,1-i],[1+i,0]]
                // √W unitary (one principal square root):
                let f = 0.5_f64;
                let m = [
                    Complex64::new(f, f),
                    Complex64::new(f, -f),
                    Complex64::new(f, f),
                    Complex64::new(-f, f),
                ];
                apply_1q(state, &m, q, dim);
            }
            "RZ" => {
                let q = *gate.qubits.first().ok_or_else(|| {
                    SimulatorError::InvalidInput("RZ gate requires a qubit argument".to_string())
                })?;
                if q >= n {
                    return Err(SimulatorError::InvalidInput(format!(
                        "Qubit index {q} out of range ({n} qubits)"
                    )));
                }
                let angle = gate.parameters.first().copied().unwrap_or(0.0);
                // RZ(θ) = [[e^(-iθ/2), 0], [0, e^(iθ/2)]]
                let half = angle / 2.0;
                let m = [
                    Complex64::new((-half).cos(), (-half).sin()),
                    Complex64::new(0.0, 0.0),
                    Complex64::new(0.0, 0.0),
                    Complex64::new(half.cos(), half.sin()),
                ];
                apply_1q(state, &m, q, dim);
            }
            "RX" => {
                let q = *gate.qubits.first().ok_or_else(|| {
                    SimulatorError::InvalidInput("RX gate requires a qubit argument".to_string())
                })?;
                if q >= n {
                    return Err(SimulatorError::InvalidInput(format!(
                        "Qubit index {q} out of range ({n} qubits)"
                    )));
                }
                let angle = gate.parameters.first().copied().unwrap_or(0.0);
                let half = angle / 2.0;
                let c = half.cos();
                let s = half.sin();
                let m = [
                    Complex64::new(c, 0.0),
                    Complex64::new(0.0, -s),
                    Complex64::new(0.0, -s),
                    Complex64::new(c, 0.0),
                ];
                apply_1q(state, &m, q, dim);
            }
            "RY" => {
                let q = *gate.qubits.first().ok_or_else(|| {
                    SimulatorError::InvalidInput("RY gate requires a qubit argument".to_string())
                })?;
                if q >= n {
                    return Err(SimulatorError::InvalidInput(format!(
                        "Qubit index {q} out of range ({n} qubits)"
                    )));
                }
                let angle = gate.parameters.first().copied().unwrap_or(0.0);
                let half = angle / 2.0;
                let c = half.cos();
                let s = half.sin();
                let m = [
                    Complex64::new(c, 0.0),
                    Complex64::new(-s, 0.0),
                    Complex64::new(s, 0.0),
                    Complex64::new(c, 0.0),
                ];
                apply_1q(state, &m, q, dim);
            }
            // ─── two-qubit gates ──────────────────────────────────────────
            "CNOT" | "CX" => {
                if gate.qubits.len() < 2 {
                    return Err(SimulatorError::InvalidInput(
                        "CNOT gate requires 2 qubit arguments".to_string(),
                    ));
                }
                let ctrl = gate.qubits[0];
                let tgt = gate.qubits[1];
                if ctrl >= n || tgt >= n {
                    return Err(SimulatorError::InvalidInput(format!(
                        "Qubit index out of range ({n} qubits)"
                    )));
                }
                // CNOT matrix |ctrl,tgt⟩: [[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]]
                let o = Complex64::new(0.0, 0.0);
                let l = Complex64::new(1.0, 0.0);
                let m: [Complex64; 16] = [l, o, o, o, o, l, o, o, o, o, o, l, o, o, l, o];
                apply_2q(state, &m, ctrl, tgt, dim);
            }
            "CZ" => {
                if gate.qubits.len() < 2 {
                    return Err(SimulatorError::InvalidInput(
                        "CZ gate requires 2 qubit arguments".to_string(),
                    ));
                }
                let ctrl = gate.qubits[0];
                let tgt = gate.qubits[1];
                if ctrl >= n || tgt >= n {
                    return Err(SimulatorError::InvalidInput(format!(
                        "Qubit index out of range ({n} qubits)"
                    )));
                }
                // CZ: flip phase of |11⟩ component
                let mask = (1 << ctrl) | (1 << tgt);
                for i in 0..dim {
                    if (i & mask) == mask {
                        state[i] = -state[i];
                    }
                }
            }
            // Unknown / custom gates: skip silently (no-op) to allow custom gate sets
            _ => {}
        }

        Ok(())
    }

    /// Simulate quantum sampling using precomputed ideal state amplitudes.
    ///
    /// For each circuit's amplitude vector we build a cumulative-probability
    /// table and draw `samples_per_circuit` bitstrings from it, faithfully
    /// mirroring the quantum probability distribution obtained by the classical
    /// state-vector simulation.
    fn simulate_quantum_sampling(
        &mut self,
        ideal_amplitudes: &[Array1<Complex64>],
    ) -> Result<Vec<Vec<Vec<u8>>>> {
        let mut all_samples = Vec::with_capacity(ideal_amplitudes.len());

        for amplitudes in ideal_amplitudes {
            let samples = self.sample_from_amplitudes(amplitudes)?;
            all_samples.push(samples);
        }

        Ok(all_samples)
    }

    /// Draw `samples_per_circuit` bitstrings from a state-amplitude vector
    /// using inverse-CDF (alias-free) sampling.
    fn sample_from_amplitudes(&mut self, amplitudes: &Array1<Complex64>) -> Result<Vec<Vec<u8>>> {
        let dim = amplitudes.len();
        let n = self.num_qubits;

        // Build probability distribution from |amplitude|²
        let mut probs: Vec<f64> = amplitudes.iter().map(|a| a.norm_sqr()).collect();

        // Normalise to guard against accumulated floating-point drift
        let total: f64 = probs.iter().sum();
        if total <= 0.0 {
            return Err(SimulatorError::InvalidInput(
                "State vector has zero norm — cannot sample".to_string(),
            ));
        }
        for p in &mut probs {
            *p /= total;
        }

        // Build cumulative distribution (CDF)
        let mut cdf = Vec::with_capacity(dim);
        let mut running = 0.0_f64;
        for p in &probs {
            running += p;
            cdf.push(running);
        }

        // Sample `samples_per_circuit` bitstrings via binary search on CDF
        let mut samples = Vec::with_capacity(self.params.samples_per_circuit);
        for _ in 0..self.params.samples_per_circuit {
            let u: f64 = self.rng.random();
            // Binary-search for the first CDF entry >= u
            let outcome = cdf.partition_point(|&c| c < u).min(dim - 1);

            // Convert outcome index to a per-qubit bitstring (MSB first)
            let mut bitstring = Vec::with_capacity(n);
            for q in (0..n).rev() {
                bitstring.push(((outcome >> q) & 1) as u8);
            }
            samples.push(bitstring);
        }

        Ok(samples)
    }

    /// Compute Linear Cross-Entropy Benchmarking (XEB) fidelity
    fn compute_linear_xeb(
        &self,
        ideal_amplitudes: &[Array1<Complex64>],
        quantum_samples: &[Vec<Vec<u8>>],
    ) -> Result<f64> {
        let mut total_fidelity = 0.0;

        for (amplitudes, samples) in ideal_amplitudes.iter().zip(quantum_samples.iter()) {
            let circuit_fidelity = self.compute_circuit_linear_xeb(amplitudes, samples)?;
            total_fidelity += circuit_fidelity;
        }

        Ok(total_fidelity / ideal_amplitudes.len() as f64)
    }

    /// Compute linear XEB for a single circuit
    fn compute_circuit_linear_xeb(
        &self,
        amplitudes: &Array1<Complex64>,
        samples: &[Vec<u8>],
    ) -> Result<f64> {
        let dim = amplitudes.len();
        let uniform_prob = 1.0 / dim as f64;

        let mut sum_probs = 0.0;

        for sample in samples {
            let bitstring_index = self.bitstring_to_index(sample);
            if bitstring_index < dim {
                let prob = amplitudes[bitstring_index].norm_sqr();
                sum_probs += prob;
            }
        }

        let mean_prob = sum_probs / samples.len() as f64;
        let linear_xeb = (mean_prob - uniform_prob) / uniform_prob;

        Ok(linear_xeb)
    }

    /// Convert bit string to state index
    fn bitstring_to_index(&self, bitstring: &[u8]) -> usize {
        let mut index = 0;
        for (i, &bit) in bitstring.iter().enumerate() {
            if bit == 1 {
                index |= 1 << (self.num_qubits - 1 - i);
            }
        }
        index
    }

    /// Analyze Porter-Thomas distribution
    fn analyze_porter_thomas(
        &self,
        ideal_amplitudes: &[Array1<Complex64>],
    ) -> Result<PorterThomasResult> {
        // Collect all probability amplitudes
        let mut all_probs = Vec::new();

        for amplitudes in ideal_amplitudes {
            for amplitude in amplitudes {
                all_probs.push(amplitude.norm_sqr());
            }
        }

        // Compute statistics
        let mean = all_probs.iter().sum::<f64>() / all_probs.len() as f64;
        let variance =
            all_probs.iter().map(|p| (p - mean).powi(2)).sum::<f64>() / all_probs.len() as f64;

        // Expected values for Porter-Thomas distribution
        let expected_mean = 1.0 / f64::from(1 << self.num_qubits);
        let expected_variance = expected_mean.powi(2);

        // Chi-squared test
        let bins = self.params.pt_bins;
        let mut observed = vec![0; bins];
        let mut expected = vec![0.0; bins];

        // Create histogram
        let max_prob = all_probs.iter().copied().fold(0.0f64, f64::max);
        for &prob in &all_probs {
            let bin = ((prob / max_prob) * (bins - 1) as f64) as usize;
            observed[bin.min(bins - 1)] += 1;
        }

        // Expected counts for Porter-Thomas
        let total_samples = all_probs.len() as f64;
        for i in 0..bins {
            let x = (i as f64 + 0.5) / bins as f64 * max_prob;
            // Porter-Thomas: p(P) = N * exp(-N*P) where N = 2^n
            let n = 1 << self.num_qubits;
            expected[i] = total_samples * f64::from(n) * (f64::from(-n) * x).exp() / bins as f64;
        }

        // Chi-squared statistic
        let mut chi_squared = 0.0;
        let mut degrees_freedom: usize = 0;

        for i in 0..bins {
            if expected[i] > 5.0 {
                // Only use bins with sufficient expected count
                chi_squared += (f64::from(observed[i]) - expected[i]).powi(2) / expected[i];
                degrees_freedom += 1;
            }
        }

        degrees_freedom = degrees_freedom.saturating_sub(1);

        // Approximate p-value (simplified)
        let p_value = self.chi_squared_p_value(chi_squared, degrees_freedom);

        // Kolmogorov-Smirnov test (simplified)
        let ks_statistic = self.kolmogorov_smirnov_test(&all_probs, expected_mean);

        Ok(PorterThomasResult {
            chi_squared,
            degrees_freedom,
            p_value,
            is_porter_thomas: p_value > self.params.significance_level,
            ks_statistic,
            mean,
            variance,
        })
    }

    /// Compute HOG (Heavy Output Generation) score
    fn compute_hog_score(
        &self,
        ideal_amplitudes: &[Array1<Complex64>],
        quantum_samples: &[Vec<Vec<u8>>],
    ) -> Result<f64> {
        let mut total_heavy_fraction = 0.0;

        for (amplitudes, samples) in ideal_amplitudes.iter().zip(quantum_samples.iter()) {
            let heavy_fraction = self.compute_circuit_hog_score(amplitudes, samples)?;
            total_heavy_fraction += heavy_fraction;
        }

        Ok(total_heavy_fraction / ideal_amplitudes.len() as f64)
    }

    /// Compute HOG score for single circuit
    fn compute_circuit_hog_score(
        &self,
        amplitudes: &Array1<Complex64>,
        samples: &[Vec<u8>],
    ) -> Result<f64> {
        // Find median probability
        let mut probs: Vec<f64> = amplitudes
            .iter()
            .map(scirs2_core::Complex::norm_sqr)
            .collect();
        probs.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
        let median_prob = probs[probs.len() / 2];

        // Count heavy outputs (above median)
        let mut heavy_count = 0;

        for sample in samples {
            let index = self.bitstring_to_index(sample);
            if index < amplitudes.len() {
                let prob = amplitudes[index].norm_sqr();
                if prob > median_prob {
                    heavy_count += 1;
                }
            }
        }

        Ok(f64::from(heavy_count) / samples.len() as f64)
    }

    /// Compute cross-entropy difference
    fn compute_cross_entropy_difference(
        &self,
        ideal_amplitudes: &[Array1<Complex64>],
        quantum_samples: &[Vec<Vec<u8>>],
    ) -> Result<f64> {
        let mut total_difference = 0.0;

        for (amplitudes, samples) in ideal_amplitudes.iter().zip(quantum_samples.iter()) {
            let difference = self.compute_circuit_cross_entropy(amplitudes, samples)?;
            total_difference += difference;
        }

        Ok(total_difference / ideal_amplitudes.len() as f64)
    }

    /// Compute cross-entropy for single circuit
    fn compute_circuit_cross_entropy(
        &self,
        amplitudes: &Array1<Complex64>,
        samples: &[Vec<u8>],
    ) -> Result<f64> {
        let dim = amplitudes.len();
        let uniform_entropy = (dim as f64).ln();

        let mut quantum_entropy = 0.0;
        let mut sample_counts = HashMap::new();

        // Count sample frequencies
        for sample in samples {
            *sample_counts.entry(sample.clone()).or_insert(0) += 1;
        }

        // Compute empirical entropy
        for count in sample_counts.values() {
            let prob = f64::from(*count) / samples.len() as f64;
            if prob > 0.0 {
                quantum_entropy -= prob * prob.ln();
            }
        }

        Ok(uniform_entropy - quantum_entropy)
    }

    /// Compute statistical confidence
    const fn compute_statistical_confidence(
        &self,
        _ideal_amplitudes: &[Array1<Complex64>],
        _quantum_samples: &[Vec<Vec<u8>>],
    ) -> Result<f64> {
        // Placeholder implementation
        Ok(0.95)
    }

    /// Estimate quantum execution time
    fn estimate_quantum_time(&self) -> Result<f64> {
        // Estimate based on gate count and typical gate times
        let gates_per_circuit = self.params.circuit_depth * self.num_qubits;
        let total_gates = gates_per_circuit * self.params.num_circuits;
        let gate_time = 100e-9; // 100 ns per gate
        let readout_time = 1e-6; // 1 μs readout

        Ok((total_gates as f64).mul_add(gate_time, self.params.num_circuits as f64 * readout_time))
    }

    /// Estimate classical memory usage
    const fn estimate_classical_memory(&self) -> usize {
        let state_size = (1 << self.num_qubits) * std::mem::size_of::<Complex64>();
        state_size * self.params.num_circuits
    }

    /// Simplified chi-squared p-value computation
    fn chi_squared_p_value(&self, chi_squared: f64, degrees_freedom: usize) -> f64 {
        // Very simplified approximation
        if degrees_freedom == 0 {
            return 1.0;
        }

        let expected = degrees_freedom as f64;
        if chi_squared < expected {
            0.95 // High p-value
        } else if chi_squared < 2.0 * expected {
            0.5 // Medium p-value
        } else {
            0.01 // Low p-value
        }
    }

    /// Kolmogorov-Smirnov test statistic
    fn kolmogorov_smirnov_test(&self, data: &[f64], expected_mean: f64) -> f64 {
        // Simplified implementation
        let n = data.len() as f64;
        let mut sorted_data = data.to_vec();
        sorted_data.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));

        let mut max_diff: f64 = 0.0;

        for (i, &value) in sorted_data.iter().enumerate() {
            let empirical_cdf = (i + 1) as f64 / n;
            let theoretical_cdf = 1.0 - (-value / expected_mean).exp(); // Exponential CDF
            let diff = (empirical_cdf - theoretical_cdf).abs();
            max_diff = max_diff.max(diff);
        }

        max_diff
    }
}

/// Random quantum circuit representation
#[derive(Debug, Clone)]
pub struct RandomCircuit {
    pub num_qubits: usize,
    pub layers: Vec<CircuitLayer>,
    pub measurement_pattern: Vec<usize>,
}

/// Layer of gates in a circuit
#[derive(Debug, Clone)]
pub struct CircuitLayer {
    pub gates: Vec<QuantumGate>,
}

/// Quantum gate representation
#[derive(Debug, Clone)]
pub struct QuantumGate {
    pub gate_type: String,
    pub qubits: Vec<usize>,
    pub parameters: Vec<f64>,
}

/// Benchmark quantum supremacy verification
pub fn benchmark_quantum_supremacy(num_qubits: usize) -> Result<CrossEntropyResult> {
    let params = VerificationParams {
        num_circuits: 10,
        samples_per_circuit: 100,
        circuit_depth: 10,
        ..Default::default()
    };

    let mut verifier = QuantumSupremacyVerifier::new(num_qubits, params)?;
    verifier.verify_quantum_supremacy()
}

/// Verify specific quantum supremacy claim
pub fn verify_supremacy_claim(
    num_qubits: usize,
    circuit_depth: usize,
    experimental_data: &[Vec<u8>],
) -> Result<CrossEntropyResult> {
    let params = VerificationParams {
        num_circuits: 1,
        samples_per_circuit: experimental_data.len(),
        circuit_depth,
        ..Default::default()
    };

    let mut verifier = QuantumSupremacyVerifier::new(num_qubits, params)?;

    // This would require the actual circuit that produced the experimental data
    // For now, return a placeholder result
    Ok(CrossEntropyResult {
        linear_xeb_fidelity: 0.0,
        cross_entropy_difference: 0.0,
        num_samples: experimental_data.len(),
        confidence: 0.0,
        porter_thomas: PorterThomasResult {
            chi_squared: 0.0,
            degrees_freedom: 0,
            p_value: 0.0,
            is_porter_thomas: false,
            ks_statistic: 0.0,
            mean: 0.0,
            variance: 0.0,
        },
        hog_score: 0.0,
        cost_comparison: CostComparison {
            classical_time: 0.0,
            quantum_time: 0.0,
            classical_memory: 0,
            speedup_factor: 0.0,
            operation_count: 0,
        },
    })
}

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

    #[test]
    fn test_verifier_creation() {
        let params = VerificationParams::default();
        let verifier = QuantumSupremacyVerifier::new(10, params);
        assert!(verifier.is_ok());
    }

    #[test]
    fn test_linear_xeb_calculation() {
        let mut verifier = QuantumSupremacyVerifier::new(3, VerificationParams::default())
            .expect("Failed to create verifier");

        // Create dummy data
        let amplitudes = Array1::from_vec(vec![
            Complex64::new(0.5, 0.0),
            Complex64::new(0.5, 0.0),
            Complex64::new(0.5, 0.0),
            Complex64::new(0.5, 0.0),
            Complex64::new(0.0, 0.0),
            Complex64::new(0.0, 0.0),
            Complex64::new(0.0, 0.0),
            Complex64::new(0.0, 0.0),
        ]);

        let samples = vec![vec![0, 0, 0], vec![0, 0, 1], vec![0, 1, 0], vec![0, 1, 1]];

        let xeb = verifier
            .compute_circuit_linear_xeb(&amplitudes, &samples)
            .expect("Failed to compute linear XEB");
        assert!(xeb >= 0.0);
    }

    #[test]
    fn test_bitstring_conversion() {
        let verifier = QuantumSupremacyVerifier::new(3, VerificationParams::default())
            .expect("Failed to create verifier");

        assert_eq!(verifier.bitstring_to_index(&[0, 0, 0]), 0);
        assert_eq!(verifier.bitstring_to_index(&[0, 0, 1]), 1);
        assert_eq!(verifier.bitstring_to_index(&[1, 1, 1]), 7);
    }

    #[test]
    fn test_porter_thomas_analysis() {
        let verifier = QuantumSupremacyVerifier::new(2, VerificationParams::default())
            .expect("Failed to create verifier");

        // Create uniform random amplitudes
        let amplitudes = vec![Array1::from_vec(vec![
            Complex64::new(0.5, 0.0),
            Complex64::new(0.5, 0.0),
            Complex64::new(0.5, 0.0),
            Complex64::new(0.5, 0.0),
        ])];

        let result = verifier
            .analyze_porter_thomas(&amplitudes)
            .expect("Failed to analyze Porter-Thomas distribution");
        assert!(result.chi_squared >= 0.0);
        assert!(result.p_value >= 0.0 && result.p_value <= 1.0);
    }
}