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
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
//! Quantum annealing simulation with realistic noise models and hardware constraints.
//!
//! This module implements comprehensive quantum annealing simulation that accurately
//! models real quantum annealing hardware including thermal noise, decoherence,
//! control errors, and hardware topology constraints. It supports various
//! optimization problems (QUBO, Ising, etc.) and provides realistic simulation
//! of quantum annealing devices like D-Wave systems.

use crate::prelude::SimulatorError;
use scirs2_core::ndarray::{Array1, Array2};
use scirs2_core::parallel_ops::{IndexedParallelIterator, ParallelIterator};
use scirs2_core::Complex64;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

use crate::device_noise_models::{DeviceNoiseSimulator, DeviceTopology};
use crate::error::Result;
use crate::scirs2_integration::SciRS2Backend;

/// Quantum annealing configuration
#[derive(Debug, Clone)]
pub struct QuantumAnnealingConfig {
    /// Total annealing time (μs)
    pub annealing_time: f64,
    /// Number of time steps
    pub time_steps: usize,
    /// Annealing schedule type
    pub schedule_type: AnnealingScheduleType,
    /// Problem formulation
    pub problem_type: ProblemType,
    /// Hardware topology
    pub topology: AnnealingTopology,
    /// Temperature (K)
    pub temperature: f64,
    /// Enable realistic noise models
    pub enable_noise: bool,
    /// Enable thermal fluctuations
    pub enable_thermal_fluctuations: bool,
    /// Enable control errors
    pub enable_control_errors: bool,
    /// Enable gauge transformations
    pub enable_gauge_transformations: bool,
    /// Post-processing configuration
    pub post_processing: PostProcessingConfig,
}

impl Default for QuantumAnnealingConfig {
    fn default() -> Self {
        Self {
            annealing_time: 20.0, // 20 μs (typical D-Wave)
            time_steps: 2000,
            schedule_type: AnnealingScheduleType::DWave,
            problem_type: ProblemType::Ising,
            topology: AnnealingTopology::Chimera(16),
            temperature: 0.015, // 15 mK
            enable_noise: true,
            enable_thermal_fluctuations: true,
            enable_control_errors: true,
            enable_gauge_transformations: true,
            post_processing: PostProcessingConfig::default(),
        }
    }
}

/// Annealing schedule types
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum AnnealingScheduleType {
    /// Linear schedule
    Linear,
    /// D-Wave like schedule with pause
    DWave,
    /// Optimized schedule for specific problems
    Optimized,
    /// Custom schedule with pause features
    CustomPause {
        pause_start: f64,
        pause_duration: f64,
    },
    /// Non-monotonic schedule
    NonMonotonic,
    /// Reverse annealing
    Reverse { reinitialize_point: f64 },
}

/// Problem types for quantum annealing
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProblemType {
    /// Ising model
    Ising,
    /// Quadratic Unconstrained Binary Optimization
    QUBO,
    /// Maximum Cut
    MaxCut,
    /// Graph Coloring
    GraphColoring,
    /// Traveling Salesman Problem
    TSP,
    /// Number Partitioning
    NumberPartitioning,
    /// Custom optimization problem
    Custom(String),
}

/// Annealing hardware topologies
#[derive(Debug, Clone, PartialEq)]
pub enum AnnealingTopology {
    /// D-Wave Chimera topology
    Chimera(usize), // Parameter is the size
    /// D-Wave Pegasus topology
    Pegasus(usize),
    /// D-Wave Zephyr topology
    Zephyr(usize),
    /// Complete graph
    Complete(usize),
    /// Custom topology
    Custom(DeviceTopology),
}

/// Post-processing configuration
#[derive(Debug, Clone)]
pub struct PostProcessingConfig {
    /// Enable spin reversal transformations
    pub enable_spin_reversal: bool,
    /// Enable local search optimization
    pub enable_local_search: bool,
    /// Maximum local search iterations
    pub max_local_search_iterations: usize,
    /// Enable majority vote post-processing
    pub enable_majority_vote: bool,
    /// Number of reads for majority vote
    pub majority_vote_reads: usize,
    /// Enable energy-based filtering
    pub enable_energy_filtering: bool,
}

impl Default for PostProcessingConfig {
    fn default() -> Self {
        Self {
            enable_spin_reversal: true,
            enable_local_search: true,
            max_local_search_iterations: 100,
            enable_majority_vote: true,
            majority_vote_reads: 1000,
            enable_energy_filtering: true,
        }
    }
}

/// Ising problem representation
#[derive(Debug, Clone)]
pub struct IsingProblem {
    /// Number of spins
    pub num_spins: usize,
    /// Linear coefficients (`h_i`)
    pub h: Array1<f64>,
    /// Quadratic coefficients (J_{ij})
    pub j: Array2<f64>,
    /// Offset constant
    pub offset: f64,
    /// Problem metadata
    pub metadata: ProblemMetadata,
}

/// QUBO problem representation
#[derive(Debug, Clone)]
pub struct QUBOProblem {
    /// Number of variables
    pub num_variables: usize,
    /// QUBO matrix (Q_{ij})
    pub q: Array2<f64>,
    /// Linear coefficients
    pub linear: Array1<f64>,
    /// Offset constant
    pub offset: f64,
    /// Problem metadata
    pub metadata: ProblemMetadata,
}

/// Problem metadata
#[derive(Debug, Clone, Default)]
pub struct ProblemMetadata {
    /// Problem name
    pub name: Option<String>,
    /// Problem description
    pub description: Option<String>,
    /// Known optimal energy
    pub optimal_energy: Option<f64>,
    /// Problem difficulty estimate
    pub difficulty_score: Option<f64>,
    /// Variable labels
    pub variable_labels: Vec<String>,
}

impl IsingProblem {
    /// Create new Ising problem
    #[must_use]
    pub fn new(num_spins: usize) -> Self {
        Self {
            num_spins,
            h: Array1::zeros(num_spins),
            j: Array2::zeros((num_spins, num_spins)),
            offset: 0.0,
            metadata: ProblemMetadata::default(),
        }
    }

