quantrs2_sim/
quantum_annealing.rs

1//! Quantum annealing simulation with realistic noise models and hardware constraints.
2//!
3//! This module implements comprehensive quantum annealing simulation that accurately
4//! models real quantum annealing hardware including thermal noise, decoherence,
5//! control errors, and hardware topology constraints. It supports various
6//! optimization problems (QUBO, Ising, etc.) and provides realistic simulation
7//! of quantum annealing devices like D-Wave systems.
8
9use 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/// Quantum annealing configuration
21#[derive(Debug, Clone)]
22pub struct QuantumAnnealingConfig {
23    /// Total annealing time (μs)
24    pub annealing_time: f64,
25    /// Number of time steps
26    pub time_steps: usize,
27    /// Annealing schedule type
28    pub schedule_type: AnnealingScheduleType,
29    /// Problem formulation
30    pub problem_type: ProblemType,
31    /// Hardware topology
32    pub topology: AnnealingTopology,
33    /// Temperature (K)
34    pub temperature: f64,
35    /// Enable realistic noise models
36    pub enable_noise: bool,
37    /// Enable thermal fluctuations
38    pub enable_thermal_fluctuations: bool,
39    /// Enable control errors
40    pub enable_control_errors: bool,
41    /// Enable gauge transformations
42    pub enable_gauge_transformations: bool,
43    /// Post-processing configuration
44    pub post_processing: PostProcessingConfig,
45}
46
47impl Default for QuantumAnnealingConfig {
48    fn default() -> Self {
49        Self {
50            annealing_time: 20.0, // 20 μs (typical D-Wave)
51            time_steps: 2000,
52            schedule_type: AnnealingScheduleType::DWave,
53            problem_type: ProblemType::Ising,
54            topology: AnnealingTopology::Chimera(16),
55            temperature: 0.015, // 15 mK
56            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/// Annealing schedule types
66#[derive(Debug, Clone, Copy, PartialEq)]
67pub enum AnnealingScheduleType {
68    /// Linear schedule
69    Linear,
70    /// D-Wave like schedule with pause
71    DWave,
72    /// Optimized schedule for specific problems
73    Optimized,
74    /// Custom schedule with pause features
75    CustomPause {
76        pause_start: f64,
77        pause_duration: f64,
78    },
79    /// Non-monotonic schedule
80    NonMonotonic,
81    /// Reverse annealing
82    Reverse { reinitialize_point: f64 },
83}
84
85/// Problem types for quantum annealing
86#[derive(Debug, Clone, PartialEq, Eq)]
87pub enum ProblemType {
88    /// Ising model
89    Ising,
90    /// Quadratic Unconstrained Binary Optimization
91    QUBO,
92    /// Maximum Cut
93    MaxCut,
94    /// Graph Coloring
95    GraphColoring,
96    /// Traveling Salesman Problem
97    TSP,
98    /// Number Partitioning
99    NumberPartitioning,
100    /// Custom optimization problem
101    Custom(String),
102}
103
104/// Annealing hardware topologies
105#[derive(Debug, Clone, PartialEq)]
106pub enum AnnealingTopology {
107    /// D-Wave Chimera topology
108    Chimera(usize), // Parameter is the size
109    /// D-Wave Pegasus topology
110    Pegasus(usize),
111    /// D-Wave Zephyr topology
112    Zephyr(usize),
113    /// Complete graph
114    Complete(usize),
115    /// Custom topology
116    Custom(DeviceTopology),
117}
118
119/// Post-processing configuration
120#[derive(Debug, Clone)]
121pub struct PostProcessingConfig {
122    /// Enable spin reversal transformations
123    pub enable_spin_reversal: bool,
124    /// Enable local search optimization
125    pub enable_local_search: bool,
126    /// Maximum local search iterations
127    pub max_local_search_iterations: usize,
128    /// Enable majority vote post-processing
129    pub enable_majority_vote: bool,
130    /// Number of reads for majority vote
131    pub majority_vote_reads: usize,
132    /// Enable energy-based filtering
133    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/// Ising problem representation
150#[derive(Debug, Clone)]
151pub struct IsingProblem {
152    /// Number of spins
153    pub num_spins: usize,
154    /// Linear coefficients (h_i)
155    pub h: Array1<f64>,
156    /// Quadratic coefficients (J_{ij})
157    pub j: Array2<f64>,
158    /// Offset constant
159    pub offset: f64,
160    /// Problem metadata
161    pub metadata: ProblemMetadata,
162}
163
164/// QUBO problem representation
165#[derive(Debug, Clone)]
166pub struct QUBOProblem {
167    /// Number of variables
168    pub num_variables: usize,
169    /// QUBO matrix (Q_{ij})
170    pub q: Array2<f64>,
171    /// Linear coefficients
172    pub linear: Array1<f64>,
173    /// Offset constant
174    pub offset: f64,
175    /// Problem metadata
176    pub metadata: ProblemMetadata,
177}
178
179/// Problem metadata
180#[derive(Debug, Clone, Default)]
181pub struct ProblemMetadata {
182    /// Problem name
183    pub name: Option<String>,
184    /// Problem description
185    pub description: Option<String>,
186    /// Known optimal energy
187    pub optimal_energy: Option<f64>,
188    /// Problem difficulty estimate
189    pub difficulty_score: Option<f64>,
190    /// Variable labels
191    pub variable_labels: Vec<String>,
192}
193
194impl IsingProblem {
195    /// Create new Ising problem
196    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    /// Set linear coefficient
207    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    /// Set quadratic coefficient
214    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; // Ensure symmetry
218        }
219    }
220
221    /// Calculate energy for a given configuration
222    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        // Linear terms
230        for i in 0..self.num_spins {
231            energy += self.h[i] * configuration[i] as f64;
232        }
233
234        // Quadratic terms
235        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    /// Convert to QUBO problem
245    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        // Convert Ising to QUBO: s_i = 2x_i - 1
252        // H_Ising = sum_i h_i s_i + sum_{i<j} J_{ij} s_i s_j
253        // H_QUBO = sum_i q_i x_i + sum_{i<j} q_{ij} x_i x_j + const
254
255        for i in 0..num_vars {
256            // Linear terms: h_i s_i = h_i (2x_i - 1) = 2h_i x_i - h_i
257            linear[i] += 2.0 * self.h[i];
258            offset -= self.h[i];
259
260            for j in i + 1..num_vars {
261                // Quadratic terms: J_{ij} s_i s_j = J_{ij} (2x_i - 1)(2x_j - 1)
262                // = 4 J_{ij} x_i x_j - 2 J_{ij} x_i - 2 J_{ij} x_j + J_{ij}
263                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    /// Find ground state using brute force (for small problems)
280    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    /// Create new QUBO problem
310    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    /// Calculate energy for a given binary configuration
321    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        // Linear terms
329        for i in 0..self.num_variables {
330            energy += self.linear[i] * configuration[i] as f64;
331        }
332
333        // Quadratic terms
334        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    /// Convert to Ising problem
346    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        // Convert QUBO to Ising: x_i = (s_i + 1)/2
353        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
381/// Quantum annealing simulator
382pub struct QuantumAnnealingSimulator {
383    /// Configuration
384    config: QuantumAnnealingConfig,
385    /// Current problem
386    current_problem: Option<IsingProblem>,
387    /// Device noise simulator
388    noise_simulator: Option<DeviceNoiseSimulator>,
389    /// SciRS2 backend for optimization
390    backend: Option<SciRS2Backend>,
391    /// Annealing history
392    annealing_history: Vec<AnnealingSnapshot>,
393    /// Final solutions
394    solutions: Vec<AnnealingSolution>,
395    /// Statistics
396    stats: AnnealingStats,
397}
398
399/// Annealing snapshot
400#[derive(Debug, Clone)]
401pub struct AnnealingSnapshot {
402    /// Time parameter
403    pub time: f64,
404    /// Annealing parameter s(t)
405    pub s: f64,
406    /// Transverse field strength
407    pub transverse_field: f64,
408    /// Longitudinal field strength
409    pub longitudinal_field: f64,
410    /// Current quantum state (if tracking)
411    pub quantum_state: Option<Array1<Complex64>>,
412    /// Classical state probabilities
413    pub classical_probabilities: Option<Array1<f64>>,
414    /// Energy expectation value
415    pub energy_expectation: f64,
416    /// Temperature effects
417    pub temperature_factor: f64,
418}
419
420/// Annealing solution
421#[derive(Debug, Clone)]
422pub struct AnnealingSolution {
423    /// Solution configuration
424    pub configuration: Vec<i8>,
425    /// Solution energy
426    pub energy: f64,
427    /// Solution probability
428    pub probability: f64,
429    /// Number of occurrences
430    pub num_occurrences: usize,
431    /// Solution rank
432    pub rank: usize,
433}
434
435/// Annealing simulation statistics
436#[derive(Debug, Clone, Default, Serialize, Deserialize)]
437pub struct AnnealingStats {
438    /// Total annealing time
439    pub total_annealing_time_ms: f64,
440    /// Number of annealing runs
441    pub num_annealing_runs: usize,
442    /// Number of solutions found
443    pub num_solutions_found: usize,
444    /// Best energy found
445    pub best_energy_found: f64,
446    /// Success probability (if ground state known)
447    pub success_probability: f64,
448    /// Time to solution statistics
449    pub time_to_solution: TimeToSolutionStats,
450    /// Noise statistics
451    pub noise_stats: NoiseStats,
452}
453
454/// Time to solution statistics
455#[derive(Debug, Clone, Default, Serialize, Deserialize)]
456pub struct TimeToSolutionStats {
457    /// Median time to solution
458    pub median_tts: f64,
459    /// 99th percentile time to solution
460    pub percentile_99_tts: f64,
461    /// Success rate
462    pub success_rate: f64,
463}
464
465/// Noise statistics
466#[derive(Debug, Clone, Default, Serialize, Deserialize)]
467pub struct NoiseStats {
468    /// Thermal excitation events
469    pub thermal_excitations: usize,
470    /// Control error events
471    pub control_errors: usize,
472    /// Decoherence events
473    pub decoherence_events: usize,
474}
475
476impl QuantumAnnealingSimulator {
477    /// Create new quantum annealing simulator
478    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    /// Initialize with SciRS2 backend
491    pub fn with_backend(mut self) -> Result<Self> {
492        self.backend = Some(SciRS2Backend::new());
493        Ok(self)
494    }
495
496    /// Set problem to solve
497    pub fn set_problem(&mut self, problem: IsingProblem) -> Result<()> {
498        // Validate problem size against topology
499        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    /// Run quantum annealing
519    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            // Run single annealing cycle
532            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        // Post-process solutions
546        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        // Sort solutions by energy
555        self.solutions
556            .sort_by(|a, b| a.energy.partial_cmp(&b.energy).unwrap());
557
558        // Rank solutions
559        for (rank, solution) in self.solutions.iter_mut().enumerate() {
560            solution.rank = rank;
561        }
562
563        // Compute statistics
564        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    /// Run single annealing cycle
581    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        // Initialize quantum state in superposition
585        let state_size = 1 << problem_num_spins.min(20); // Limit for memory
586        let mut quantum_state = if problem_num_spins <= 20 {
587            let mut state = Array1::zeros(state_size);
588            // Initialize in equal superposition
589            let amplitude = (1.0 / state_size as f64).sqrt();
590            state.fill(Complex64::new(amplitude, 0.0));
591            Some(state)
592        } else {
593            None // Use classical approximation for large problems
594        };
595
596        let dt = self.config.annealing_time / self.config.time_steps as f64;
597        self.annealing_history.clear();
598
599        // Annealing evolution
600        for step in 0..=self.config.time_steps {
601            let t = step as f64 * dt;
602            let s = self.schedule_function(t);
603
604            // Calculate field strengths
605            let (transverse_field, longitudinal_field) = self.calculate_field_strengths(s);
606
607            // Apply quantum evolution
608            if let Some(ref mut state) = quantum_state {
609                self.apply_quantum_evolution(state, transverse_field, longitudinal_field, dt)?;
610
611                // Apply noise if enabled
612                if self.config.enable_noise {
613                    self.apply_annealing_noise(state, dt)?;
614                }
615            }
616
617            // Take snapshot
618            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        // Final measurement/sampling
631        let final_configuration = if let Some(ref state) = quantum_state {
632            self.measure_final_state(state)?
633        } else {
634            // Get the problem again for classical sampling
635            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), // Will be updated later
649            num_occurrences: 1,
650            rank: 0,
651        })
652    }
653
654    /// Calculate annealing schedule s(t)
655    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                // D-Wave like schedule with slower start and end
662                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                // Optimized schedule based on problem characteristics
675                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 // Pause at this value
683                } 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                // Non-monotonic schedule with oscillations
691                (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 // Start at problem Hamiltonian
697                } else {
698                    1.0 - (normalized_t - reinitialize_point) / (1.0 - reinitialize_point)
699                }
700            }
701        }
702    }
703
704    /// Optimized schedule function
705    fn optimized_schedule(&self, t: f64) -> f64 {
706        // Simple optimization: slower evolution near avoided crossings
707        // This would be problem-specific in practice
708        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    /// Calculate transverse and longitudinal field strengths
718    fn calculate_field_strengths(&self, s: f64) -> (f64, f64) {
719        // Standard quantum annealing: H(s) = -A(s) ∑_i σ_x^i + B(s) H_problem
720        let a_s = (1.0 - s) * 1.0; // Transverse field strength
721        let b_s = s * 1.0; // Longitudinal field strength
722        (a_s, b_s)
723    }
724
725    /// Apply quantum evolution for one time step
726    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        // Build total Hamiltonian matrix
737        let hamiltonian = self.build_annealing_hamiltonian(transverse_field, longitudinal_field)?;
738
739        // Apply time evolution: |ψ(t+dt)⟩ = exp(-i H dt / ℏ) |ψ(t)⟩
740        let evolution_operator = self.compute_evolution_operator(&hamiltonian, dt)?;
741        *state = evolution_operator.dot(state);
742
743        // Renormalize to handle numerical errors
744        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    /// Build full annealing Hamiltonian
753    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        // Transverse field terms: -A(s) ∑_i σ_x^i
764        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        // Longitudinal field terms: B(s) H_problem
770        let problem_hamiltonian = self.build_problem_hamiltonian()?;
771        hamiltonian = hamiltonian + problem_hamiltonian.mapv(|x| x * longitudinal_field);
772
773        Ok(hamiltonian)
774    }
775
776    /// Build Pauli-X operator for specific spin
777    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); // Flip the target spin
783            sigma_x[[i, j]] = Complex64::new(1.0, 0.0);
784        }
785
786        sigma_x
787    }
788
789    /// Build problem Hamiltonian (Ising model)
790    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        // Linear terms: ∑_i h_i σ_z^i
797        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        // Quadratic terms: ∑_{i<j} J_{ij} σ_z^i σ_z^j
803        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        // Add offset as identity matrix
815        for i in 0..dim {
816            hamiltonian[[i, i]] += Complex64::new(problem.offset, 0.0);
817        }
818
819        Ok(hamiltonian)
820    }
821
822    /// Build Pauli-Z operator for specific spin
823    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    /// Compute time evolution operator
840    fn compute_evolution_operator(
841        &self,
842        hamiltonian: &Array2<Complex64>,
843        dt: f64,
844    ) -> Result<Array2<Complex64>> {
845        // Use matrix exponentiation for small systems
846        self.matrix_exponential(hamiltonian, -Complex64::new(0.0, dt))
847    }
848
849    /// Matrix exponential implementation
850    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            // Limit series expansion
863            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    /// Apply various noise sources during annealing
877    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        // Decoherence
889        self.apply_decoherence_noise(state, dt)?;
890        self.stats.noise_stats.decoherence_events += 1;
891
892        Ok(())
893    }
894
895    /// Apply thermal noise
896    fn apply_thermal_noise(&self, state: &mut Array1<Complex64>, dt: f64) -> Result<()> {
897        // Thermal fluctuations cause random phase evolution
898        let kb_t = 1.38e-23 * self.config.temperature; // Boltzmann constant times temperature
899        let thermal_energy = kb_t * dt * 1e6; // Convert to relevant energy scale
900
901        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    /// Apply control error noise
910    fn apply_control_error_noise(&self, state: &mut Array1<Complex64>, dt: f64) -> Result<()> {
911        // Control errors cause imperfect implementation of the intended Hamiltonian
912        let error_strength = 0.01; // 1% control errors
913
914        // Apply random single-qubit rotations to simulate control errors
915        let problem = self.current_problem.as_ref().unwrap();
916        for spin in 0..problem.num_spins.min(10) {
917            // Limit for performance
918            if fastrand::f64() < error_strength * dt {
919                let error_angle = fastrand::f64() * 0.1; // Small random rotation
920                self.apply_single_spin_rotation(state, spin, error_angle)?;
921            }
922        }
923
924        Ok(())
925    }
926
927    /// Apply decoherence noise
928    fn apply_decoherence_noise(&self, state: &mut Array1<Complex64>, dt: f64) -> Result<()> {
929        let decoherence_rate = 1e-3; // Typical decoherence rate
930        let decoherence_prob = decoherence_rate * dt;
931
932        for amplitude in state.iter_mut() {
933            if fastrand::f64() < decoherence_prob {
934                // Apply random dephasing
935                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    /// Apply single spin rotation
944    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    /// Take annealing snapshot
972    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    /// Calculate energy expectation value
1001    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, &amplitude) in state.iter().enumerate() {
1006            let prob = amplitude.norm_sqr();
1007
1008            // Convert state index to spin configuration
1009            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    /// Measure final quantum state
1024    fn measure_final_state(&self, state: &Array1<Complex64>) -> Result<Vec<i8>> {
1025        let problem = self.current_problem.as_ref().unwrap();
1026
1027        // Sample from the quantum state probability distribution
1028        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                // Convert state index to spin configuration
1036                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        // Fallback to ground state
1047        Ok(vec![-1; problem.num_spins])
1048    }
1049
1050    /// Classical sampling for large problems
1051    fn classical_sampling(&self, problem: &IsingProblem) -> Result<Vec<i8>> {
1052        // Use simulated annealing or other classical heuristics
1053        let mut config: Vec<i8> = (0..problem.num_spins)
1054            .map(|_| if fastrand::f64() > 0.5 { 1 } else { -1 })
1055            .collect();
1056
1057        // Simple local search
1058        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; // Revert if energy increased
1067            }
1068        }
1069
1070        Ok(config)
1071    }
1072
1073    /// Apply majority vote post-processing
1074    fn apply_majority_vote_post_processing(&mut self) -> Result<()> {
1075        if self.solutions.is_empty() {
1076            return Ok(());
1077        }
1078
1079        // Group solutions by configuration
1080        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        // Update occurrence counts
1089        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    /// Apply local search post-processing
1100    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                    // Try flipping this spin
1112                    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; // Revert
1121                }
1122
1123                if !found_improvement {
1124                    break;
1125                }
1126            }
1127
1128            // Update solution if improved
1129            if improved_energy < solution.energy {
1130                solution.configuration = improved_config;
1131                solution.energy = improved_energy;
1132            }
1133        }
1134
1135        Ok(())
1136    }
1137
1138    /// Compute annealing statistics
1139    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        // Calculate success probability if ground state energy is known
1152        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    /// Get annealing statistics
1171    pub const fn get_stats(&self) -> &AnnealingStats {
1172        &self.stats
1173    }
1174
1175    /// Reset statistics
1176    pub fn reset_stats(&mut self) {
1177        self.stats = AnnealingStats::default();
1178    }
1179}
1180
1181/// Annealing result
1182#[derive(Debug, Clone)]
1183pub struct AnnealingResult {
1184    /// All solutions found
1185    pub solutions: Vec<AnnealingSolution>,
1186    /// Best energy found
1187    pub best_energy: f64,
1188    /// Annealing evolution history
1189    pub annealing_history: Vec<AnnealingSnapshot>,
1190    /// Total computation time
1191    pub total_time_ms: f64,
1192    /// Success probability
1193    pub success_probability: f64,
1194    /// Time to solution statistics
1195    pub time_to_solution: TimeToSolutionStats,
1196}
1197
1198/// Quantum annealing utilities
1199pub struct QuantumAnnealingUtils;
1200
1201impl QuantumAnnealingUtils {
1202    /// Create Max-Cut Ising problem
1203    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            // Max-Cut: maximize ∑ w_{ij} (1 - s_i s_j) / 2
1217            // Equivalent to minimizing ∑ w_{ij} (s_i s_j - 1) / 2
1218            problem.set_j(u, v, weight / 2.0);
1219            problem.offset -= weight / 2.0;
1220        }
1221
1222        problem
1223    }
1224
1225    /// Create number partitioning problem
1226    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        // Minimize (∑_i n_i s_i)^2 = ∑_i n_i^2 + 2 ∑_{i<j} n_i n_j s_i s_j
1232        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    /// Create random Ising problem
1243    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        // Random linear coefficients
1252        for i in 0..num_spins {
1253            problem.set_h(i, (fastrand::f64() - 0.5) * 2.0 * h_range);
1254        }
1255
1256        // Random quadratic coefficients
1257        for i in 0..num_spins {
1258            for j in i + 1..num_spins {
1259                if fastrand::f64() < 0.5 {
1260                    // 50% sparsity
1261                    problem.set_j(i, j, (fastrand::f64() - 0.5) * 2.0 * j_range);
1262                }
1263            }
1264        }
1265
1266        problem
1267    }
1268
1269    /// Benchmark quantum annealing
1270    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]; // μs
1275
1276        for &size in &problem_sizes {
1277            for &time in &annealing_times {
1278                // Create random problem
1279                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/// Annealing benchmark results
1309#[derive(Debug, Clone, Default)]
1310pub struct AnnealingBenchmarkResults {
1311    /// Execution times by configuration
1312    pub execution_times: Vec<(String, f64)>,
1313    /// Best energies found
1314    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        // E = h_0 * s_0 + h_1 * s_1 + J_{01} * s_0 * s_1
1344        // E = 1.0 * 1 + (-0.5) * (-1) + 2.0 * 1 * (-1)
1345        // E = 1.0 + 0.5 - 2.0 = -0.5
1346        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        // Test energy equivalence for a configuration
1359        let ising_config = vec![1, -1];
1360        let qubo_config = vec![1, 0]; // s=1 -> x=1, s=-1 -> x=0
1361
1362        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, // Disable for deterministic test
1421            ..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        // Simple 2-spin ferromagnetic Ising model
1470        let mut problem = IsingProblem::new(2);
1471        problem.set_j(0, 1, -1.0); // Ferromagnetic coupling
1472
1473        let (ground_state, ground_energy) = problem.find_ground_state_brute_force();
1474
1475        // Ground states should be [1, 1] or [-1, -1] with energy -1
1476        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}