1use crate::prelude::SimulatorError;
10use scirs2_core::ndarray::{Array1, Array2};
11use scirs2_core::parallel_ops::*;
12use scirs2_core::Complex64;
13use serde::{Deserialize, Serialize};
14use std::collections::HashMap;
15
16use crate::device_noise_models::{DeviceNoiseSimulator, DeviceTopology};
17use crate::error::Result;
18use crate::scirs2_integration::SciRS2Backend;
19
20#[derive(Debug, Clone)]
22pub struct QuantumAnnealingConfig {
23 pub annealing_time: f64,
25 pub time_steps: usize,
27 pub schedule_type: AnnealingScheduleType,
29 pub problem_type: ProblemType,
31 pub topology: AnnealingTopology,
33 pub temperature: f64,
35 pub enable_noise: bool,
37 pub enable_thermal_fluctuations: bool,
39 pub enable_control_errors: bool,
41 pub enable_gauge_transformations: bool,
43 pub post_processing: PostProcessingConfig,
45}
46
47impl Default for QuantumAnnealingConfig {
48 fn default() -> Self {
49 Self {
50 annealing_time: 20.0, time_steps: 2000,
52 schedule_type: AnnealingScheduleType::DWave,
53 problem_type: ProblemType::Ising,
54 topology: AnnealingTopology::Chimera(16),
55 temperature: 0.015, enable_noise: true,
57 enable_thermal_fluctuations: true,
58 enable_control_errors: true,
59 enable_gauge_transformations: true,
60 post_processing: PostProcessingConfig::default(),
61 }
62 }
63}
64
65#[derive(Debug, Clone, Copy, PartialEq)]
67pub enum AnnealingScheduleType {
68 Linear,
70 DWave,
72 Optimized,
74 CustomPause {
76 pause_start: f64,
77 pause_duration: f64,
78 },
79 NonMonotonic,
81 Reverse { reinitialize_point: f64 },
83}
84
85#[derive(Debug, Clone, PartialEq, Eq)]
87pub enum ProblemType {
88 Ising,
90 QUBO,
92 MaxCut,
94 GraphColoring,
96 TSP,
98 NumberPartitioning,
100 Custom(String),
102}
103
104#[derive(Debug, Clone, PartialEq)]
106pub enum AnnealingTopology {
107 Chimera(usize), Pegasus(usize),
111 Zephyr(usize),
113 Complete(usize),
115 Custom(DeviceTopology),
117}
118
119#[derive(Debug, Clone)]
121pub struct PostProcessingConfig {
122 pub enable_spin_reversal: bool,
124 pub enable_local_search: bool,
126 pub max_local_search_iterations: usize,
128 pub enable_majority_vote: bool,
130 pub majority_vote_reads: usize,
132 pub enable_energy_filtering: bool,
134}
135
136impl Default for PostProcessingConfig {
137 fn default() -> Self {
138 Self {
139 enable_spin_reversal: true,
140 enable_local_search: true,
141 max_local_search_iterations: 100,
142 enable_majority_vote: true,
143 majority_vote_reads: 1000,
144 enable_energy_filtering: true,
145 }
146 }
147}
148
149#[derive(Debug, Clone)]
151pub struct IsingProblem {
152 pub num_spins: usize,
154 pub h: Array1<f64>,
156 pub j: Array2<f64>,
158 pub offset: f64,
160 pub metadata: ProblemMetadata,
162}
163
164#[derive(Debug, Clone)]
166pub struct QUBOProblem {
167 pub num_variables: usize,
169 pub q: Array2<f64>,
171 pub linear: Array1<f64>,
173 pub offset: f64,
175 pub metadata: ProblemMetadata,
177}
178
179#[derive(Debug, Clone, Default)]
181pub struct ProblemMetadata {
182 pub name: Option<String>,
184 pub description: Option<String>,
186 pub optimal_energy: Option<f64>,
188 pub difficulty_score: Option<f64>,
190 pub variable_labels: Vec<String>,
192}
193
194impl IsingProblem {
195 pub fn new(num_spins: usize) -> Self {
197 Self {
198 num_spins,
199 h: Array1::zeros(num_spins),
200 j: Array2::zeros((num_spins, num_spins)),
201 offset: 0.0,
202 metadata: ProblemMetadata::default(),
203 }
204 }
205
206 pub fn set_h(&mut self, i: usize, value: f64) {
208 if i < self.num_spins {
209 self.h[i] = value;
210 }
211 }
212
213 pub fn set_j(&mut self, i: usize, j: usize, value: f64) {
215 if i < self.num_spins && j < self.num_spins {
216 self.j[[i, j]] = value;
217 self.j[[j, i]] = value; }
219 }
220
221 pub fn calculate_energy(&self, configuration: &[i8]) -> f64 {
223 if configuration.len() != self.num_spins {
224 return f64::INFINITY;
225 }
226
227 let mut energy = self.offset;
228
229 for i in 0..self.num_spins {
231 energy += self.h[i] * configuration[i] as f64;
232 }
233
234 for i in 0..self.num_spins {
236 for j in i + 1..self.num_spins {
237 energy += self.j[[i, j]] * configuration[i] as f64 * configuration[j] as f64;
238 }
239 }
240
241 energy
242 }
243
244 pub fn to_qubo(&self) -> QUBOProblem {
246 let num_vars = self.num_spins;
247 let mut q = Array2::zeros((num_vars, num_vars));
248 let mut linear = Array1::zeros(num_vars);
249 let mut offset = self.offset;
250
251 for i in 0..num_vars {
256 linear[i] += 2.0 * self.h[i];
258 offset -= self.h[i];
259
260 for j in i + 1..num_vars {
261 q[[i, j]] += 4.0 * self.j[[i, j]];
264 linear[i] -= 2.0 * self.j[[i, j]];
265 linear[j] -= 2.0 * self.j[[i, j]];
266 offset += self.j[[i, j]];
267 }
268 }
269
270 QUBOProblem {
271 num_variables: num_vars,
272 q,
273 linear,
274 offset,
275 metadata: self.metadata.clone(),
276 }
277 }
278
279 pub fn find_ground_state_brute_force(&self) -> (Vec<i8>, f64) {
281 assert!(
282 (self.num_spins <= 20),
283 "Brute force search only supported for <= 20 spins"
284 );
285
286 let mut best_config = vec![-1; self.num_spins];
287 let mut best_energy = f64::INFINITY;
288
289 for state in 0..(1 << self.num_spins) {
290 let mut config = vec![-1; self.num_spins];
291 for i in 0..self.num_spins {
292 if (state >> i) & 1 == 1 {
293 config[i] = 1;
294 }
295 }
296
297 let energy = self.calculate_energy(&config);
298 if energy < best_energy {
299 best_energy = energy;
300 best_config = config;
301 }
302 }
303
304 (best_config, best_energy)
305 }
306}
307
308impl QUBOProblem {
309 pub fn new(num_variables: usize) -> Self {
311 Self {
312 num_variables,
313 q: Array2::zeros((num_variables, num_variables)),
314 linear: Array1::zeros(num_variables),
315 offset: 0.0,
316 metadata: ProblemMetadata::default(),
317 }
318 }
319
320 pub fn calculate_energy(&self, configuration: &[u8]) -> f64 {
322 if configuration.len() != self.num_variables {
323 return f64::INFINITY;
324 }
325
326 let mut energy = self.offset;
327
328 for i in 0..self.num_variables {
330 energy += self.linear[i] * configuration[i] as f64;
331 }
332
333 for i in 0..self.num_variables {
335 for j in 0..self.num_variables {
336 if i != j {
337 energy += self.q[[i, j]] * configuration[i] as f64 * configuration[j] as f64;
338 }
339 }
340 }
341
342 energy
343 }
344
345 pub fn to_ising(&self) -> IsingProblem {
347 let num_spins = self.num_variables;
348 let mut h = Array1::zeros(num_spins);
349 let mut j = Array2::zeros((num_spins, num_spins));
350 let mut offset = self.offset;
351
352 for i in 0..num_spins {
354 h[i] = self.linear[i] / 2.0;
355 offset += self.linear[i] / 2.0;
356
357 for k in 0..num_spins {
358 if k != i {
359 h[i] += self.q[[i, k]] / 4.0;
360 offset += self.q[[i, k]] / 4.0;
361 }
362 }
363 }
364
365 for i in 0..num_spins {
366 for k in i + 1..num_spins {
367 j[[i, k]] = self.q[[i, k]] / 4.0;
368 }
369 }
370
371 IsingProblem {
372 num_spins,
373 h,
374 j,
375 offset,
376 metadata: self.metadata.clone(),
377 }
378 }
379}
380
381pub struct QuantumAnnealingSimulator {
383 config: QuantumAnnealingConfig,
385 current_problem: Option<IsingProblem>,
387 noise_simulator: Option<DeviceNoiseSimulator>,
389 backend: Option<SciRS2Backend>,
391 annealing_history: Vec<AnnealingSnapshot>,
393 solutions: Vec<AnnealingSolution>,
395 stats: AnnealingStats,
397}
398
399#[derive(Debug, Clone)]
401pub struct AnnealingSnapshot {
402 pub time: f64,
404 pub s: f64,
406 pub transverse_field: f64,
408 pub longitudinal_field: f64,
410 pub quantum_state: Option<Array1<Complex64>>,
412 pub classical_probabilities: Option<Array1<f64>>,
414 pub energy_expectation: f64,
416 pub temperature_factor: f64,
418}
419
420#[derive(Debug, Clone)]
422pub struct AnnealingSolution {
423 pub configuration: Vec<i8>,
425 pub energy: f64,
427 pub probability: f64,
429 pub num_occurrences: usize,
431 pub rank: usize,
433}
434
435#[derive(Debug, Clone, Default, Serialize, Deserialize)]
437pub struct AnnealingStats {
438 pub total_annealing_time_ms: f64,
440 pub num_annealing_runs: usize,
442 pub num_solutions_found: usize,
444 pub best_energy_found: f64,
446 pub success_probability: f64,
448 pub time_to_solution: TimeToSolutionStats,
450 pub noise_stats: NoiseStats,
452}
453
454#[derive(Debug, Clone, Default, Serialize, Deserialize)]
456pub struct TimeToSolutionStats {
457 pub median_tts: f64,
459 pub percentile_99_tts: f64,
461 pub success_rate: f64,
463}
464
465#[derive(Debug, Clone, Default, Serialize, Deserialize)]
467pub struct NoiseStats {
468 pub thermal_excitations: usize,
470 pub control_errors: usize,
472 pub decoherence_events: usize,
474}
475
476impl QuantumAnnealingSimulator {
477 pub fn new(config: QuantumAnnealingConfig) -> Result<Self> {
479 Ok(Self {
480 config,
481 current_problem: None,
482 noise_simulator: None,
483 backend: None,
484 annealing_history: Vec::new(),
485 solutions: Vec::new(),
486 stats: AnnealingStats::default(),
487 })
488 }
489
490 pub fn with_backend(mut self) -> Result<Self> {
492 self.backend = Some(SciRS2Backend::new());
493 Ok(self)
494 }
495
496 pub fn set_problem(&mut self, problem: IsingProblem) -> Result<()> {
498 let max_spins = match &self.config.topology {
500 AnnealingTopology::Chimera(size) => size * size * 8,
501 AnnealingTopology::Pegasus(size) => size * (size - 1) * 12,
502 AnnealingTopology::Zephyr(size) => size * size * 8,
503 AnnealingTopology::Complete(size) => *size,
504 AnnealingTopology::Custom(topology) => topology.num_qubits,
505 };
506
507 if problem.num_spins > max_spins {
508 return Err(SimulatorError::InvalidInput(format!(
509 "Problem size {} exceeds topology limit {}",
510 problem.num_spins, max_spins
511 )));
512 }
513
514 self.current_problem = Some(problem);
515 Ok(())
516 }
517
518 pub fn anneal(&mut self, num_reads: usize) -> Result<AnnealingResult> {
520 let problem = self
521 .current_problem
522 .as_ref()
523 .ok_or_else(|| SimulatorError::InvalidInput("No problem set".to_string()))?;
524
525 let start_time = std::time::Instant::now();
526 self.solutions.clear();
527
528 for read in 0..num_reads {
529 let read_start = std::time::Instant::now();
530
531 let solution = self.single_anneal(read)?;
533 self.solutions.push(solution);
534
535 if read % 100 == 0 {
536 println!(
537 "Completed read {}/{}, time={:.2}ms",
538 read,
539 num_reads,
540 read_start.elapsed().as_secs_f64() * 1000.0
541 );
542 }
543 }
544
545 if self.config.post_processing.enable_majority_vote {
547 self.apply_majority_vote_post_processing()?;
548 }
549
550 if self.config.post_processing.enable_local_search {
551 self.apply_local_search_post_processing()?;
552 }
553
554 self.solutions
556 .sort_by(|a, b| a.energy.partial_cmp(&b.energy).unwrap());
557
558 for (rank, solution) in self.solutions.iter_mut().enumerate() {
560 solution.rank = rank;
561 }
562
563 self.compute_annealing_statistics()?;
565
566 let total_time = start_time.elapsed().as_secs_f64() * 1000.0;
567 self.stats.total_annealing_time_ms += total_time;
568 self.stats.num_annealing_runs += num_reads;
569
570 Ok(AnnealingResult {
571 solutions: self.solutions.clone(),
572 best_energy: self.solutions.first().map_or(f64::INFINITY, |s| s.energy),
573 annealing_history: self.annealing_history.clone(),
574 total_time_ms: total_time,
575 success_probability: self.stats.success_probability,
576 time_to_solution: self.stats.time_to_solution.clone(),
577 })
578 }
579
580 fn single_anneal(&mut self, read_id: usize) -> Result<AnnealingSolution> {
582 let problem_num_spins = self.current_problem.as_ref().unwrap().num_spins;
583
584 let state_size = 1 << problem_num_spins.min(20); let mut quantum_state = if problem_num_spins <= 20 {
587 let mut state = Array1::zeros(state_size);
588 let amplitude = (1.0 / state_size as f64).sqrt();
590 state.fill(Complex64::new(amplitude, 0.0));
591 Some(state)
592 } else {
593 None };
595
596 let dt = self.config.annealing_time / self.config.time_steps as f64;
597 self.annealing_history.clear();
598
599 for step in 0..=self.config.time_steps {
601 let t = step as f64 * dt;
602 let s = self.schedule_function(t);
603
604 let (transverse_field, longitudinal_field) = self.calculate_field_strengths(s);
606
607 if let Some(ref mut state) = quantum_state {
609 self.apply_quantum_evolution(state, transverse_field, longitudinal_field, dt)?;
610
611 if self.config.enable_noise {
613 self.apply_annealing_noise(state, dt)?;
614 }
615 }
616
617 if step % (self.config.time_steps / 100) == 0 {
619 let snapshot = self.take_annealing_snapshot(
620 t,
621 s,
622 transverse_field,
623 longitudinal_field,
624 &quantum_state,
625 )?;
626 self.annealing_history.push(snapshot);
627 }
628 }
629
630 let final_configuration = if let Some(ref state) = quantum_state {
632 self.measure_final_state(state)?
633 } else {
634 let problem = self.current_problem.as_ref().unwrap();
636 self.classical_sampling(problem)?
637 };
638
639 let energy = self
640 .current_problem
641 .as_ref()
642 .unwrap()
643 .calculate_energy(&final_configuration);
644
645 Ok(AnnealingSolution {
646 configuration: final_configuration,
647 energy,
648 probability: 1.0 / (self.config.time_steps as f64), num_occurrences: 1,
650 rank: 0,
651 })
652 }
653
654 fn schedule_function(&self, t: f64) -> f64 {
656 let normalized_t = t / self.config.annealing_time;
657
658 match self.config.schedule_type {
659 AnnealingScheduleType::Linear => normalized_t,
660 AnnealingScheduleType::DWave => {
661 if normalized_t < 0.1 {
663 5.0 * normalized_t * normalized_t
664 } else if normalized_t < 0.9 {
665 0.05 + 0.9 * (normalized_t - 0.1) / 0.8
666 } else {
667 0.05f64.mul_add(
668 1.0 - (1.0 - normalized_t) * (1.0 - normalized_t) / 0.01,
669 0.95,
670 )
671 }
672 }
673 AnnealingScheduleType::Optimized => {
674 self.optimized_schedule(normalized_t)
676 }
677 AnnealingScheduleType::CustomPause {
678 pause_start,
679 pause_duration,
680 } => {
681 if normalized_t >= pause_start && normalized_t <= pause_start + pause_duration {
682 pause_start } else if normalized_t > pause_start + pause_duration {
684 (normalized_t - pause_duration - pause_start) / (1.0 - pause_duration)
685 } else {
686 normalized_t / pause_start
687 }
688 }
689 AnnealingScheduleType::NonMonotonic => {
690 (0.1 * (10.0 * std::f64::consts::PI * normalized_t).sin())
692 .mul_add(1.0 - normalized_t, normalized_t)
693 }
694 AnnealingScheduleType::Reverse { reinitialize_point } => {
695 if normalized_t < reinitialize_point {
696 1.0 } else {
698 1.0 - (normalized_t - reinitialize_point) / (1.0 - reinitialize_point)
699 }
700 }
701 }
702 }
703
704 fn optimized_schedule(&self, t: f64) -> f64 {
706 if t < 0.3 {
709 t * t / 0.09 * 0.3
710 } else if t < 0.7 {
711 0.3 + (t - 0.3) * 0.4 / 0.4
712 } else {
713 ((t - 0.7) * (t - 0.7) / 0.09).mul_add(0.3, 0.7)
714 }
715 }
716
717 fn calculate_field_strengths(&self, s: f64) -> (f64, f64) {
719 let a_s = (1.0 - s) * 1.0; let b_s = s * 1.0; (a_s, b_s)
723 }
724
725 fn apply_quantum_evolution(
727 &mut self,
728 state: &mut Array1<Complex64>,
729 transverse_field: f64,
730 longitudinal_field: f64,
731 dt: f64,
732 ) -> Result<()> {
733 let problem = self.current_problem.as_ref().unwrap();
734 let num_spins = problem.num_spins;
735
736 let hamiltonian = self.build_annealing_hamiltonian(transverse_field, longitudinal_field)?;
738
739 let evolution_operator = self.compute_evolution_operator(&hamiltonian, dt)?;
741 *state = evolution_operator.dot(state);
742
743 let norm: f64 = state.iter().map(|x| x.norm_sqr()).sum::<f64>().sqrt();
745 if norm > 1e-15 {
746 state.mapv_inplace(|x| x / norm);
747 }
748
749 Ok(())
750 }
751
752 fn build_annealing_hamiltonian(
754 &self,
755 transverse_field: f64,
756 longitudinal_field: f64,
757 ) -> Result<Array2<Complex64>> {
758 let problem = self.current_problem.as_ref().unwrap();
759 let num_spins = problem.num_spins;
760 let dim = 1 << num_spins;
761 let mut hamiltonian = Array2::zeros((dim, dim));
762
763 for spin in 0..num_spins {
765 let sigma_x = self.build_sigma_x(spin, num_spins);
766 hamiltonian = hamiltonian - sigma_x.mapv(|x| x * transverse_field);
767 }
768
769 let problem_hamiltonian = self.build_problem_hamiltonian()?;
771 hamiltonian = hamiltonian + problem_hamiltonian.mapv(|x| x * longitudinal_field);
772
773 Ok(hamiltonian)
774 }
775
776 fn build_sigma_x(&self, target_spin: usize, num_spins: usize) -> Array2<Complex64> {
778 let dim = 1 << num_spins;
779 let mut sigma_x = Array2::zeros((dim, dim));
780
781 for i in 0..dim {
782 let j = i ^ (1 << target_spin); sigma_x[[i, j]] = Complex64::new(1.0, 0.0);
784 }
785
786 sigma_x
787 }
788
789 fn build_problem_hamiltonian(&self) -> Result<Array2<Complex64>> {
791 let problem = self.current_problem.as_ref().unwrap();
792 let num_spins = problem.num_spins;
793 let dim = 1 << num_spins;
794 let mut hamiltonian = Array2::zeros((dim, dim));
795
796 for i in 0..num_spins {
798 let sigma_z = self.build_sigma_z(i, num_spins);
799 hamiltonian = hamiltonian + sigma_z.mapv(|x| x * problem.h[i]);
800 }
801
802 for i in 0..num_spins {
804 for j in i + 1..num_spins {
805 if problem.j[[i, j]] != 0.0 {
806 let sigma_z_i = self.build_sigma_z(i, num_spins);
807 let sigma_z_j = self.build_sigma_z(j, num_spins);
808 let sigma_z_ij = sigma_z_i.dot(&sigma_z_j);
809 hamiltonian = hamiltonian + sigma_z_ij.mapv(|x| x * problem.j[[i, j]]);
810 }
811 }
812 }
813
814 for i in 0..dim {
816 hamiltonian[[i, i]] += Complex64::new(problem.offset, 0.0);
817 }
818
819 Ok(hamiltonian)
820 }
821
822 fn build_sigma_z(&self, target_spin: usize, num_spins: usize) -> Array2<Complex64> {
824 let dim = 1 << num_spins;
825 let mut sigma_z = Array2::zeros((dim, dim));
826
827 for i in 0..dim {
828 let sign = if (i >> target_spin) & 1 == 0 {
829 1.0
830 } else {
831 -1.0
832 };
833 sigma_z[[i, i]] = Complex64::new(sign, 0.0);
834 }
835
836 sigma_z
837 }
838
839 fn compute_evolution_operator(
841 &self,
842 hamiltonian: &Array2<Complex64>,
843 dt: f64,
844 ) -> Result<Array2<Complex64>> {
845 self.matrix_exponential(hamiltonian, -Complex64::new(0.0, dt))
847 }
848
849 fn matrix_exponential(
851 &self,
852 matrix: &Array2<Complex64>,
853 factor: Complex64,
854 ) -> Result<Array2<Complex64>> {
855 let dim = matrix.dim().0;
856 let scaled_matrix = matrix.mapv(|x| x * factor);
857
858 let mut result = Array2::eye(dim);
859 let mut term = Array2::eye(dim);
860
861 for n in 1..=15 {
862 term = term.dot(&scaled_matrix) / (n as f64);
864 let term_norm: f64 = term.iter().map(|x| x.norm_sqr()).sum::<f64>().sqrt();
865
866 result += &term;
867
868 if term_norm < 1e-12 {
869 break;
870 }
871 }
872
873 Ok(result)
874 }
875
876 fn apply_annealing_noise(&mut self, state: &mut Array1<Complex64>, dt: f64) -> Result<()> {
878 if self.config.enable_thermal_fluctuations {
879 self.apply_thermal_noise(state, dt)?;
880 self.stats.noise_stats.thermal_excitations += 1;
881 }
882
883 if self.config.enable_control_errors {
884 self.apply_control_error_noise(state, dt)?;
885 self.stats.noise_stats.control_errors += 1;
886 }
887
888 self.apply_decoherence_noise(state, dt)?;
890 self.stats.noise_stats.decoherence_events += 1;
891
892 Ok(())
893 }
894
895 fn apply_thermal_noise(&self, state: &mut Array1<Complex64>, dt: f64) -> Result<()> {
897 let kb_t = 1.38e-23 * self.config.temperature; let thermal_energy = kb_t * dt * 1e6; for amplitude in state.iter_mut() {
902 let thermal_phase = fastrand::f64() * thermal_energy * 2.0 * std::f64::consts::PI;
903 *amplitude *= Complex64::new(0.0, thermal_phase).exp();
904 }
905
906 Ok(())
907 }
908
909 fn apply_control_error_noise(&self, state: &mut Array1<Complex64>, dt: f64) -> Result<()> {
911 let error_strength = 0.01; let problem = self.current_problem.as_ref().unwrap();
916 for spin in 0..problem.num_spins.min(10) {
917 if fastrand::f64() < error_strength * dt {
919 let error_angle = fastrand::f64() * 0.1; self.apply_single_spin_rotation(state, spin, error_angle)?;
921 }
922 }
923
924 Ok(())
925 }
926
927 fn apply_decoherence_noise(&self, state: &mut Array1<Complex64>, dt: f64) -> Result<()> {
929 let decoherence_rate = 1e-3; let decoherence_prob = decoherence_rate * dt;
931
932 for amplitude in state.iter_mut() {
933 if fastrand::f64() < decoherence_prob {
934 let phase = fastrand::f64() * 2.0 * std::f64::consts::PI;
936 *amplitude *= Complex64::new(0.0, phase).exp();
937 }
938 }
939
940 Ok(())
941 }
942
943 fn apply_single_spin_rotation(
945 &self,
946 state: &mut Array1<Complex64>,
947 spin: usize,
948 angle: f64,
949 ) -> Result<()> {
950 let problem = self.current_problem.as_ref().unwrap();
951 let spin_mask = 1 << spin;
952 let cos_half = (angle / 2.0).cos();
953 let sin_half = (angle / 2.0).sin();
954
955 for i in 0..state.len() {
956 if i & spin_mask == 0 {
957 let j = i | spin_mask;
958 if j < state.len() {
959 let amp_0 = state[i];
960 let amp_1 = state[j];
961
962 state[i] = cos_half * amp_0 - Complex64::new(0.0, sin_half) * amp_1;
963 state[j] = cos_half * amp_1 - Complex64::new(0.0, sin_half) * amp_0;
964 }
965 }
966 }
967
968 Ok(())
969 }
970
971 fn take_annealing_snapshot(
973 &self,
974 time: f64,
975 s: f64,
976 transverse_field: f64,
977 longitudinal_field: f64,
978 quantum_state: &Option<Array1<Complex64>>,
979 ) -> Result<AnnealingSnapshot> {
980 let energy_expectation = if let Some(state) = quantum_state {
981 self.calculate_energy_expectation(state)?
982 } else {
983 0.0
984 };
985
986 let temperature_factor = (-1.0 / (1.38e-23 * self.config.temperature)).exp();
987
988 Ok(AnnealingSnapshot {
989 time,
990 s,
991 transverse_field,
992 longitudinal_field,
993 quantum_state: quantum_state.clone(),
994 classical_probabilities: None,
995 energy_expectation,
996 temperature_factor,
997 })
998 }
999
1000 fn calculate_energy_expectation(&self, state: &Array1<Complex64>) -> Result<f64> {
1002 let problem = self.current_problem.as_ref().unwrap();
1003 let mut expectation = 0.0;
1004
1005 for (i, &litude) in state.iter().enumerate() {
1006 let prob = amplitude.norm_sqr();
1007
1008 let mut config = vec![-1; problem.num_spins];
1010 for spin in 0..problem.num_spins {
1011 if (i >> spin) & 1 == 1 {
1012 config[spin] = 1;
1013 }
1014 }
1015
1016 let energy = problem.calculate_energy(&config);
1017 expectation += prob * energy;
1018 }
1019
1020 Ok(expectation)
1021 }
1022
1023 fn measure_final_state(&self, state: &Array1<Complex64>) -> Result<Vec<i8>> {
1025 let problem = self.current_problem.as_ref().unwrap();
1026
1027 let probabilities: Vec<f64> = state.iter().map(|x| x.norm_sqr()).collect();
1029 let random_val = fastrand::f64();
1030
1031 let mut cumulative_prob = 0.0;
1032 for (i, &prob) in probabilities.iter().enumerate() {
1033 cumulative_prob += prob;
1034 if random_val < cumulative_prob {
1035 let mut config = vec![-1; problem.num_spins];
1037 for spin in 0..problem.num_spins {
1038 if (i >> spin) & 1 == 1 {
1039 config[spin] = 1;
1040 }
1041 }
1042 return Ok(config);
1043 }
1044 }
1045
1046 Ok(vec![-1; problem.num_spins])
1048 }
1049
1050 fn classical_sampling(&self, problem: &IsingProblem) -> Result<Vec<i8>> {
1052 let mut config: Vec<i8> = (0..problem.num_spins)
1054 .map(|_| if fastrand::f64() > 0.5 { 1 } else { -1 })
1055 .collect();
1056
1057 for _ in 0..1000 {
1059 let spin_to_flip = fastrand::usize(0..problem.num_spins);
1060 let old_energy = problem.calculate_energy(&config);
1061
1062 config[spin_to_flip] *= -1;
1063 let new_energy = problem.calculate_energy(&config);
1064
1065 if new_energy > old_energy {
1066 config[spin_to_flip] *= -1; }
1068 }
1069
1070 Ok(config)
1071 }
1072
1073 fn apply_majority_vote_post_processing(&mut self) -> Result<()> {
1075 if self.solutions.is_empty() {
1076 return Ok(());
1077 }
1078
1079 let mut config_groups: HashMap<Vec<i8>, Vec<usize>> = HashMap::new();
1081 for (i, solution) in self.solutions.iter().enumerate() {
1082 config_groups
1083 .entry(solution.configuration.clone())
1084 .or_default()
1085 .push(i);
1086 }
1087
1088 for (config, indices) in config_groups {
1090 let num_occurrences = indices.len();
1091 for &idx in &indices {
1092 self.solutions[idx].num_occurrences = num_occurrences;
1093 }
1094 }
1095
1096 Ok(())
1097 }
1098
1099 fn apply_local_search_post_processing(&mut self) -> Result<()> {
1101 let problem = self.current_problem.as_ref().unwrap();
1102
1103 for solution in &mut self.solutions {
1104 let mut improved_config = solution.configuration.clone();
1105 let mut improved_energy = solution.energy;
1106
1107 for _ in 0..self.config.post_processing.max_local_search_iterations {
1108 let mut found_improvement = false;
1109
1110 for spin in 0..problem.num_spins {
1111 improved_config[spin] *= -1;
1113 let new_energy = problem.calculate_energy(&improved_config);
1114
1115 if new_energy < improved_energy {
1116 improved_energy = new_energy;
1117 found_improvement = true;
1118 break;
1119 }
1120 improved_config[spin] *= -1; }
1122
1123 if !found_improvement {
1124 break;
1125 }
1126 }
1127
1128 if improved_energy < solution.energy {
1130 solution.configuration = improved_config;
1131 solution.energy = improved_energy;
1132 }
1133 }
1134
1135 Ok(())
1136 }
1137
1138 fn compute_annealing_statistics(&mut self) -> Result<()> {
1140 if self.solutions.is_empty() {
1141 return Ok(());
1142 }
1143
1144 self.stats.num_solutions_found = self.solutions.len();
1145 self.stats.best_energy_found = self
1146 .solutions
1147 .iter()
1148 .map(|s| s.energy)
1149 .fold(f64::INFINITY, f64::min);
1150
1151 if let Some(optimal_energy) = self
1153 .current_problem
1154 .as_ref()
1155 .and_then(|p| p.metadata.optimal_energy)
1156 {
1157 let tolerance = 1e-6;
1158 let successful_solutions = self
1159 .solutions
1160 .iter()
1161 .filter(|s| (s.energy - optimal_energy).abs() < tolerance)
1162 .count();
1163 self.stats.success_probability =
1164 successful_solutions as f64 / self.solutions.len() as f64;
1165 }
1166
1167 Ok(())
1168 }
1169
1170 pub const fn get_stats(&self) -> &AnnealingStats {
1172 &self.stats
1173 }
1174
1175 pub fn reset_stats(&mut self) {
1177 self.stats = AnnealingStats::default();
1178 }
1179}
1180
1181#[derive(Debug, Clone)]
1183pub struct AnnealingResult {
1184 pub solutions: Vec<AnnealingSolution>,
1186 pub best_energy: f64,
1188 pub annealing_history: Vec<AnnealingSnapshot>,
1190 pub total_time_ms: f64,
1192 pub success_probability: f64,
1194 pub time_to_solution: TimeToSolutionStats,
1196}
1197
1198pub struct QuantumAnnealingUtils;
1200
1201impl QuantumAnnealingUtils {
1202 pub fn create_max_cut_problem(graph_edges: &[(usize, usize)], weights: &[f64]) -> IsingProblem {
1204 let num_vertices = graph_edges
1205 .iter()
1206 .flat_map(|&(u, v)| [u, v])
1207 .max()
1208 .unwrap_or(0)
1209 + 1;
1210
1211 let mut problem = IsingProblem::new(num_vertices);
1212 problem.metadata.name = Some("Max-Cut".to_string());
1213
1214 for (i, &(u, v)) in graph_edges.iter().enumerate() {
1215 let weight = weights.get(i).copied().unwrap_or(1.0);
1216 problem.set_j(u, v, weight / 2.0);
1219 problem.offset -= weight / 2.0;
1220 }
1221
1222 problem
1223 }
1224
1225 pub fn create_number_partitioning_problem(numbers: &[f64]) -> IsingProblem {
1227 let n = numbers.len();
1228 let mut problem = IsingProblem::new(n);
1229 problem.metadata.name = Some("Number Partitioning".to_string());
1230
1231 for i in 0..n {
1233 problem.offset += numbers[i] * numbers[i];
1234 for j in i + 1..n {
1235 problem.set_j(i, j, 2.0 * numbers[i] * numbers[j]);
1236 }
1237 }
1238
1239 problem
1240 }
1241
1242 pub fn create_random_ising_problem(
1244 num_spins: usize,
1245 h_range: f64,
1246 j_range: f64,
1247 ) -> IsingProblem {
1248 let mut problem = IsingProblem::new(num_spins);
1249 problem.metadata.name = Some("Random Ising".to_string());
1250
1251 for i in 0..num_spins {
1253 problem.set_h(i, (fastrand::f64() - 0.5) * 2.0 * h_range);
1254 }
1255
1256 for i in 0..num_spins {
1258 for j in i + 1..num_spins {
1259 if fastrand::f64() < 0.5 {
1260 problem.set_j(i, j, (fastrand::f64() - 0.5) * 2.0 * j_range);
1262 }
1263 }
1264 }
1265
1266 problem
1267 }
1268
1269 pub fn benchmark_quantum_annealing() -> Result<AnnealingBenchmarkResults> {
1271 let mut results = AnnealingBenchmarkResults::default();
1272
1273 let problem_sizes = vec![8, 12, 16];
1274 let annealing_times = vec![1.0, 10.0, 100.0]; for &size in &problem_sizes {
1277 for &time in &annealing_times {
1278 let problem = Self::create_random_ising_problem(size, 1.0, 1.0);
1280
1281 let config = QuantumAnnealingConfig {
1282 annealing_time: time,
1283 time_steps: (time * 100.0) as usize,
1284 topology: AnnealingTopology::Complete(size),
1285 ..Default::default()
1286 };
1287
1288 let mut simulator = QuantumAnnealingSimulator::new(config)?;
1289 simulator.set_problem(problem)?;
1290
1291 let start = std::time::Instant::now();
1292 let result = simulator.anneal(100)?;
1293 let execution_time = start.elapsed().as_secs_f64() * 1000.0;
1294
1295 results
1296 .execution_times
1297 .push((format!("{size}spins_{time}us"), execution_time));
1298 results
1299 .best_energies
1300 .push((format!("{size}spins_{time}us"), result.best_energy));
1301 }
1302 }
1303
1304 Ok(results)
1305 }
1306}
1307
1308#[derive(Debug, Clone, Default)]
1310pub struct AnnealingBenchmarkResults {
1311 pub execution_times: Vec<(String, f64)>,
1313 pub best_energies: Vec<(String, f64)>,
1315}
1316
1317#[cfg(test)]
1318mod tests {
1319 use super::*;
1320 use approx::assert_abs_diff_eq;
1321
1322 #[test]
1323 fn test_ising_problem_creation() {
1324 let mut problem = IsingProblem::new(3);
1325 problem.set_h(0, 0.5);
1326 problem.set_j(0, 1, -1.0);
1327
1328 assert_eq!(problem.num_spins, 3);
1329 assert_eq!(problem.h[0], 0.5);
1330 assert_eq!(problem.j[[0, 1]], -1.0);
1331 assert_eq!(problem.j[[1, 0]], -1.0);
1332 }
1333
1334 #[test]
1335 fn test_ising_energy_calculation() {
1336 let mut problem = IsingProblem::new(2);
1337 problem.set_h(0, 1.0);
1338 problem.set_h(1, -0.5);
1339 problem.set_j(0, 1, 2.0);
1340
1341 let config = vec![1, -1];
1342 let energy = problem.calculate_energy(&config);
1343 assert_abs_diff_eq!(energy, -0.5, epsilon = 1e-10);
1347 }
1348
1349 #[test]
1350 fn test_ising_to_qubo_conversion() {
1351 let mut ising = IsingProblem::new(2);
1352 ising.set_h(0, 1.0);
1353 ising.set_j(0, 1, -1.0);
1354
1355 let qubo = ising.to_qubo();
1356 assert_eq!(qubo.num_variables, 2);
1357
1358 let ising_config = vec![1, -1];
1360 let qubo_config = vec![1, 0]; let ising_energy = ising.calculate_energy(&ising_config);
1363 let qubo_energy = qubo.calculate_energy(&qubo_config);
1364 assert_abs_diff_eq!(ising_energy, qubo_energy, epsilon = 1e-10);
1365 }
1366
1367 #[test]
1368 fn test_quantum_annealing_simulator_creation() {
1369 let config = QuantumAnnealingConfig::default();
1370 let simulator = QuantumAnnealingSimulator::new(config);
1371 assert!(simulator.is_ok());
1372 }
1373
1374 #[test]
1375 fn test_schedule_functions() {
1376 let config = QuantumAnnealingConfig {
1377 annealing_time: 10.0,
1378 schedule_type: AnnealingScheduleType::Linear,
1379 ..Default::default()
1380 };
1381 let simulator = QuantumAnnealingSimulator::new(config).unwrap();
1382
1383 assert_abs_diff_eq!(simulator.schedule_function(0.0), 0.0, epsilon = 1e-10);
1384 assert_abs_diff_eq!(simulator.schedule_function(5.0), 0.5, epsilon = 1e-10);
1385 assert_abs_diff_eq!(simulator.schedule_function(10.0), 1.0, epsilon = 1e-10);
1386 }
1387
1388 #[test]
1389 fn test_max_cut_problem_creation() {
1390 let edges = vec![(0, 1), (1, 2), (2, 0)];
1391 let weights = vec![1.0, 1.0, 1.0];
1392
1393 let problem = QuantumAnnealingUtils::create_max_cut_problem(&edges, &weights);
1394 assert_eq!(problem.num_spins, 3);
1395 assert!(problem.metadata.name.as_ref().unwrap().contains("Max-Cut"));
1396 }
1397
1398 #[test]
1399 fn test_number_partitioning_problem() {
1400 let numbers = vec![3.0, 1.0, 1.0, 2.0, 2.0, 1.0];
1401 let problem = QuantumAnnealingUtils::create_number_partitioning_problem(&numbers);
1402
1403 assert_eq!(problem.num_spins, 6);
1404 assert!(problem
1405 .metadata
1406 .name
1407 .as_ref()
1408 .unwrap()
1409 .contains("Number Partitioning"));
1410 }
1411
1412 #[test]
1413 fn test_small_problem_annealing() {
1414 let problem = QuantumAnnealingUtils::create_random_ising_problem(3, 1.0, 1.0);
1415
1416 let config = QuantumAnnealingConfig {
1417 annealing_time: 1.0,
1418 time_steps: 100,
1419 topology: AnnealingTopology::Complete(3),
1420 enable_noise: false, ..Default::default()
1422 };
1423
1424 let mut simulator = QuantumAnnealingSimulator::new(config).unwrap();
1425 simulator.set_problem(problem).unwrap();
1426
1427 let result = simulator.anneal(10);
1428 assert!(result.is_ok());
1429
1430 let annealing_result = result.unwrap();
1431 assert_eq!(annealing_result.solutions.len(), 10);
1432 assert!(!annealing_result.annealing_history.is_empty());
1433 }
1434
1435 #[test]
1436 fn test_field_strength_calculation() {
1437 let config = QuantumAnnealingConfig::default();
1438 let simulator = QuantumAnnealingSimulator::new(config).unwrap();
1439
1440 let (transverse, longitudinal) = simulator.calculate_field_strengths(0.0);
1441 assert_abs_diff_eq!(transverse, 1.0, epsilon = 1e-10);
1442 assert_abs_diff_eq!(longitudinal, 0.0, epsilon = 1e-10);
1443
1444 let (transverse, longitudinal) = simulator.calculate_field_strengths(1.0);
1445 assert_abs_diff_eq!(transverse, 0.0, epsilon = 1e-10);
1446 assert_abs_diff_eq!(longitudinal, 1.0, epsilon = 1e-10);
1447 }
1448
1449 #[test]
1450 fn test_annealing_topologies() {
1451 let topologies = vec![
1452 AnnealingTopology::Chimera(4),
1453 AnnealingTopology::Pegasus(3),
1454 AnnealingTopology::Complete(5),
1455 ];
1456
1457 for topology in topologies {
1458 let config = QuantumAnnealingConfig {
1459 topology,
1460 ..Default::default()
1461 };
1462 let simulator = QuantumAnnealingSimulator::new(config);
1463 assert!(simulator.is_ok());
1464 }
1465 }
1466
1467 #[test]
1468 fn test_ising_ground_state_brute_force() {
1469 let mut problem = IsingProblem::new(2);
1471 problem.set_j(0, 1, -1.0); let (ground_state, ground_energy) = problem.find_ground_state_brute_force();
1474
1475 assert!(ground_state == vec![1, 1] || ground_state == vec![-1, -1]);
1477 assert_abs_diff_eq!(ground_energy, -1.0, epsilon = 1e-10);
1478 }
1479
1480 #[test]
1481 fn test_post_processing_config() {
1482 let config = PostProcessingConfig::default();
1483 assert!(config.enable_spin_reversal);
1484 assert!(config.enable_local_search);
1485 assert!(config.enable_majority_vote);
1486 assert_eq!(config.majority_vote_reads, 1000);
1487 }
1488}