    /// Set linear coefficient
    pub fn set_h(&mut self, i: usize, value: f64) {
        if i < self.num_spins {
            self.h[i] = value;
        }
    }

    /// Set quadratic coefficient
    pub fn set_j(&mut self, i: usize, j: usize, value: f64) {
        if i < self.num_spins && j < self.num_spins {
            self.j[[i, j]] = value;
            self.j[[j, i]] = value; // Ensure symmetry
        }
    }

    /// Calculate energy for a given configuration
    #[must_use]
    pub fn calculate_energy(&self, configuration: &[i8]) -> f64 {
        if configuration.len() != self.num_spins {
            return f64::INFINITY;
        }

        let mut energy = self.offset;

        // Linear terms
        for i in 0..self.num_spins {
            energy += self.h[i] * f64::from(configuration[i]);
        }

        // Quadratic terms
        for i in 0..self.num_spins {
            for j in i + 1..self.num_spins {
                energy +=
                    self.j[[i, j]] * f64::from(configuration[i]) * f64::from(configuration[j]);
            }
        }

        energy
    }

    /// Convert to QUBO problem
    #[must_use]
    pub fn to_qubo(&self) -> QUBOProblem {
        let num_vars = self.num_spins;
        let mut q = Array2::zeros((num_vars, num_vars));
        let mut linear = Array1::zeros(num_vars);
        let mut offset = self.offset;

        // Convert Ising to QUBO: s_i = 2x_i - 1
        // H_Ising = sum_i h_i s_i + sum_{i<j} J_{ij} s_i s_j
        // H_QUBO = sum_i q_i x_i + sum_{i<j} q_{ij} x_i x_j + const

        for i in 0..num_vars {
            // Linear terms: h_i s_i = h_i (2x_i - 1) = 2h_i x_i - h_i
            linear[i] += 2.0 * self.h[i];
            offset -= self.h[i];

            for j in i + 1..num_vars {
                // Quadratic terms: J_{ij} s_i s_j = J_{ij} (2x_i - 1)(2x_j - 1)
                // = 4 J_{ij} x_i x_j - 2 J_{ij} x_i - 2 J_{ij} x_j + J_{ij}
                q[[i, j]] += 4.0 * self.j[[i, j]];
                linear[i] -= 2.0 * self.j[[i, j]];
                linear[j] -= 2.0 * self.j[[i, j]];
                offset += self.j[[i, j]];
            }
        }

        QUBOProblem {
            num_variables: num_vars,
            q,
            linear,
            offset,
            metadata: self.metadata.clone(),
        }
    }

    /// Find ground state using brute force (for small problems)
    #[must_use]
    pub fn find_ground_state_brute_force(&self) -> (Vec<i8>, f64) {
        assert!(
            (self.num_spins <= 20),
            "Brute force search only supported for <= 20 spins"
        );

        let mut best_config = vec![-1; self.num_spins];
        let mut best_energy = f64::INFINITY;

        for state in 0..(1 << self.num_spins) {
            let mut config = vec![-1; self.num_spins];
            for i in 0..self.num_spins {
                if (state >> i) & 1 == 1 {
                    config[i] = 1;
                }
            }

            let energy = self.calculate_energy(&config);
            if energy < best_energy {
                best_energy = energy;
                best_config = config;
            }
        }

        (best_config, best_energy)
    }
}

impl QUBOProblem {
    /// Create new QUBO problem
    #[must_use]
    pub fn new(num_variables: usize) -> Self {
        Self {
            num_variables,
            q: Array2::zeros((num_variables, num_variables)),
            linear: Array1::zeros(num_variables),
            offset: 0.0,
            metadata: ProblemMetadata::default(),
        }
    }

    /// Calculate energy for a given binary configuration
    #[must_use]
    pub fn calculate_energy(&self, configuration: &[u8]) -> f64 {
        if configuration.len() != self.num_variables {
            return f64::INFINITY;
        }

        let mut energy = self.offset;

        // Linear terms
        for i in 0..self.num_variables {
            energy += self.linear[i] * f64::from(configuration[i]);
        }

        // Quadratic terms
        for i in 0..self.num_variables {
            for j in 0..self.num_variables {
                if i != j {
                    energy +=
                        self.q[[i, j]] * f64::from(configuration[i]) * f64::from(configuration[j]);
                }
            }
        }

        energy
    }

    /// Convert to Ising problem
    #[must_use]
    pub fn to_ising(&self) -> IsingProblem {
        let num_spins = self.num_variables;
        let mut h = Array1::zeros(num_spins);
        let mut j = Array2::zeros((num_spins, num_spins));
        let mut offset = self.offset;

        // Convert QUBO to Ising: x_i = (s_i + 1)/2
        for i in 0..num_spins {
            h[i] = self.linear[i] / 2.0;
            offset += self.linear[i] / 2.0;

            for k in 0..num_spins {
                if k != i {
                    h[i] += self.q[[i, k]] / 4.0;
                    offset += self.q[[i, k]] / 4.0;
                }
            }
        }

        for i in 0..num_spins {
            for k in i + 1..num_spins {
                j[[i, k]] = self.q[[i, k]] / 4.0;
            }
        }

        IsingProblem {
            num_spins,
            h,
            j,
            offset,
            metadata: self.metadata.clone(),
        }
    }
}

/// Quantum annealing simulator
pub struct QuantumAnnealingSimulator {
    /// Configuration
    config: QuantumAnnealingConfig,
    /// Current problem
    current_problem: Option<IsingProblem>,
    /// Device noise simulator
    noise_simulator: Option<DeviceNoiseSimulator>,
    /// `SciRS2` backend for optimization
    backend: Option<SciRS2Backend>,
    /// Annealing history
    annealing_history: Vec<AnnealingSnapshot>,
    /// Final solutions
    solutions: Vec<AnnealingSolution>,
    /// Statistics
    stats: AnnealingStats,
}

