1use super::types::*;
8use crate::error::InterpolateResult;
9use scirs2_core::ndarray::Array2;
10use scirs2_core::numeric::Float;
11use std::collections::{HashMap, VecDeque};
12use std::fmt::Debug;
13use std::time::Instant;
14
15#[derive(Debug)]
17pub struct QuantumParameterOptimizer<F: Float + Debug> {
18 quantum_state: QuantumState<F>,
20 quantum_operators: Vec<QuantumOperator<F>>,
22 annealing_params: AnnealingParameters<F>,
24 measurement_system: QuantumMeasurement<F>,
26 optimization_history: VecDeque<QuantumOptimizationResult<F>>,
28 state_population: Vec<QuantumState<F>>,
30}
31
32#[derive(Debug, Clone)]
34pub struct QuantumState<F: Float> {
35 pub amplitudes: Vec<(F, F)>, pub phases: Vec<F>,
39 pub entanglement: EntanglementInfo,
41 pub parameter_values: HashMap<String, F>,
43 pub energy: F,
45}
46
47#[derive(Debug, Clone)]
49pub struct EntanglementInfo {
50 pub entangled_pairs: Vec<(usize, usize)>,
52 pub entanglement_strength: f64,
54 pub entanglement_matrix: Option<Vec<Vec<f64>>>,
56}
57
58#[derive(Debug, Clone)]
60pub enum QuantumOperator<F: Float> {
61 Hadamard { parameter: usize },
63 PauliX { parameter: usize },
65 PauliY { parameter: usize },
67 PauliZ { parameter: usize },
69 CNOT { control: usize, target: usize },
71 Rotation { parameter: usize, angle: F },
73 PhaseShift { parameter: usize, phase: F },
75 QFT { parameters: Vec<usize> },
77 Custom {
79 name: String,
80 matrix: Array2<(F, F)>, },
82}
83
84#[derive(Debug, Clone)]
86pub struct AnnealingParameters<F: Float> {
87 pub initial_temperature: F,
89 pub final_temperature: F,
91 pub annealing_schedule: AnnealingSchedule<F>,
93 pub num_steps: usize,
95 pub tunneling_strength: F,
97 pub transverse_field: F,
99}
100
101#[derive(Debug, Clone)]
103pub enum AnnealingSchedule<F: Float> {
104 Linear,
106 Exponential { decay_rate: F },
108 Logarithmic { scale_factor: F },
110 Custom { schedule: Vec<F> },
112 Adaptive {
114 convergence_threshold: F,
115 adaptation_rate: F,
116 },
117}
118
119#[derive(Debug)]
121pub struct QuantumMeasurement<F: Float> {
122 measurement_operators: Vec<MeasurementOperator<F>>,
124 measurement_history: VecDeque<MeasurementResult<F>>,
126 measurement_bases: Vec<MeasurementBasis<F>>,
128}
129
130#[derive(Debug, Clone)]
132pub struct MeasurementOperator<F: Float> {
133 pub name: String,
135 pub operator: Array2<(F, F)>,
137 pub expected_value: Option<F>,
139 pub precision: F,
141}
142
143#[derive(Debug, Clone)]
145pub struct MeasurementResult<F: Float> {
146 pub value: F,
148 pub uncertainty: F,
150 pub basis: String,
152 pub timestamp: Instant,
154 pub probability: F,
156}
157
158#[derive(Debug, Clone)]
160pub struct MeasurementBasis<F: Float> {
161 pub name: String,
163 pub basis_vectors: Vec<Vec<(F, F)>>,
165 pub completeness: F,
167}
168
169#[derive(Debug, Clone)]
171pub struct QuantumOptimizationResult<F: Float> {
172 pub optimized_parameters: HashMap<String, F>,
174 pub final_state: QuantumState<F>,
176 pub energy_history: Vec<F>,
178 pub algorithm_used: QuantumAlgorithm,
180 pub quantum_iterations: usize,
182 pub measurement_stats: MeasurementStatistics<F>,
184 pub success: bool,
186 pub converged: bool,
188}
189
190#[derive(Debug, Clone)]
192pub enum QuantumAlgorithm {
193 QuantumAnnealing,
195 VQE,
197 QAOA,
199 AdiabaticQC,
201 QPE,
203 QAA,
205}
206
207#[derive(Debug, Clone)]
209pub struct MeasurementStatistics<F: Float> {
210 pub mean: F,
212 pub variance: F,
214 pub std_dev: F,
216 pub sample_count: usize,
218 pub confidence_interval: (F, F),
220}
221
222impl<F: Float + Debug + std::ops::MulAssign + std::ops::AddAssign + std::ops::SubAssign>
223 QuantumParameterOptimizer<F>
224{
225 pub fn new() -> InterpolateResult<Self> {
227 Ok(Self {
228 quantum_state: QuantumState::new()?,
229 quantum_operators: Vec::new(),
230 annealing_params: AnnealingParameters::default(),
231 measurement_system: QuantumMeasurement::new()?,
232 optimization_history: VecDeque::new(),
233 state_population: Vec::new(),
234 })
235 }
236
237 pub fn initialize_quantum_state(
239 &mut self,
240 parameters: &HashMap<String, F>,
241 ) -> InterpolateResult<()> {
242 let param_count = parameters.len();
243
244 self.quantum_state = QuantumState {
246 amplitudes: vec![
247 (
248 F::one() / F::from(param_count as f64).unwrap().sqrt(),
249 F::zero()
250 );
251 param_count
252 ],
253 phases: vec![F::zero(); param_count],
254 entanglement: EntanglementInfo::default(),
255 parameter_values: parameters.clone(),
256 energy: F::zero(),
257 };
258
259 self.create_parameter_entanglements(parameters)?;
261
262 self.initialize_quantum_operators(param_count)?;
264
265 Ok(())
266 }
267
268 pub fn quantum_anneal_optimize(
270 &mut self,
271 objective_function: impl Fn(&HashMap<String, F>) -> F,
272 parameter_bounds: &HashMap<String, (F, F)>,
273 ) -> InterpolateResult<QuantumOptimizationResult<F>> {
274 let start_time = Instant::now();
275 let mut energy_history = Vec::new();
276
277 self.initialize_population(parameter_bounds, 20)?; let mut current_temperature = self.annealing_params.initial_temperature;
281 let temperature_step = (self.annealing_params.initial_temperature
282 - self.annealing_params.final_temperature)
283 / F::from(self.annealing_params.num_steps as f64).unwrap();
284
285 for step in 0..self.annealing_params.num_steps {
286 self.apply_quantum_evolution()?;
288
289 let measured_params = self.measure_parameters()?;
291
292 let energy = objective_function(&measured_params);
294 energy_history.push(energy);
295
296 self.update_quantum_state_energy(energy)?;
298
299 let accept_probability =
301 self.calculate_acceptance_probability(energy, current_temperature);
302
303 if self.should_accept_state(accept_probability)? {
304 self.quantum_state.parameter_values = measured_params;
305 self.quantum_state.energy = energy;
306 }
307
308 current_temperature = match &self.annealing_params.annealing_schedule {
310 AnnealingSchedule::Linear => {
311 self.annealing_params.initial_temperature
312 - temperature_step * F::from(step as f64).unwrap()
313 }
314 AnnealingSchedule::Exponential { decay_rate } => current_temperature * *decay_rate,
315 AnnealingSchedule::Logarithmic { scale_factor } => {
316 self.annealing_params.initial_temperature
317 / (F::one() + *scale_factor * F::from(step as f64).unwrap().ln())
318 }
319 AnnealingSchedule::Custom { schedule } => {
320 if step < schedule.len() {
321 schedule[step]
322 } else {
323 self.annealing_params.final_temperature
324 }
325 }
326 AnnealingSchedule::Adaptive {
327 convergence_threshold,
328 adaptation_rate,
329 } => {
330 if energy_history.len() > 10 {
331 let recent_variance = self.calculate_energy_variance(
332 &energy_history[energy_history.len() - 10..],
333 );
334 if recent_variance < *convergence_threshold {
335 current_temperature * *adaptation_rate
336 } else {
337 current_temperature
338 }
339 } else {
340 current_temperature
341 }
342 }
343 };
344
345 if step % 100 == 0 {
347 self.apply_quantum_tunneling()?;
348 }
349 }
350
351 let final_measurement = self.perform_final_measurement()?;
353 let measurement_stats = self.calculate_measurement_statistics(&energy_history);
354
355 let result = QuantumOptimizationResult {
356 optimized_parameters: self.quantum_state.parameter_values.clone(),
357 final_state: self.quantum_state.clone(),
358 energy_history,
359 algorithm_used: QuantumAlgorithm::QuantumAnnealing,
360 quantum_iterations: self.annealing_params.num_steps,
361 measurement_stats,
362 success: true,
363 converged: self.check_convergence(&final_measurement)?,
364 };
365
366 self.optimization_history.push_back(result.clone());
368 if self.optimization_history.len() > 50 {
369 self.optimization_history.pop_front();
370 }
371
372 Ok(result)
373 }
374
375 pub fn vqe_optimize(
377 &mut self,
378 hamiltonian: impl Fn(&HashMap<String, F>) -> F,
379 parameter_bounds: &HashMap<String, (F, F)>,
380 max_iterations: usize,
381 ) -> InterpolateResult<QuantumOptimizationResult<F>> {
382 let mut energy_history = Vec::new();
383 let mut current_best_energy = F::infinity();
384 let mut current_best_params = self.quantum_state.parameter_values.clone();
385
386 for iteration in 0..max_iterations {
387 self.prepare_ansatz_state()?;
389
390 let measured_params = self.measure_parameters()?;
392 let energy = hamiltonian(&measured_params);
393 energy_history.push(energy);
394
395 if energy < current_best_energy {
397 current_best_energy = energy;
398 current_best_params = measured_params.clone();
399 self.quantum_state.parameter_values = measured_params;
400 self.quantum_state.energy = energy;
401 }
402
403 self.apply_variational_updates(energy)?;
405
406 if iteration > 10
408 && self.check_vqe_convergence(&energy_history[iteration - 10..iteration])
409 {
410 break;
411 }
412 }
413
414 let measurement_stats = self.calculate_measurement_statistics(&energy_history);
415
416 Ok(QuantumOptimizationResult {
417 optimized_parameters: current_best_params,
418 final_state: self.quantum_state.clone(),
419 energy_history,
420 algorithm_used: QuantumAlgorithm::VQE,
421 quantum_iterations: max_iterations,
422 measurement_stats,
423 success: true,
424 converged: true,
425 })
426 }
427
428 fn create_parameter_entanglements(
430 &mut self,
431 parameters: &HashMap<String, F>,
432 ) -> InterpolateResult<()> {
433 let param_names: Vec<_> = parameters.keys().collect();
434 let mut entangled_pairs = Vec::new();
435
436 for (i, ¶m1) in param_names.iter().enumerate() {
438 for (j, ¶m2) in param_names.iter().enumerate().skip(i + 1) {
439 if self.should_entangle_parameters(param1, param2) {
441 entangled_pairs.push((i, j));
442 }
443 }
444 }
445
446 self.quantum_state.entanglement = EntanglementInfo {
447 entangled_pairs,
448 entanglement_strength: 0.5, entanglement_matrix: None,
450 };
451
452 Ok(())
453 }
454
455 fn should_entangle_parameters(&self, param1: &str, param2: &str) -> bool {
457 let related_pairs = [
459 ("tolerance", "max_iterations"),
460 ("degree", "smoothing"),
461 ("kernel_width", "regularization"),
462 ("learning_rate", "momentum"),
463 ];
464
465 related_pairs.iter().any(|(p1, p2)| {
466 (param1.contains(p1) && param2.contains(p2))
467 || (param1.contains(p2) && param2.contains(p1))
468 })
469 }
470
471 fn initialize_quantum_operators(&mut self, param_count: usize) -> InterpolateResult<()> {
473 self.quantum_operators.clear();
474
475 for i in 0..param_count {
477 self.quantum_operators
478 .push(QuantumOperator::Hadamard { parameter: i });
479 }
480
481 for i in 0..param_count {
483 self.quantum_operators.push(QuantumOperator::Rotation {
484 parameter: i,
485 angle: F::from(std::f64::consts::PI / 4.0).unwrap(),
486 });
487 }
488
489 for &(control, target) in &self.quantum_state.entanglement.entangled_pairs {
491 self.quantum_operators
492 .push(QuantumOperator::CNOT { control, target });
493 }
494
495 Ok(())
496 }
497
498 fn initialize_population(
500 &mut self,
501 parameter_bounds: &HashMap<String, (F, F)>,
502 population_size: usize,
503 ) -> InterpolateResult<()> {
504 self.state_population.clear();
505
506 for _ in 0..population_size {
507 let mut state = QuantumState::new()?;
508
509 for (param_name, &(min_val, max_val)) in parameter_bounds {
511 let random_val = min_val
512 + (max_val - min_val) * F::from(scirs2_core::random::random::<f64>()).unwrap();
513 state
514 .parameter_values
515 .insert(param_name.clone(), random_val);
516 }
517
518 let param_count = parameter_bounds.len();
520 state.amplitudes = vec![
521 (
522 F::one() / F::from(param_count as f64).unwrap().sqrt(),
523 F::zero()
524 );
525 param_count
526 ];
527 state.phases =
528 vec![
529 F::from(scirs2_core::random::random::<f64>() * 2.0 * std::f64::consts::PI)
530 .unwrap();
531 param_count
532 ];
533
534 self.state_population.push(state);
535 }
536
537 Ok(())
538 }
539
540 fn apply_quantum_evolution(&mut self) -> InterpolateResult<()> {
542 let operators_to_apply = std::cmp::min(3, self.quantum_operators.len());
544
545 for i in 0..operators_to_apply {
546 let operator = self.quantum_operators[i].clone();
547 self.apply_quantum_operator(&operator)?;
548 }
549
550 self.apply_quantum_decoherence(F::from(0.01).unwrap())?;
552
553 Ok(())
554 }
555
556 fn apply_quantum_operator(&mut self, operator: &QuantumOperator<F>) -> InterpolateResult<()> {
558 match operator {
559 QuantumOperator::Hadamard { parameter } => {
560 if *parameter < self.quantum_state.amplitudes.len() {
561 let (real, imag) = self.quantum_state.amplitudes[*parameter];
563 let sqrt2_inv = F::one() / F::from(2.0_f64.sqrt()).unwrap();
564 self.quantum_state.amplitudes[*parameter] =
565 ((real + imag) * sqrt2_inv, (real - imag) * sqrt2_inv);
566 }
567 }
568 QuantumOperator::Rotation { parameter, angle } => {
569 if *parameter < self.quantum_state.phases.len() {
570 self.quantum_state.phases[*parameter] += *angle;
571 }
572 }
573 QuantumOperator::CNOT { control, target } => {
574 if *control < self.quantum_state.amplitudes.len()
576 && *target < self.quantum_state.amplitudes.len()
577 {
578 let control_amp = self.quantum_state.amplitudes[*control];
579 let target_amp = self.quantum_state.amplitudes[*target];
580
581 if control_amp.0.abs() > F::from(0.5).unwrap() {
583 self.quantum_state.amplitudes[*target] = (target_amp.1, target_amp.0);
584 }
585 }
586 }
587 _ => {
588 }
590 }
591
592 Ok(())
593 }
594
595 fn apply_quantum_decoherence(&mut self, decoherence_rate: F) -> InterpolateResult<()> {
597 for (real, imag) in &mut self.quantum_state.amplitudes {
598 *real *= F::one() - decoherence_rate;
599 *imag *= F::one() - decoherence_rate;
600 }
601
602 for phase in &mut self.quantum_state.phases {
603 *phase *= F::one() - decoherence_rate;
604 }
605
606 Ok(())
607 }
608
609 fn measure_parameters(&self) -> InterpolateResult<HashMap<String, F>> {
611 let mut measured_params = HashMap::new();
612
613 for (param_name, ¤t_value) in &self.quantum_state.parameter_values {
614 let measurement_uncertainty = F::from(0.01).unwrap(); let random_factor = F::from(scirs2_core::random::random::<f64>() - 0.5).unwrap()
617 * measurement_uncertainty;
618 let measured_value = current_value * (F::one() + random_factor);
619
620 measured_params.insert(param_name.clone(), measured_value);
621 }
622
623 Ok(measured_params)
624 }
625
626 fn update_quantum_state_energy(&mut self, energy: F) -> InterpolateResult<()> {
628 self.quantum_state.energy = energy;
629
630 let energy_factor = (-energy / F::from(10.0).unwrap()).exp();
632 for (real, imag) in &mut self.quantum_state.amplitudes {
633 *real *= energy_factor;
634 *imag *= energy_factor;
635 }
636
637 Ok(())
638 }
639
640 fn calculate_acceptance_probability(&self, energy: F, temperature: F) -> F {
642 if energy < self.quantum_state.energy {
643 F::one() } else {
645 let delta_energy = energy - self.quantum_state.energy;
646 (-delta_energy / temperature).exp()
647 }
648 }
649
650 fn should_accept_state(&self, acceptance_probability: F) -> InterpolateResult<bool> {
652 let random_value = F::from(scirs2_core::random::random::<f64>()).unwrap();
653 Ok(random_value < acceptance_probability)
654 }
655
656 fn apply_quantum_tunneling(&mut self) -> InterpolateResult<()> {
658 let tunneling_strength = self.annealing_params.tunneling_strength;
659
660 for value in self.quantum_state.parameter_values.values_mut() {
662 let tunneling_offset =
663 F::from(scirs2_core::random::random::<f64>() - 0.5).unwrap() * tunneling_strength;
664 *value += tunneling_offset;
665 }
666
667 Ok(())
668 }
669
670 fn calculate_energy_variance(&self, energies: &[F]) -> F {
672 if energies.len() < 2 {
673 return F::infinity();
674 }
675
676 let mean = energies.iter().fold(F::zero(), |acc, &x| acc + x)
677 / F::from(energies.len() as f64).unwrap();
678 let variance = energies
679 .iter()
680 .map(|&x| (x - mean) * (x - mean))
681 .fold(F::zero(), |acc, x| acc + x)
682 / F::from(energies.len() as f64).unwrap();
683
684 variance
685 }
686
687 fn perform_final_measurement(&self) -> InterpolateResult<MeasurementResult<F>> {
689 let final_energy = self.quantum_state.energy;
690 let uncertainty = F::from(0.001).unwrap(); Ok(MeasurementResult {
693 value: final_energy,
694 uncertainty,
695 basis: "energy".to_string(),
696 timestamp: Instant::now(),
697 probability: F::one(), })
699 }
700
701 fn calculate_measurement_statistics(&self, energy_history: &[F]) -> MeasurementStatistics<F> {
703 if energy_history.is_empty() {
704 return MeasurementStatistics {
705 mean: F::zero(),
706 variance: F::zero(),
707 std_dev: F::zero(),
708 sample_count: 0,
709 confidence_interval: (F::zero(), F::zero()),
710 };
711 }
712
713 let mean = energy_history.iter().fold(F::zero(), |acc, &x| acc + x)
714 / F::from(energy_history.len() as f64).unwrap();
715 let variance = energy_history
716 .iter()
717 .map(|&x| (x - mean) * (x - mean))
718 .fold(F::zero(), |acc, x| acc + x)
719 / F::from(energy_history.len() as f64).unwrap();
720 let std_dev = variance.sqrt();
721
722 let confidence_margin =
724 std_dev * F::from(1.96).unwrap() / F::from(energy_history.len() as f64).unwrap().sqrt();
725
726 MeasurementStatistics {
727 mean,
728 variance,
729 std_dev,
730 sample_count: energy_history.len(),
731 confidence_interval: (mean - confidence_margin, mean + confidence_margin),
732 }
733 }
734
735 fn check_convergence(&self, _measurement: &MeasurementResult<F>) -> InterpolateResult<bool> {
737 if self.optimization_history.len() < 3 {
739 return Ok(false);
740 }
741
742 let recent_energies: Vec<F> = self
743 .optimization_history
744 .iter()
745 .rev()
746 .take(3)
747 .map(|result| result.final_state.energy)
748 .collect();
749
750 let energy_variance = self.calculate_energy_variance(&recent_energies);
751 Ok(energy_variance < F::from(1e-6).unwrap())
752 }
753
754 fn prepare_ansatz_state(&mut self) -> InterpolateResult<()> {
756 for i in 0..self.quantum_state.amplitudes.len() {
758 self.apply_quantum_operator(&QuantumOperator::Rotation {
759 parameter: i,
760 angle: self.quantum_state.phases[i],
761 })?;
762 }
763
764 Ok(())
765 }
766
767 fn apply_variational_updates(&mut self, energy: F) -> InterpolateResult<()> {
769 let learning_rate = F::from(0.01).unwrap();
770
771 for phase in &mut self.quantum_state.phases {
773 let gradient = if energy > self.quantum_state.energy {
774 -learning_rate
775 } else {
776 learning_rate
777 };
778 *phase += gradient;
779 }
780
781 Ok(())
782 }
783
784 fn check_vqe_convergence(&self, recent_energies: &[F]) -> bool {
786 if recent_energies.len() < 5 {
787 return false;
788 }
789
790 let variance = self.calculate_energy_variance(recent_energies);
791 variance < F::from(1e-8).unwrap()
792 }
793
794 pub fn get_optimization_history(&self) -> &VecDeque<QuantumOptimizationResult<F>> {
796 &self.optimization_history
797 }
798
799 pub fn get_quantum_state(&self) -> &QuantumState<F> {
801 &self.quantum_state
802 }
803}
804
805impl<F: Float + std::ops::SubAssign> QuantumState<F> {
806 pub fn new() -> InterpolateResult<Self> {
808 Ok(Self {
809 amplitudes: Vec::new(),
810 phases: Vec::new(),
811 entanglement: EntanglementInfo::default(),
812 parameter_values: HashMap::new(),
813 energy: F::zero(),
814 })
815 }
816
817 pub fn get_measurement_probability(&self, parameter_index: usize) -> F {
819 if parameter_index < self.amplitudes.len() {
820 let (real, imag) = self.amplitudes[parameter_index];
821 real * real + imag * imag
822 } else {
823 F::zero()
824 }
825 }
826
827 pub fn calculate_entropy(&self) -> F {
829 let mut entropy = F::zero();
830
831 for (real, imag) in &self.amplitudes {
832 let probability = *real * *real + *imag * *imag;
833 if probability > F::zero() {
834 entropy -= probability * probability.ln();
835 }
836 }
837
838 entropy
839 }
840}
841
842impl Default for EntanglementInfo {
843 fn default() -> Self {
844 Self {
845 entangled_pairs: Vec::new(),
846 entanglement_strength: 0.0,
847 entanglement_matrix: None,
848 }
849 }
850}
851
852impl<F: Float> Default for AnnealingParameters<F> {
853 fn default() -> Self {
854 Self {
855 initial_temperature: F::from(1.0).unwrap(),
856 final_temperature: F::from(0.01).unwrap(),
857 annealing_schedule: AnnealingSchedule::Linear,
858 num_steps: 1000,
859 tunneling_strength: F::from(0.1).unwrap(),
860 transverse_field: F::from(0.5).unwrap(),
861 }
862 }
863}
864
865impl<F: Float> QuantumMeasurement<F> {
866 pub fn new() -> InterpolateResult<Self> {
868 Ok(Self {
869 measurement_operators: Vec::new(),
870 measurement_history: VecDeque::new(),
871 measurement_bases: Vec::new(),
872 })
873 }
874
875 pub fn add_measurement_operator(&mut self, operator: MeasurementOperator<F>) {
877 self.measurement_operators.push(operator);
878 }
879
880 pub fn measure_with_operator(
882 &mut self,
883 state: &QuantumState<F>,
884 operator_name: &str,
885 ) -> InterpolateResult<MeasurementResult<F>> {
886 let operator = self
888 .measurement_operators
889 .iter()
890 .find(|op| op.name == operator_name)
891 .ok_or_else(|| {
892 crate::error::InterpolateError::invalid_input(format!(
893 "Measurement operator '{}' not found",
894 operator_name
895 ))
896 })?;
897
898 let measurement_value = state.energy; let uncertainty = operator.precision;
901
902 let result = MeasurementResult {
903 value: measurement_value,
904 uncertainty,
905 basis: operator_name.to_string(),
906 timestamp: Instant::now(),
907 probability: F::one(),
908 };
909
910 self.measurement_history.push_back(result.clone());
911 if self.measurement_history.len() > 100 {
912 self.measurement_history.pop_front();
913 }
914
915 Ok(result)
916 }
917
918 pub fn get_measurement_history(&self) -> &VecDeque<MeasurementResult<F>> {
920 &self.measurement_history
921 }
922}
923
924#[cfg(test)]
925mod tests {
926 use super::*;
927
928 #[test]
929 fn test_quantum_optimizer_creation() {
930 let optimizer: QuantumParameterOptimizer<f64> = QuantumParameterOptimizer::new().unwrap();
931 assert!(optimizer.quantum_operators.is_empty());
932 assert!(optimizer.optimization_history.is_empty());
933 }
934
935 #[test]
936 fn test_quantum_state_creation() {
937 let state: QuantumState<f64> = QuantumState::new().unwrap();
938 assert!(state.amplitudes.is_empty());
939 assert!(state.parameter_values.is_empty());
940 assert_eq!(state.energy, 0.0);
941 }
942
943 #[test]
944 fn test_annealing_parameters_default() {
945 let params: AnnealingParameters<f64> = AnnealingParameters::default();
946 assert_eq!(params.initial_temperature, 1.0);
947 assert_eq!(params.final_temperature, 0.01);
948 assert_eq!(params.num_steps, 1000);
949 }
950
951 #[test]
952 fn test_measurement_probability() {
953 let mut state: QuantumState<f64> = QuantumState::new().unwrap();
954 state.amplitudes = vec![(0.8, 0.6)]; let prob = state.get_measurement_probability(0);
957 assert!((prob - 1.0).abs() < 1e-10);
958 }
959
960 #[test]
961 fn test_quantum_entropy_calculation() {
962 let mut state: QuantumState<f64> = QuantumState::new().unwrap();
963 state.amplitudes = vec![(0.707, 0.0), (0.707, 0.0)]; let entropy = state.calculate_entropy();
966 assert!(entropy > 0.0); }
968}