/// Annealing snapshot
#[derive(Debug, Clone)]
pub struct AnnealingSnapshot {
    /// Time parameter
    pub time: f64,
    /// Annealing parameter s(t)
    pub s: f64,
    /// Transverse field strength
    pub transverse_field: f64,
    /// Longitudinal field strength
    pub longitudinal_field: f64,
    /// Current quantum state (if tracking)
    pub quantum_state: Option<Array1<Complex64>>,
    /// Classical state probabilities
    pub classical_probabilities: Option<Array1<f64>>,
    /// Energy expectation value
    pub energy_expectation: f64,
    /// Temperature effects
    pub temperature_factor: f64,
}

/// Annealing solution
#[derive(Debug, Clone)]
pub struct AnnealingSolution {
    /// Solution configuration
    pub configuration: Vec<i8>,
    /// Solution energy
    pub energy: f64,
    /// Solution probability
    pub probability: f64,
    /// Number of occurrences
    pub num_occurrences: usize,
    /// Solution rank
    pub rank: usize,
}

/// Annealing simulation statistics
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AnnealingStats {
    /// Total annealing time
    pub total_annealing_time_ms: f64,
    /// Number of annealing runs
    pub num_annealing_runs: usize,
    /// Number of solutions found
    pub num_solutions_found: usize,
    /// Best energy found
    pub best_energy_found: f64,
    /// Success probability (if ground state known)
    pub success_probability: f64,
    /// Time to solution statistics
    pub time_to_solution: TimeToSolutionStats,
    /// Noise statistics
    pub noise_stats: NoiseStats,
}

/// Time to solution statistics
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct TimeToSolutionStats {
    /// Median time to solution
    pub median_tts: f64,
    /// 99th percentile time to solution
    pub percentile_99_tts: f64,
    /// Success rate
    pub success_rate: f64,
}

/// Noise statistics
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct NoiseStats {
    /// Thermal excitation events
    pub thermal_excitations: usize,
    /// Control error events
    pub control_errors: usize,
    /// Decoherence events
    pub decoherence_events: usize,
}

impl QuantumAnnealingSimulator {
    /// Create new quantum annealing simulator
    pub fn new(config: QuantumAnnealingConfig) -> Result<Self> {
        Ok(Self {
            config,
            current_problem: None,
            noise_simulator: None,
            backend: None,
            annealing_history: Vec::new(),
            solutions: Vec::new(),
            stats: AnnealingStats::default(),
        })
    }

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

    /// Set problem to solve
    pub fn set_problem(&mut self, problem: IsingProblem) -> Result<()> {
        // Validate problem size against topology
        let max_spins = match &self.config.topology {
            AnnealingTopology::Chimera(size) => size * size * 8,
            AnnealingTopology::Pegasus(size) => size * (size - 1) * 12,
            AnnealingTopology::Zephyr(size) => size * size * 8,
            AnnealingTopology::Complete(size) => *size,
            AnnealingTopology::Custom(topology) => topology.num_qubits,
        };

        if problem.num_spins > max_spins {
            return Err(SimulatorError::InvalidInput(format!(
                "Problem size {} exceeds topology limit {}",
                problem.num_spins, max_spins
            )));
        }

        self.current_problem = Some(problem);
        Ok(())
    }

    /// Run quantum annealing
    pub fn anneal(&mut self, num_reads: usize) -> Result<AnnealingResult> {
        let problem = self
            .current_problem
            .as_ref()
            .ok_or_else(|| SimulatorError::InvalidInput("No problem set".to_string()))?;

        let start_time = std::time::Instant::now();
        self.solutions.clear();

        for read in 0..num_reads {
            let read_start = std::time::Instant::now();

            // Run single annealing cycle
            let solution = self.single_anneal(read)?;
            self.solutions.push(solution);

            if read % 100 == 0 {
                println!(
                    "Completed read {}/{}, time={:.2}ms",
                    read,
                    num_reads,
                    read_start.elapsed().as_secs_f64() * 1000.0
                );
            }
        }

        // Post-process solutions
        if self.config.post_processing.enable_majority_vote {
            self.apply_majority_vote_post_processing()?;
        }

        if self.config.post_processing.enable_local_search {
            self.apply_local_search_post_processing()?;
        }

        // Sort solutions by energy
        self.solutions.sort_by(|a, b| {
            a.energy
                .partial_cmp(&b.energy)
                .unwrap_or(std::cmp::Ordering::Equal)
        });

        // Rank solutions
        for (rank, solution) in self.solutions.iter_mut().enumerate() {
            solution.rank = rank;
        }

        // Compute statistics
        self.compute_annealing_statistics()?;

        let total_time = start_time.elapsed().as_secs_f64() * 1000.0;
        self.stats.total_annealing_time_ms += total_time;
        self.stats.num_annealing_runs += num_reads;

        Ok(AnnealingResult {
            solutions: self.solutions.clone(),
            best_energy: self.solutions.first().map_or(f64::INFINITY, |s| s.energy),
            annealing_history: self.annealing_history.clone(),
            total_time_ms: total_time,
            success_probability: self.stats.success_probability,
            time_to_solution: self.stats.time_to_solution.clone(),
        })
    }

    /// Run single annealing cycle
    fn single_anneal(&mut self, _read_id: usize) -> Result<AnnealingSolution> {
        let problem = self
            .current_problem
            .as_ref()
            .ok_or_else(|| SimulatorError::InvalidInput("No problem set".to_string()))?;
        let problem_num_spins = problem.num_spins;

        // Initialize quantum state in superposition
        let state_size = 1 << problem_num_spins.min(20); // Limit for memory
        let mut quantum_state = if problem_num_spins <= 20 {
            let mut state = Array1::zeros(state_size);
            // Initialize in equal superposition
            let amplitude = (1.0 / state_size as f64).sqrt();
            state.fill(Complex64::new(amplitude, 0.0));
            Some(state)
        } else {
            None // Use classical approximation for large problems
        };

        let dt = self.config.annealing_time / self.config.time_steps as f64;
        self.annealing_history.clear();

        // Annealing evolution
        for step in 0..=self.config.time_steps {
            let t = step as f64 * dt;
            let s = self.schedule_function(t);

            // Calculate field strengths
            let (transverse_field, longitudinal_field) = self.calculate_field_strengths(s);

            // Apply quantum evolution
            if let Some(ref mut state) = quantum_state {
                self.apply_quantum_evolution(state, transverse_field, longitudinal_field, dt)?;

                // Apply noise if enabled
                if self.config.enable_noise {
                    self.apply_annealing_noise(state, dt)?;
                }
            }

            // Take snapshot
            if step % (self.config.time_steps / 100) == 0 {
                let snapshot = self.take_annealing_snapshot(
                    t,
                    s,
                    transverse_field,
                    longitudinal_field,
                    quantum_state.as_ref(),
                )?;
                self.annealing_history.push(snapshot);
            }
        }

        // Final measurement/sampling
        let final_configuration = if let Some(ref state) = quantum_state {
            self.measure_final_state(state)?
        } else {
            // Get the problem again for classical sampling
            let problem = self
                .current_problem
                .as_ref()
                .ok_or_else(|| SimulatorError::InvalidInput("No problem set".to_string()))?;
            self.classical_sampling(problem)?
        };

        let energy = self
            .current_problem
            .as_ref()
            .ok_or_else(|| SimulatorError::InvalidInput("No problem set".to_string()))?
            .calculate_energy(&final_configuration);

        Ok(AnnealingSolution {
            configuration: final_configuration,
            energy,
            probability: 1.0 / (self.config.time_steps as f64), // Will be updated later
            num_occurrences: 1,
            rank: 0,
        })
    }

    /// Calculate annealing schedule s(t)
    fn schedule_function(&self, t: f64) -> f64 {
        let normalized_t = t / self.config.annealing_time;

        match self.config.schedule_type {
            AnnealingScheduleType::Linear => normalized_t,
            AnnealingScheduleType::DWave => {
                // D-Wave like schedule with slower start and end
                if normalized_t < 0.1 {
                    5.0 * normalized_t * normalized_t
                } else if normalized_t < 0.9 {
                    0.05 + 0.9 * (normalized_t - 0.1) / 0.8
                } else {
                    0.05f64.mul_add(
                        1.0 - (1.0 - normalized_t) * (1.0 - normalized_t) / 0.01,
                        0.95,
                    )
                }
            }
            AnnealingScheduleType::Optimized => {
                // Optimized schedule based on problem characteristics
                self.optimized_schedule(normalized_t)
            }
            AnnealingScheduleType::CustomPause {
                pause_start,
                pause_duration,
            } => {
                if normalized_t >= pause_start && normalized_t <= pause_start + pause_duration {
                    pause_start // Pause at this value
                } else if normalized_t > pause_start + pause_duration {
                    (normalized_t - pause_duration - pause_start) / (1.0 - pause_duration)
                } else {
                    normalized_t / pause_start
                }
            }
            AnnealingScheduleType::NonMonotonic => {
                // Non-monotonic schedule with oscillations
                (0.1 * (10.0 * std::f64::consts::PI * normalized_t).sin())
                    .mul_add(1.0 - normalized_t, normalized_t)
            }
            AnnealingScheduleType::Reverse { reinitialize_point } => {
                if normalized_t < reinitialize_point {
                    1.0 // Start at problem Hamiltonian
                } else {
                    1.0 - (normalized_t - reinitialize_point) / (1.0 - reinitialize_point)
                }
            }
        }
    }

    /// Optimized schedule function
    fn optimized_schedule(&self, t: f64) -> f64 {
        // Simple optimization: slower evolution near avoided crossings
        // This would be problem-specific in practice
        if t < 0.3 {
            t * t / 0.09 * 0.3
        } else if t < 0.7 {
            0.3 + (t - 0.3) * 0.4 / 0.4
        } else {
            ((t - 0.7) * (t - 0.7) / 0.09).mul_add(0.3, 0.7)
        }
    }

    /// Calculate transverse and longitudinal field strengths
    fn calculate_field_strengths(&self, s: f64) -> (f64, f64) {
        // Standard quantum annealing: H(s) = -A(s) ∑_i σ_x^i + B(s) H_problem
        let a_s = (1.0 - s) * 1.0; // Transverse field strength
        let b_s = s * 1.0; // Longitudinal field strength
        (a_s, b_s)
    }

    /// Apply quantum evolution for one time step
    fn apply_quantum_evolution(
        &self,
        state: &mut Array1<Complex64>,
        transverse_field: f64,
        longitudinal_field: f64,
        dt: f64,
    ) -> Result<()> {
        // Problem is guaranteed to exist when called from single_anneal
        let _problem = self
            .current_problem
            .as_ref()
            .ok_or_else(|| SimulatorError::InvalidInput("No problem set".to_string()))?;

        // Build total Hamiltonian matrix
        let hamiltonian = self.build_annealing_hamiltonian(transverse_field, longitudinal_field)?;

        // Apply time evolution: |ψ(t+dt)⟩ = exp(-i H dt / ℏ) |ψ(t)⟩
        let evolution_operator = self.compute_evolution_operator(&hamiltonian, dt)?;
        *state = evolution_operator.dot(state);

        // Renormalize to handle numerical errors
        let norm: f64 = state
            .iter()
            .map(scirs2_core::Complex::norm_sqr)
            .sum::<f64>()
            .sqrt();
        if norm > 1e-15 {
            state.mapv_inplace(|x| x / norm);
        }

        Ok(())
    }

    /// Build full annealing Hamiltonian
    fn build_annealing_hamiltonian(
        &self,
        transverse_field: f64,
        longitudinal_field: f64,
    ) -> Result<Array2<Complex64>> {
        let problem = self
            .current_problem
            .as_ref()
            .ok_or_else(|| SimulatorError::InvalidInput("No problem set".to_string()))?;
        let num_spins = problem.num_spins;
        let dim = 1 << num_spins;
        let mut hamiltonian = Array2::zeros((dim, dim));

        // Transverse field terms: -A(s) ∑_i σ_x^i
        for spin in 0..num_spins {
            let sigma_x = self.build_sigma_x(spin, num_spins);
            hamiltonian = hamiltonian - sigma_x.mapv(|x| x * transverse_field);
        }

        // Longitudinal field terms: B(s) H_problem
        let problem_hamiltonian = self.build_problem_hamiltonian()?;
        hamiltonian = hamiltonian + problem_hamiltonian.mapv(|x| x * longitudinal_field);

        Ok(hamiltonian)
    }

    /// Build Pauli-X operator for specific spin
    fn build_sigma_x(&self, target_spin: usize, num_spins: usize) -> Array2<Complex64> {
        let dim = 1 << num_spins;
        let mut sigma_x = Array2::zeros((dim, dim));

        for i in 0..dim {
            let j = i ^ (1 << target_spin); // Flip the target spin
            sigma_x[[i, j]] = Complex64::new(1.0, 0.0);
        }

        sigma_x
    }

    /// Build problem Hamiltonian (Ising model)
    fn build_problem_hamiltonian(&self) -> Result<Array2<Complex64>> {
        let problem = self
            .current_problem
            .as_ref()
            .ok_or_else(|| SimulatorError::InvalidInput("No problem set".to_string()))?;
        let num_spins = problem.num_spins;
        let dim = 1 << num_spins;
        let mut hamiltonian = Array2::zeros((dim, dim));

        // Linear terms: ∑_i h_i σ_z^i
        for i in 0..num_spins {
            let sigma_z = self.build_sigma_z(i, num_spins);
            hamiltonian = hamiltonian + sigma_z.mapv(|x| x * problem.h[i]);
        }

        // Quadratic terms: ∑_{i<j} J_{ij} σ_z^i σ_z^j
        for i in 0..num_spins {
            for j in i + 1..num_spins {
                if problem.j[[i, j]] != 0.0 {
                    let sigma_z_i = self.build_sigma_z(i, num_spins);
                    let sigma_z_j = self.build_sigma_z(j, num_spins);
                    let sigma_z_ij = sigma_z_i.dot(&sigma_z_j);
                    hamiltonian = hamiltonian + sigma_z_ij.mapv(|x| x * problem.j[[i, j]]);
                }
            }
        }

        // Add offset as identity matrix
        for i in 0..dim {
            hamiltonian[[i, i]] += Complex64::new(problem.offset, 0.0);
        }

        Ok(hamiltonian)
    }

    /// Build Pauli-Z operator for specific spin
    fn build_sigma_z(&self, target_spin: usize, num_spins: usize) -> Array2<Complex64> {
        let dim = 1 << num_spins;
        let mut sigma_z = Array2::zeros((dim, dim));

        for i in 0..dim {
            let sign = if (i >> target_spin) & 1 == 0 {
                1.0
            } else {
                -1.0
            };
            sigma_z[[i, i]] = Complex64::new(sign, 0.0);
        }

        sigma_z
    }

    /// Compute time evolution operator
    fn compute_evolution_operator(
        &self,
        hamiltonian: &Array2<Complex64>,
        dt: f64,
    ) -> Result<Array2<Complex64>> {
        // Use matrix exponentiation for small systems
        self.matrix_exponential(hamiltonian, -Complex64::new(0.0, dt))
    }

    /// Matrix exponential implementation
    fn matrix_exponential(
        &self,
        matrix: &Array2<Complex64>,
        factor: Complex64,
    ) -> Result<Array2<Complex64>> {
        let dim = matrix.dim().0;
        let scaled_matrix = matrix.mapv(|x| x * factor);

        let mut result = Array2::eye(dim);
        let mut term = Array2::eye(dim);

        for n in 1..=15 {
            // Limit series expansion
            term = term.dot(&scaled_matrix) / f64::from(n);
            let term_norm: f64 = term
                .iter()
                .map(scirs2_core::Complex::norm_sqr)
                .sum::<f64>()
                .sqrt();

            result += &term;

            if term_norm < 1e-12 {
                break;
            }
        }

        Ok(result)
    }

    /// Apply various noise sources during annealing
    fn apply_annealing_noise(&mut self, state: &mut Array1<Complex64>, dt: f64) -> Result<()> {
        if self.config.enable_thermal_fluctuations {
            self.apply_thermal_noise(state, dt)?;
            self.stats.noise_stats.thermal_excitations += 1;
        }

        if self.config.enable_control_errors {
            self.apply_control_error_noise(state, dt)?;
            self.stats.noise_stats.control_errors += 1;
        }

        // Decoherence
        self.apply_decoherence_noise(state, dt)?;
        self.stats.noise_stats.decoherence_events += 1;

        Ok(())
    }

    /// Apply thermal noise
    fn apply_thermal_noise(&self, state: &mut Array1<Complex64>, dt: f64) -> Result<()> {
        // Thermal fluctuations cause random phase evolution
        let kb_t = 1.38e-23 * self.config.temperature; // Boltzmann constant times temperature
        let thermal_energy = kb_t * dt * 1e6; // Convert to relevant energy scale

        for amplitude in state.iter_mut() {
            let thermal_phase = fastrand::f64() * thermal_energy * 2.0 * std::f64::consts::PI;
            *amplitude *= Complex64::new(0.0, thermal_phase).exp();
        }

        Ok(())
    }

    /// Apply control error noise
    fn apply_control_error_noise(&self, state: &mut Array1<Complex64>, dt: f64) -> Result<()> {
        // Control errors cause imperfect implementation of the intended Hamiltonian
        let error_strength = 0.01; // 1% control errors

        // Apply random single-qubit rotations to simulate control errors
        // Problem is guaranteed to exist when called from apply_annealing_noise
        let problem = self
            .current_problem
            .as_ref()
            .ok_or_else(|| SimulatorError::InvalidInput("No problem set".to_string()))?;
        for spin in 0..problem.num_spins.min(10) {
            // Limit for performance
            if fastrand::f64() < error_strength * dt {
                let error_angle = fastrand::f64() * 0.1; // Small random rotation
                self.apply_single_spin_rotation(state, spin, error_angle)?;
            }
        }

        Ok(())
    }

    /// Apply decoherence noise
    fn apply_decoherence_noise(&self, state: &mut Array1<Complex64>, dt: f64) -> Result<()> {
        let decoherence_rate = 1e-3; // Typical decoherence rate
        let decoherence_prob = decoherence_rate * dt;

        for amplitude in state.iter_mut() {
            if fastrand::f64() < decoherence_prob {
                // Apply random dephasing
                let phase = fastrand::f64() * 2.0 * std::f64::consts::PI;
                *amplitude *= Complex64::new(0.0, phase).exp();
            }
        }

        Ok(())
    }

    /// Apply single spin rotation
    fn apply_single_spin_rotation(
        &self,
        state: &mut Array1<Complex64>,
        spin: usize,
        angle: f64,
    ) -> Result<()> {
        // Problem check for validation - spin_mask doesn't depend on it but kept for API consistency
        let _problem = self
            .current_problem
            .as_ref()
            .ok_or_else(|| SimulatorError::InvalidInput("No problem set".to_string()))?;
        let spin_mask = 1 << spin;
        let cos_half = (angle / 2.0).cos();
        let sin_half = (angle / 2.0).sin();

        for i in 0..state.len() {
            if i & spin_mask == 0 {
                let j = i | spin_mask;
                if j < state.len() {
                    let amp_0 = state[i];
                    let amp_1 = state[j];

                    state[i] = cos_half * amp_0 - Complex64::new(0.0, sin_half) * amp_1;
                    state[j] = cos_half * amp_1 - Complex64::new(0.0, sin_half) * amp_0;
                }
            }
        }

        Ok(())
    }

    /// Take annealing snapshot
    fn take_annealing_snapshot(
        &self,
        time: f64,
        s: f64,
        transverse_field: f64,
        longitudinal_field: f64,
        quantum_state: Option<&Array1<Complex64>>,
    ) -> Result<AnnealingSnapshot> {
        let energy_expectation = if let Some(state) = quantum_state {
            self.calculate_energy_expectation(state)?
        } else {
            0.0
        };

        let temperature_factor = (-1.0 / (1.38e-23 * self.config.temperature)).exp();

        Ok(AnnealingSnapshot {
            time,
            s,
            transverse_field,
            longitudinal_field,
            quantum_state: quantum_state.cloned(),
            classical_probabilities: None,
            energy_expectation,
            temperature_factor,
        })
    }

    /// Calculate energy expectation value
    fn calculate_energy_expectation(&self, state: &Array1<Complex64>) -> Result<f64> {
        let problem = self
            .current_problem
            .as_ref()
            .ok_or_else(|| SimulatorError::InvalidInput("No problem set".to_string()))?;
        let mut expectation = 0.0;

        for (i, &amplitude) in state.iter().enumerate() {
            let prob = amplitude.norm_sqr();

            // Convert state index to spin configuration
            let mut config = vec![-1; problem.num_spins];
            for spin in 0..problem.num_spins {
                if (i >> spin) & 1 == 1 {
                    config[spin] = 1;
                }
            }

            let energy = problem.calculate_energy(&config);
            expectation += prob * energy;
        }

        Ok(expectation)
    }

    /// Measure final quantum state
    fn measure_final_state(&self, state: &Array1<Complex64>) -> Result<Vec<i8>> {
        let problem = self
            .current_problem
            .as_ref()
            .ok_or_else(|| SimulatorError::InvalidInput("No problem set".to_string()))?;

        // Sample from the quantum state probability distribution
        let probabilities: Vec<f64> = state.iter().map(scirs2_core::Complex::norm_sqr).collect();
        let random_val = fastrand::f64();

        let mut cumulative_prob = 0.0;
        for (i, &prob) in probabilities.iter().enumerate() {
            cumulative_prob += prob;
            if random_val < cumulative_prob {
                // Convert state index to spin configuration
                let mut config = vec![-1; problem.num_spins];
                for spin in 0..problem.num_spins {
                    if (i >> spin) & 1 == 1 {
                        config[spin] = 1;
                    }
                }
                return Ok(config);
            }
        }

        // Fallback to ground state
        Ok(vec![-1; problem.num_spins])
    }

    /// Classical sampling for large problems
    fn classical_sampling(&self, problem: &IsingProblem) -> Result<Vec<i8>> {
        // Use simulated annealing or other classical heuristics
        let mut config: Vec<i8> = (0..problem.num_spins)
            .map(|_| if fastrand::f64() > 0.5 { 1 } else { -1 })
            .collect();

        // Simple local search
        for _ in 0..1000 {
            let spin_to_flip = fastrand::usize(0..problem.num_spins);
            let old_energy = problem.calculate_energy(&config);

            config[spin_to_flip] *= -1;
            let new_energy = problem.calculate_energy(&config);

            if new_energy > old_energy {
                config[spin_to_flip] *= -1; // Revert if energy increased
            }
        }

        Ok(config)
    }

    /// Apply majority vote post-processing
    fn apply_majority_vote_post_processing(&mut self) -> Result<()> {
        if self.solutions.is_empty() {
            return Ok(());
        }

        // Group solutions by configuration
        let mut config_groups: HashMap<Vec<i8>, Vec<usize>> = HashMap::new();
        for (i, solution) in self.solutions.iter().enumerate() {
            config_groups
                .entry(solution.configuration.clone())
                .or_default()
                .push(i);
        }

        // Update occurrence counts
        for (config, indices) in config_groups {
            let num_occurrences = indices.len();
            for &idx in &indices {
                self.solutions[idx].num_occurrences = num_occurrences;
            }
        }

        Ok(())
    }

    /// Apply local search post-processing
    fn apply_local_search_post_processing(&mut self) -> Result<()> {
        let problem = self
            .current_problem
            .as_ref()
            .ok_or_else(|| SimulatorError::InvalidInput("No problem set".to_string()))?;

        for solution in &mut self.solutions {
            let mut improved_config = solution.configuration.clone();
            let mut improved_energy = solution.energy;

            for _ in 0..self.config.post_processing.max_local_search_iterations {
                let mut found_improvement = false;

                for spin in 0..problem.num_spins {
                    // Try flipping this spin
                    improved_config[spin] *= -1;
                    let new_energy = problem.calculate_energy(&improved_config);

                    if new_energy < improved_energy {
                        improved_energy = new_energy;
                        found_improvement = true;
                        break;
                    }
                    improved_config[spin] *= -1; // Revert
                }

                if !found_improvement {
                    break;
                }
            }

            // Update solution if improved
            if improved_energy < solution.energy {
                solution.configuration = improved_config;
                solution.energy = improved_energy;
            }
        }

        Ok(())
    }

    /// Compute annealing statistics
    fn compute_annealing_statistics(&mut self) -> Result<()> {
        if self.solutions.is_empty() {
            return Ok(());
        }

        self.stats.num_solutions_found = self.solutions.len();
        self.stats.best_energy_found = self
            .solutions
            .iter()
            .map(|s| s.energy)
            .fold(f64::INFINITY, f64::min);

        // Calculate success probability if ground state energy is known
        if let Some(optimal_energy) = self
            .current_problem
            .as_ref()
            .and_then(|p| p.metadata.optimal_energy)
        {
            let tolerance = 1e-6;
            let successful_solutions = self
                .solutions
                .iter()
                .filter(|s| (s.energy - optimal_energy).abs() < tolerance)
                .count();
            self.stats.success_probability =
                successful_solutions as f64 / self.solutions.len() as f64;
        }

        Ok(())
    }

    /// Get annealing statistics
    #[must_use]
    pub const fn get_stats(&self) -> &AnnealingStats {
        &self.stats
    }

    /// Reset statistics
    pub fn reset_stats(&mut self) {
        self.stats = AnnealingStats::default();
    }
}

/// Annealing result
#[derive(Debug, Clone)]
pub struct AnnealingResult {
    /// All solutions found
    pub solutions: Vec<AnnealingSolution>,
    /// Best energy found
    pub best_energy: f64,
    /// Annealing evolution history
    pub annealing_history: Vec<AnnealingSnapshot>,
    /// Total computation time
    pub total_time_ms: f64,
    /// Success probability
    pub success_probability: f64,
    /// Time to solution statistics
    pub time_to_solution: TimeToSolutionStats,
}

/// Quantum annealing utilities
pub struct QuantumAnnealingUtils;

impl QuantumAnnealingUtils {
    /// Create Max-Cut Ising problem
    #[must_use]
    pub fn create_max_cut_problem(graph_edges: &[(usize, usize)], weights: &[f64]) -> IsingProblem {
        let num_vertices = graph_edges
            .iter()
            .flat_map(|&(u, v)| [u, v])
            .max()
            .unwrap_or(0)
            + 1;

        let mut problem = IsingProblem::new(num_vertices);
        problem.metadata.name = Some("Max-Cut".to_string());

        for (i, &(u, v)) in graph_edges.iter().enumerate() {
            let weight = weights.get(i).copied().unwrap_or(1.0);
            // Max-Cut: maximize ∑ w_{ij} (1 - s_i s_j) / 2
            // Equivalent to minimizing ∑ w_{ij} (s_i s_j - 1) / 2
            problem.set_j(u, v, weight / 2.0);
            problem.offset -= weight / 2.0;
        }

        problem
    }

    /// Create number partitioning problem
    #[must_use]
    pub fn create_number_partitioning_problem(numbers: &[f64]) -> IsingProblem {
        let n = numbers.len();
        let mut problem = IsingProblem::new(n);
        problem.metadata.name = Some("Number Partitioning".to_string());

        // Minimize (∑_i n_i s_i)^2 = ∑_i n_i^2 + 2 ∑_{i<j} n_i n_j s_i s_j
        for i in 0..n {
            problem.offset += numbers[i] * numbers[i];
            for j in i + 1..n {
                problem.set_j(i, j, 2.0 * numbers[i] * numbers[j]);
            }
        }

        problem
    }

    /// Create random Ising problem
    #[must_use]
    pub fn create_random_ising_problem(
        num_spins: usize,
        h_range: f64,
        j_range: f64,
    ) -> IsingProblem {
        let mut problem = IsingProblem::new(num_spins);
        problem.metadata.name = Some("Random Ising".to_string());

        // Random linear coefficients
        for i in 0..num_spins {
            problem.set_h(i, (fastrand::f64() - 0.5) * 2.0 * h_range);
        }

        // Random quadratic coefficients
        for i in 0..num_spins {
            for j in i + 1..num_spins {
                if fastrand::f64() < 0.5 {
                    // 50% sparsity
                    problem.set_j(i, j, (fastrand::f64() - 0.5) * 2.0 * j_range);
                }
            }
        }

        problem
    }

    /// Benchmark quantum annealing
    pub fn benchmark_quantum_annealing() -> Result<AnnealingBenchmarkResults> {
        let mut results = AnnealingBenchmarkResults::default();

        let problem_sizes = vec![8, 12, 16];
        let annealing_times = vec![1.0, 10.0, 100.0]; // μs

        for &size in &problem_sizes {
            for &time in &annealing_times {
                // Create random problem
                let problem = Self::create_random_ising_problem(size, 1.0, 1.0);

                let config = QuantumAnnealingConfig {
                    annealing_time: time,
                    time_steps: (time * 100.0) as usize,
                    topology: AnnealingTopology::Complete(size),
                    ..Default::default()
                };

                let mut simulator = QuantumAnnealingSimulator::new(config)?;
                simulator.set_problem(problem)?;

                let start = std::time::Instant::now();
                let result = simulator.anneal(100)?;
                let execution_time = start.elapsed().as_secs_f64() * 1000.0;

                results
                    .execution_times
                    .push((format!("{size}spins_{time}us"), execution_time));
                results
                    .best_energies
                    .push((format!("{size}spins_{time}us"), result.best_energy));
            }
        }

        Ok(results)
    }
}

/// Annealing benchmark results
#[derive(Debug, Clone, Default)]
pub struct AnnealingBenchmarkResults {
    /// Execution times by configuration
    pub execution_times: Vec<(String, f64)>,
    /// Best energies found
    pub best_energies: Vec<(String, f64)>,
}

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

    #[test]
    fn test_ising_problem_creation() {
        let mut problem = IsingProblem::new(3);
        problem.set_h(0, 0.5);
        problem.set_j(0, 1, -1.0);

        assert_eq!(problem.num_spins, 3);
        assert_eq!(problem.h[0], 0.5);
        assert_eq!(problem.j[[0, 1]], -1.0);
        assert_eq!(problem.j[[1, 0]], -1.0);
    }

    #[test]
    fn test_ising_energy_calculation() {
        let mut problem = IsingProblem::new(2);
        problem.set_h(0, 1.0);
        problem.set_h(1, -0.5);
        problem.set_j(0, 1, 2.0);

        let config = vec![1, -1];
        let energy = problem.calculate_energy(&config);
        // E = h_0 * s_0 + h_1 * s_1 + J_{01} * s_0 * s_1
        // E = 1.0 * 1 + (-0.5) * (-1) + 2.0 * 1 * (-1)
        // E = 1.0 + 0.5 - 2.0 = -0.5
        assert_abs_diff_eq!(energy, -0.5, epsilon = 1e-10);
    }

    #[test]
    fn test_ising_to_qubo_conversion() {
        let mut ising = IsingProblem::new(2);
        ising.set_h(0, 1.0);
        ising.set_j(0, 1, -1.0);

        let qubo = ising.to_qubo();
        assert_eq!(qubo.num_variables, 2);

        // Test energy equivalence for a configuration
        let ising_config = vec![1, -1];
        let qubo_config = vec![1, 0]; // s=1 -> x=1, s=-1 -> x=0

        let ising_energy = ising.calculate_energy(&ising_config);
        let qubo_energy = qubo.calculate_energy(&qubo_config);
        assert_abs_diff_eq!(ising_energy, qubo_energy, epsilon = 1e-10);
    }

    #[test]
    fn test_quantum_annealing_simulator_creation() {
        let config = QuantumAnnealingConfig::default();
        let simulator = QuantumAnnealingSimulator::new(config);
        assert!(simulator.is_ok());
    }

    #[test]
    fn test_schedule_functions() {
        let config = QuantumAnnealingConfig {
            annealing_time: 10.0,
            schedule_type: AnnealingScheduleType::Linear,
            ..Default::default()
        };
        let simulator = QuantumAnnealingSimulator::new(config)
            .expect("should create quantum annealing simulator");

        assert_abs_diff_eq!(simulator.schedule_function(0.0), 0.0, epsilon = 1e-10);
        assert_abs_diff_eq!(simulator.schedule_function(5.0), 0.5, epsilon = 1e-10);
        assert_abs_diff_eq!(simulator.schedule_function(10.0), 1.0, epsilon = 1e-10);
    }

    #[test]
    fn test_max_cut_problem_creation() {
        let edges = vec![(0, 1), (1, 2), (2, 0)];
        let weights = vec![1.0, 1.0, 1.0];

        let problem = QuantumAnnealingUtils::create_max_cut_problem(&edges, &weights);
        assert_eq!(problem.num_spins, 3);
        assert!(problem
            .metadata
            .name
            .as_ref()
            .expect("metadata name should be set")
            .contains("Max-Cut"));
    }

    #[test]
    fn test_number_partitioning_problem() {
        let numbers = vec![3.0, 1.0, 1.0, 2.0, 2.0, 1.0];
        let problem = QuantumAnnealingUtils::create_number_partitioning_problem(&numbers);

        assert_eq!(problem.num_spins, 6);
        assert!(problem
            .metadata
            .name
            .as_ref()
            .expect("metadata name should be set")
            .contains("Number Partitioning"));
    }

    #[test]
    fn test_small_problem_annealing() {
        let problem = QuantumAnnealingUtils::create_random_ising_problem(3, 1.0, 1.0);

        let config = QuantumAnnealingConfig {
            annealing_time: 1.0,
            time_steps: 100,
            topology: AnnealingTopology::Complete(3),
            enable_noise: false, // Disable for deterministic test
            ..Default::default()
        };

        let mut simulator = QuantumAnnealingSimulator::new(config)
            .expect("should create quantum annealing simulator");
        simulator
            .set_problem(problem)
            .expect("should set problem successfully");

        let result = simulator.anneal(10);
        assert!(result.is_ok());

        let annealing_result = result.expect("should get annealing result");
        assert_eq!(annealing_result.solutions.len(), 10);
        assert!(!annealing_result.annealing_history.is_empty());
    }

    #[test]
    fn test_field_strength_calculation() {
        let config = QuantumAnnealingConfig::default();
        let simulator = QuantumAnnealingSimulator::new(config)
            .expect("should create quantum annealing simulator");

        let (transverse, longitudinal) = simulator.calculate_field_strengths(0.0);
        assert_abs_diff_eq!(transverse, 1.0, epsilon = 1e-10);
        assert_abs_diff_eq!(longitudinal, 0.0, epsilon = 1e-10);

        let (transverse, longitudinal) = simulator.calculate_field_strengths(1.0);
        assert_abs_diff_eq!(transverse, 0.0, epsilon = 1e-10);
        assert_abs_diff_eq!(longitudinal, 1.0, epsilon = 1e-10);
    }

    #[test]
    fn test_annealing_topologies() {
        let topologies = vec![
            AnnealingTopology::Chimera(4),
            AnnealingTopology::Pegasus(3),
            AnnealingTopology::Complete(5),
        ];

        for topology in topologies {
            let config = QuantumAnnealingConfig {
                topology,
                ..Default::default()
            };
            let simulator = QuantumAnnealingSimulator::new(config);
            assert!(simulator.is_ok());
        }
    }

    #[test]
    fn test_ising_ground_state_brute_force() {
        // Simple 2-spin ferromagnetic Ising model
        let mut problem = IsingProblem::new(2);
        problem.set_j(0, 1, -1.0); // Ferromagnetic coupling

        let (ground_state, ground_energy) = problem.find_ground_state_brute_force();

        // Ground states should be [1, 1] or [-1, -1] with energy -1
        assert!(ground_state == vec![1, 1] || ground_state == vec![-1, -1]);
        assert_abs_diff_eq!(ground_energy, -1.0, epsilon = 1e-10);
    }

    #[test]
    fn test_post_processing_config() {
        let config = PostProcessingConfig::default();
        assert!(config.enable_spin_reversal);
        assert!(config.enable_local_search);
        assert!(config.enable_majority_vote);
        assert_eq!(config.majority_vote_reads, 1000);
    }
}