1use scirs2_core::ndarray::{Array1, Array2};
10use scirs2_core::parallel_ops::{IndexedParallelIterator, ParallelIterator};
11use scirs2_core::Complex64;
12use serde::{Deserialize, Serialize};
13use std::collections::HashMap;
14use std::f64::consts::PI;
15
16use crate::circuit_interfaces::{
17 CircuitInterface, InterfaceCircuit, InterfaceGate, InterfaceGateType,
18};
19use crate::error::{Result, SimulatorError};
20use crate::scirs2_integration::SciRS2Backend;
21use crate::scirs2_qft::{QFTConfig, QFTMethod, SciRS2QFT};
22use crate::statevector::StateVectorSimulator;
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26pub enum OptimizationLevel {
27 Basic,
29 Memory,
31 Speed,
33 Hardware,
35 Maximum,
37}
38
39#[derive(Debug, Clone)]
41pub struct QuantumAlgorithmConfig {
42 pub optimization_level: OptimizationLevel,
44 pub use_classical_preprocessing: bool,
46 pub enable_error_mitigation: bool,
48 pub max_circuit_depth: usize,
50 pub precision_tolerance: f64,
52 pub enable_parallel: bool,
54 pub resource_estimation_accuracy: f64,
56}
57
58impl Default for QuantumAlgorithmConfig {
59 fn default() -> Self {
60 Self {
61 optimization_level: OptimizationLevel::Maximum,
62 use_classical_preprocessing: true,
63 enable_error_mitigation: true,
64 max_circuit_depth: 1000,
65 precision_tolerance: 1e-10,
66 enable_parallel: true,
67 resource_estimation_accuracy: 0.95,
68 }
69 }
70}
71
72#[derive(Debug, Clone, Serialize, Deserialize)]
74pub struct ShorResult {
75 pub n: u64,
77 pub factors: Vec<u64>,
79 pub period: Option<u64>,
81 pub quantum_iterations: usize,
83 pub execution_time_ms: f64,
85 pub classical_preprocessing_ms: f64,
87 pub quantum_computation_ms: f64,
89 pub success_probability: f64,
91 pub resource_stats: AlgorithmResourceStats,
93}
94
95#[derive(Debug, Clone, Serialize, Deserialize)]
97pub struct GroverResult {
98 pub found_items: Vec<usize>,
100 pub final_amplitudes: Vec<Complex64>,
102 pub iterations: usize,
104 pub optimal_iterations: usize,
106 pub success_probability: f64,
108 pub amplification_gain: f64,
110 pub execution_time_ms: f64,
112 pub resource_stats: AlgorithmResourceStats,
114}
115
116#[derive(Debug, Clone, Serialize, Deserialize)]
118pub struct PhaseEstimationResult {
119 pub eigenvalues: Vec<f64>,
121 pub precisions: Vec<f64>,
123 pub eigenvectors: Option<Array2<Complex64>>,
125 pub phase_qubits: usize,
127 pub precision_iterations: usize,
129 pub execution_time_ms: f64,
131 pub resource_stats: AlgorithmResourceStats,
133}
134
135#[derive(Debug, Clone, Default, Serialize, Deserialize)]
137pub struct AlgorithmResourceStats {
138 pub qubits_used: usize,
140 pub circuit_depth: usize,
142 pub gate_count: usize,
144 pub measurement_count: usize,
146 pub memory_usage_bytes: usize,
148 pub cnot_count: usize,
150 pub t_gate_count: usize,
152}
153
154pub struct OptimizedShorAlgorithm {
156 config: QuantumAlgorithmConfig,
158 backend: Option<SciRS2Backend>,
160 circuit_interface: CircuitInterface,
162 qft_engine: SciRS2QFT,
164}
165
166impl OptimizedShorAlgorithm {
167 pub fn new(config: QuantumAlgorithmConfig) -> Result<Self> {
169 let circuit_interface = CircuitInterface::new(Default::default())?;
170 let qft_config = QFTConfig {
171 method: QFTMethod::SciRS2Exact,
172 bit_reversal: true,
173 parallel: config.enable_parallel,
174 precision_threshold: config.precision_tolerance,
175 ..Default::default()
176 };
177 let qft_engine = SciRS2QFT::new(0, qft_config)?; Ok(Self {
180 config,
181 backend: None,
182 circuit_interface,
183 qft_engine,
184 })
185 }
186
187 pub fn with_backend(mut self) -> Result<Self> {
189 self.backend = Some(SciRS2Backend::new());
190 self.circuit_interface = self.circuit_interface.with_backend()?;
191 self.qft_engine = self.qft_engine.with_backend()?;
192 Ok(self)
193 }
194
195 pub fn factor(&mut self, n: u64) -> Result<ShorResult> {
197 let start_time = std::time::Instant::now();
198
199 let preprocessing_start = std::time::Instant::now();
201
202 if n <= 1 {
204 return Err(SimulatorError::InvalidInput(
205 "Cannot factor numbers <= 1".to_string(),
206 ));
207 }
208
209 if n == 2 {
210 return Ok(ShorResult {
211 n,
212 factors: vec![2],
213 period: None,
214 quantum_iterations: 0,
215 execution_time_ms: start_time.elapsed().as_secs_f64() * 1000.0,
216 classical_preprocessing_ms: 0.0,
217 quantum_computation_ms: 0.0,
218 success_probability: 1.0,
219 resource_stats: AlgorithmResourceStats::default(),
220 });
221 }
222
223 if n % 2 == 0 {
225 let factor = 2;
226 let other_factor = n / 2;
227 return Ok(ShorResult {
228 n,
229 factors: vec![factor, other_factor],
230 period: None,
231 quantum_iterations: 0,
232 execution_time_ms: start_time.elapsed().as_secs_f64() * 1000.0,
233 classical_preprocessing_ms: preprocessing_start.elapsed().as_secs_f64() * 1000.0,
234 quantum_computation_ms: 0.0,
235 success_probability: 1.0,
236 resource_stats: AlgorithmResourceStats::default(),
237 });
238 }
239
240 if let Some((base, _exponent)) = Self::find_perfect_power(n) {
242 return Ok(ShorResult {
243 n,
244 factors: vec![base],
245 period: None,
246 quantum_iterations: 0,
247 execution_time_ms: start_time.elapsed().as_secs_f64() * 1000.0,
248 classical_preprocessing_ms: preprocessing_start.elapsed().as_secs_f64() * 1000.0,
249 quantum_computation_ms: 0.0,
250 success_probability: 1.0,
251 resource_stats: AlgorithmResourceStats::default(),
252 });
253 }
254
255 let classical_preprocessing_ms = preprocessing_start.elapsed().as_secs_f64() * 1000.0;
256
257 let quantum_start = std::time::Instant::now();
259 let mut quantum_iterations = 0;
260 let max_attempts = 10;
261
262 for attempt in 0..max_attempts {
263 quantum_iterations += 1;
264
265 let a = self.choose_random_base(n)?;
267
268 let gcd_val = Self::gcd(a, n);
270 if gcd_val > 1 {
271 let other_factor = n / gcd_val;
272 return Ok(ShorResult {
273 n,
274 factors: vec![gcd_val, other_factor],
275 period: None,
276 quantum_iterations,
277 execution_time_ms: start_time.elapsed().as_secs_f64() * 1000.0,
278 classical_preprocessing_ms,
279 quantum_computation_ms: quantum_start.elapsed().as_secs_f64() * 1000.0,
280 success_probability: 1.0,
281 resource_stats: AlgorithmResourceStats::default(),
282 });
283 }
284
285 if let Some(period) = self.quantum_period_finding(a, n)? {
287 if self.verify_period(a, n, period) {
289 if let Some(factors) = self.extract_factors_from_period(a, n, period) {
291 let quantum_computation_ms = quantum_start.elapsed().as_secs_f64() * 1000.0;
292
293 let resource_stats = Self::estimate_resources(n);
294
295 return Ok(ShorResult {
296 n,
297 factors,
298 period: Some(period),
299 quantum_iterations,
300 execution_time_ms: start_time.elapsed().as_secs_f64() * 1000.0,
301 classical_preprocessing_ms,
302 quantum_computation_ms,
303 success_probability: Self::estimate_success_probability(
304 attempt,
305 max_attempts,
306 ),
307 resource_stats,
308 });
309 }
310 }
311 }
312 }
313
314 Ok(ShorResult {
316 n,
317 factors: vec![],
318 period: None,
319 quantum_iterations,
320 execution_time_ms: start_time.elapsed().as_secs_f64() * 1000.0,
321 classical_preprocessing_ms,
322 quantum_computation_ms: quantum_start.elapsed().as_secs_f64() * 1000.0,
323 success_probability: 0.0,
324 resource_stats: Self::estimate_resources(n),
325 })
326 }
327
328 fn quantum_period_finding(&mut self, a: u64, n: u64) -> Result<Option<u64>> {
330 let n_bits = (n as f64).log2().ceil() as usize;
332 let register_size = 3 * n_bits; let total_qubits = register_size + n_bits;
334
335 let mut circuit = InterfaceCircuit::new(total_qubits, register_size);
337
338 for i in 0..register_size {
340 circuit.add_gate(InterfaceGate::new(InterfaceGateType::Hadamard, vec![i]));
341 }
342
343 circuit.add_gate(InterfaceGate::new(
345 InterfaceGateType::PauliX,
346 vec![register_size],
347 ));
348
349 self.add_optimized_controlled_modular_exponentiation(&mut circuit, a, n, register_size)?;
351
352 self.add_inverse_qft(&mut circuit, register_size)?;
354
355 for i in 0..register_size {
357 circuit.add_gate(InterfaceGate::measurement(i, i));
358 }
359
360 let backend = crate::circuit_interfaces::SimulationBackend::StateVector;
362 let compiled = self.circuit_interface.compile_circuit(&circuit, backend)?;
363 let result = self.circuit_interface.execute_circuit(&compiled, None)?;
364
365 if !result.measurement_results.is_empty() {
367 let mut measured_value = 0usize;
369 for (i, &bit) in result
370 .measurement_results
371 .iter()
372 .take(register_size)
373 .enumerate()
374 {
375 if bit {
376 measured_value |= 1 << i;
377 }
378 }
379
380 if self.config.enable_error_mitigation {
382 measured_value = Self::apply_error_mitigation(measured_value, register_size)?;
383 }
384
385 if let Some(period) =
387 self.extract_period_from_measurement_enhanced(measured_value, register_size, n)
388 {
389 return Ok(Some(period));
390 }
391 }
392
393 Ok(None)
394 }
395
396 fn add_optimized_controlled_modular_exponentiation(
398 &self,
399 circuit: &mut InterfaceCircuit,
400 a: u64,
401 n: u64,
402 register_size: usize,
403 ) -> Result<()> {
404 let n_bits = (n as f64).log2().ceil() as usize;
405
406 for i in 0..register_size {
407 let power = 1u64 << i;
408 let a_power_mod_n = Self::mod_exp(a, power, n);
409
410 self.add_controlled_modular_multiplication_optimized(
412 circuit,
413 a_power_mod_n,
414 n,
415 i,
416 register_size,
417 n_bits,
418 )?;
419 }
420
421 Ok(())
422 }
423
424 fn add_controlled_modular_exponentiation(
426 &self,
427 circuit: &mut InterfaceCircuit,
428 a: u64,
429 n: u64,
430 register_size: usize,
431 ) -> Result<()> {
432 self.add_optimized_controlled_modular_exponentiation(circuit, a, n, register_size)
433 }
434
435 fn add_controlled_modular_multiplication_optimized(
437 &self,
438 circuit: &mut InterfaceCircuit,
439 multiplier: u64,
440 modulus: u64,
441 control_qubit: usize,
442 register_start: usize,
443 register_size: usize,
444 ) -> Result<()> {
445 let target_start = register_start + register_size;
447
448 let mont_multiplier = Self::montgomery_form(multiplier, modulus);
450
451 for i in 0..register_size {
453 if (mont_multiplier >> i) & 1 == 1 {
454 Self::add_controlled_quantum_adder(
456 circuit,
457 control_qubit,
458 register_start + i,
459 target_start + i,
460 register_size - i,
461 )?;
462 }
463 }
464
465 Self::add_controlled_modular_reduction(
467 circuit,
468 modulus,
469 control_qubit,
470 target_start,
471 register_size,
472 )?;
473
474 Ok(())
475 }
476
477 fn add_controlled_modular_multiplication(
479 circuit: &mut InterfaceCircuit,
480 multiplier: u64,
481 modulus: u64,
482 control_qubit: usize,
483 register_start: usize,
484 register_size: usize,
485 ) -> Result<()> {
486 for i in 0..register_size {
490 if (multiplier >> i) & 1 == 1 {
491 circuit.add_gate(InterfaceGate::new(
493 InterfaceGateType::CNOT,
494 vec![control_qubit, register_start + i],
495 ));
496 }
497 }
498
499 Ok(())
500 }
501
502 fn add_inverse_qft(&mut self, circuit: &mut InterfaceCircuit, num_qubits: usize) -> Result<()> {
504 let qft_config = QFTConfig {
506 method: QFTMethod::SciRS2Exact,
507 bit_reversal: true,
508 parallel: self.config.enable_parallel,
509 precision_threshold: self.config.precision_tolerance,
510 ..Default::default()
511 };
512 self.qft_engine = SciRS2QFT::new(num_qubits, qft_config)?;
513
514 for i in 0..num_qubits {
516 circuit.add_gate(InterfaceGate::new(InterfaceGateType::Hadamard, vec![i]));
517
518 for j in (i + 1)..num_qubits {
519 let angle = -PI / 2.0_f64.powi((j - i) as i32);
520 circuit.add_gate(InterfaceGate::new(InterfaceGateType::Phase(angle), vec![j]));
521 circuit.add_gate(InterfaceGate::new(InterfaceGateType::CNOT, vec![i, j]));
522 circuit.add_gate(InterfaceGate::new(
523 InterfaceGateType::Phase(-angle),
524 vec![j],
525 ));
526 circuit.add_gate(InterfaceGate::new(InterfaceGateType::CNOT, vec![i, j]));
527 }
528 }
529
530 Ok(())
531 }
532
533 fn extract_period_from_measurement(
535 &self,
536 measured_value: usize,
537 register_size: usize,
538 n: u64,
539 ) -> Option<u64> {
540 if measured_value == 0 {
541 return None;
542 }
543
544 let max_register_value = 1 << register_size;
545 let fraction = measured_value as f64 / f64::from(max_register_value);
546
547 let convergents = Self::continued_fractions(fraction, n);
549
550 for (num, den) in convergents {
551 if den > 0 && den < n {
552 return Some(den);
553 }
554 }
555
556 None
557 }
558
559 fn continued_fractions(x: f64, max_denominator: u64) -> Vec<(u64, u64)> {
561 let mut convergents = Vec::new();
562 let mut a = x;
563 let mut p_prev = 0u64;
564 let mut p_curr = 1u64;
565 let mut q_prev = 1u64;
566 let mut q_curr = 0u64;
567
568 for _ in 0..20 {
569 let a_int = a.floor() as u64;
571 let p_next = a_int * p_curr + p_prev;
572 let q_next = a_int * q_curr + q_prev;
573
574 if q_next > max_denominator {
575 break;
576 }
577
578 convergents.push((p_next, q_next));
579
580 let remainder = a - a_int as f64;
581 if remainder.abs() < 1e-12 {
582 break;
583 }
584
585 a = 1.0 / remainder;
586 p_prev = p_curr;
587 p_curr = p_next;
588 q_prev = q_curr;
589 q_curr = q_next;
590 }
591
592 convergents
593 }
594
595 fn extract_period_from_measurement_enhanced(
597 &self,
598 measured_value: usize,
599 register_size: usize,
600 n: u64,
601 ) -> Option<u64> {
602 if measured_value == 0 {
603 return None;
604 }
605
606 let max_register_value = 1 << register_size;
607 let fraction = measured_value as f64 / f64::from(max_register_value);
608
609 let convergents = Self::continued_fractions_enhanced(fraction, n);
611
612 for (num, den) in convergents {
614 if den > 0 && den < n {
615 if Self::verify_period_enhanced(num, den, n) {
617 return Some(den);
618 }
619 }
620 }
621
622 None
623 }
624
625 fn continued_fractions_enhanced(x: f64, max_denominator: u64) -> Vec<(u64, u64)> {
627 let mut convergents = Vec::new();
628 let mut a = x;
629 let mut p_prev = 0u64;
630 let mut p_curr = 1u64;
631 let mut q_prev = 1u64;
632 let mut q_curr = 0u64;
633
634 for _ in 0..50 {
636 let a_int = a.floor() as u64;
637 let p_next = a_int * p_curr + p_prev;
638 let q_next = a_int * q_curr + q_prev;
639
640 if q_next > max_denominator {
641 break;
642 }
643
644 convergents.push((p_next, q_next));
645
646 let remainder = a - a_int as f64;
647 if remainder.abs() < 1e-15 {
648 break;
650 }
651
652 a = 1.0 / remainder;
653 p_prev = p_curr;
654 p_curr = p_next;
655 q_prev = q_curr;
656 q_curr = q_next;
657 }
658
659 convergents
660 }
661
662 const fn verify_period_enhanced(_num: u64, period: u64, n: u64) -> bool {
664 if period == 0 || period >= n {
665 return false;
666 }
667
668 period > 1 && period % 2 == 0 && period < n / 2
670 }
671
672 fn apply_error_mitigation(measured_value: usize, register_size: usize) -> Result<usize> {
674 let mut candidates = vec![measured_value];
676
677 if measured_value > 0 {
679 candidates.push(measured_value - 1);
680 }
681 if measured_value < (1 << register_size) - 1 {
682 candidates.push(measured_value + 1);
683 }
684
685 Ok(candidates[0])
687 }
688
689 const fn montgomery_form(value: u64, modulus: u64) -> u64 {
691 value % modulus
694 }
695
696 fn add_controlled_quantum_adder(
698 circuit: &mut InterfaceCircuit,
699 control_qubit: usize,
700 source_qubit: usize,
701 target_qubit: usize,
702 _width: usize,
703 ) -> Result<()> {
704 circuit.add_gate(InterfaceGate::new(
706 InterfaceGateType::CNOT,
707 vec![control_qubit, source_qubit],
708 ));
709 circuit.add_gate(InterfaceGate::new(
710 InterfaceGateType::CNOT,
711 vec![source_qubit, target_qubit],
712 ));
713 Ok(())
714 }
715
716 fn add_controlled_modular_reduction(
718 circuit: &mut InterfaceCircuit,
719 _modulus: u64,
720 control_qubit: usize,
721 register_start: usize,
722 register_size: usize,
723 ) -> Result<()> {
724 for i in 0..register_size {
726 circuit.add_gate(InterfaceGate::new(
727 InterfaceGateType::CPhase(PI / 4.0),
728 vec![control_qubit, register_start + i],
729 ));
730 }
731 Ok(())
732 }
733
734 fn find_perfect_power(n: u64) -> Option<(u64, u32)> {
736 for exponent in 2..=((n as f64).log2().floor() as u32) {
737 let base = (n as f64).powf(1.0 / f64::from(exponent)).round() as u64;
738 if base.pow(exponent) == n {
739 return Some((base, exponent));
740 }
741 }
742 None
743 }
744
745 fn choose_random_base(&self, n: u64) -> Result<u64> {
746 let candidates = [2, 3, 4, 5, 6, 7, 8];
748 for &a in &candidates {
749 if a < n && Self::gcd(a, n) == 1 {
750 return Ok(a);
751 }
752 }
753
754 for a in 2..n {
756 if Self::gcd(a, n) == 1 {
757 return Ok(a);
758 }
759 }
760
761 Err(SimulatorError::InvalidInput(
762 "Cannot find suitable base for factoring".to_string(),
763 ))
764 }
765
766 const fn gcd(mut a: u64, mut b: u64) -> u64 {
767 while b != 0 {
768 let temp = b;
769 b = a % b;
770 a = temp;
771 }
772 a
773 }
774
775 const fn mod_exp(base: u64, exp: u64, modulus: u64) -> u64 {
776 let mut result = 1u64;
777 let mut base = base % modulus;
778 let mut exp = exp;
779
780 while exp > 0 {
781 if exp % 2 == 1 {
782 result = (result * base) % modulus;
783 }
784 exp >>= 1;
785 base = (base * base) % modulus;
786 }
787
788 result
789 }
790
791 const fn verify_period(&self, a: u64, n: u64, period: u64) -> bool {
792 if period == 0 {
793 return false;
794 }
795 Self::mod_exp(a, period, n) == 1
796 }
797
798 fn extract_factors_from_period(&self, a: u64, n: u64, period: u64) -> Option<Vec<u64>> {
799 if period % 2 != 0 {
800 return None;
801 }
802
803 let half_period = period / 2;
804 let a_to_half = Self::mod_exp(a, half_period, n);
805
806 if a_to_half == n - 1 {
807 return None; }
809
810 let factor1 = Self::gcd(a_to_half - 1, n);
811 let factor2 = Self::gcd(a_to_half + 1, n);
812
813 let mut factors = Vec::new();
814 if factor1 > 1 && factor1 < n {
815 factors.push(factor1);
816 factors.push(n / factor1);
817 } else if factor2 > 1 && factor2 < n {
818 factors.push(factor2);
819 factors.push(n / factor2);
820 }
821
822 if factors.is_empty() {
823 None
824 } else {
825 Some(factors)
826 }
827 }
828
829 fn estimate_success_probability(attempt: usize, max_attempts: usize) -> f64 {
830 let base_probability = 0.5; 1.0f64 - (1.0f64 - base_probability).powi(attempt as i32 + 1)
833 }
834
835 fn estimate_resources(n: u64) -> AlgorithmResourceStats {
836 let n_bits = (n as f64).log2().ceil() as usize;
837 let register_size = 2 * n_bits;
838 let total_qubits = register_size + n_bits;
839
840 let gate_count = total_qubits * total_qubits * 10; let cnot_count = gate_count / 3; let t_gate_count = gate_count / 10; let circuit_depth = total_qubits * 50; AlgorithmResourceStats {
847 qubits_used: total_qubits,
848 circuit_depth,
849 gate_count,
850 measurement_count: register_size,
851 memory_usage_bytes: (1 << total_qubits) * 16, cnot_count,
853 t_gate_count,
854 }
855 }
856}
857
858pub struct OptimizedGroverAlgorithm {
860 config: QuantumAlgorithmConfig,
862 backend: Option<SciRS2Backend>,
864 circuit_interface: CircuitInterface,
866}
867
868impl OptimizedGroverAlgorithm {
869 pub fn new(config: QuantumAlgorithmConfig) -> Result<Self> {
871 let circuit_interface = CircuitInterface::new(Default::default())?;
872
873 Ok(Self {
874 config,
875 backend: None,
876 circuit_interface,
877 })
878 }
879
880 pub fn with_backend(mut self) -> Result<Self> {
882 self.backend = Some(SciRS2Backend::new());
883 self.circuit_interface = self.circuit_interface.with_backend()?;
884 Ok(self)
885 }
886
887 pub fn search<F>(
889 &mut self,
890 num_qubits: usize,
891 oracle: F,
892 num_targets: usize,
893 ) -> Result<GroverResult>
894 where
895 F: Fn(usize) -> bool + Send + Sync,
896 {
897 let start_time = std::time::Instant::now();
898 let num_items = 1 << num_qubits;
899
900 if num_targets == 0 || num_targets >= num_items {
901 return Err(SimulatorError::InvalidInput(
902 "Invalid number of target items".to_string(),
903 ));
904 }
905
906 let optimal_iterations = self.calculate_optimal_iterations_enhanced(num_items, num_targets);
908
909 let mut circuit = InterfaceCircuit::new(num_qubits, num_qubits);
911
912 self.add_enhanced_superposition(&mut circuit, num_qubits)?;
914
915 for iteration in 0..optimal_iterations {
917 self.add_optimized_oracle(&mut circuit, &oracle, num_qubits, iteration)?;
919
920 self.add_enhanced_diffusion(&mut circuit, num_qubits, iteration, optimal_iterations)?;
922 }
923
924 if self.config.optimization_level == OptimizationLevel::Maximum {
926 Self::add_pre_measurement_amplification(&mut circuit, &oracle, num_qubits)?;
927 }
928
929 for qubit in 0..num_qubits {
931 circuit.add_gate(InterfaceGate::measurement(qubit, qubit));
932 }
933
934 let backend = crate::circuit_interfaces::SimulationBackend::StateVector;
936 let compiled = self.circuit_interface.compile_circuit(&circuit, backend)?;
937 let result = self.circuit_interface.execute_circuit(&compiled, None)?;
938
939 let final_state = if let Some(state) = result.final_state {
941 state.to_vec()
942 } else {
943 let mut state = vec![Complex64::new(0.0, 0.0); 1 << num_qubits];
945 for i in 0..state.len() {
947 if oracle(i) {
948 state[i] = Complex64::new(1.0 / (num_targets as f64).sqrt(), 0.0);
949 } else {
950 let remaining_amp = (1.0 - num_targets as f64 / num_items as f64).sqrt()
951 / ((num_items - num_targets) as f64).sqrt();
952 state[i] = Complex64::new(remaining_amp, 0.0);
953 }
954 }
955 state
956 };
957 let probabilities: Vec<f64> = final_state
958 .iter()
959 .map(scirs2_core::Complex::norm_sqr)
960 .collect();
961
962 let mut items_with_probs: Vec<(usize, f64)> = probabilities
964 .iter()
965 .enumerate()
966 .map(|(i, &p)| (i, p))
967 .collect();
968 items_with_probs.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
969
970 let found_items: Vec<usize> = items_with_probs
971 .iter()
972 .take(num_targets)
973 .filter(|(item, prob)| oracle(*item) && *prob > 1.0 / num_items as f64)
974 .map(|(item, _)| *item)
975 .collect();
976
977 let success_probability = found_items
978 .iter()
979 .map(|&item| probabilities[item])
980 .sum::<f64>();
981
982 let amplification_gain = success_probability / (num_targets as f64 / num_items as f64);
983
984 let resource_stats = AlgorithmResourceStats {
985 qubits_used: num_qubits,
986 circuit_depth: optimal_iterations * (num_qubits * 3 + 10), gate_count: optimal_iterations * (num_qubits * 5 + 20), measurement_count: num_qubits,
989 memory_usage_bytes: (1 << num_qubits) * 16,
990 cnot_count: optimal_iterations * num_qubits,
991 t_gate_count: optimal_iterations * 2,
992 };
993
994 Ok(GroverResult {
995 found_items,
996 final_amplitudes: final_state,
997 iterations: optimal_iterations,
998 optimal_iterations,
999 success_probability,
1000 amplification_gain,
1001 execution_time_ms: start_time.elapsed().as_secs_f64() * 1000.0,
1002 resource_stats,
1003 })
1004 }
1005
1006 fn calculate_optimal_iterations_enhanced(&self, num_items: usize, num_targets: usize) -> usize {
1008 let theta = (num_targets as f64 / num_items as f64).sqrt().asin();
1009 let optimal = (PI / (4.0 * theta) - 0.5).round() as usize;
1010
1011 match self.config.optimization_level {
1013 OptimizationLevel::Maximum => {
1014 let corrected = (optimal as f64 * 1.05).round() as usize; corrected.clamp(1, num_items / 2)
1017 }
1018 OptimizationLevel::Speed => {
1019 (optimal * 9 / 10).max(1)
1021 }
1022 _ => optimal.max(1),
1023 }
1024 }
1025
1026 fn calculate_optimal_iterations(&self, num_items: usize, num_targets: usize) -> usize {
1028 self.calculate_optimal_iterations_enhanced(num_items, num_targets)
1029 }
1030
1031 fn add_enhanced_superposition(
1033 &self,
1034 circuit: &mut InterfaceCircuit,
1035 num_qubits: usize,
1036 ) -> Result<()> {
1037 for qubit in 0..num_qubits {
1039 circuit.add_gate(InterfaceGate::new(InterfaceGateType::Hadamard, vec![qubit]));
1040 }
1041
1042 if self.config.optimization_level == OptimizationLevel::Maximum {
1044 let enhancement_angle = PI / (8.0 * num_qubits as f64);
1045 for qubit in 0..num_qubits {
1046 circuit.add_gate(InterfaceGate::new(
1047 InterfaceGateType::RY(enhancement_angle),
1048 vec![qubit],
1049 ));
1050 }
1051 }
1052
1053 Ok(())
1054 }
1055
1056 fn add_optimized_oracle<F>(
1058 &self,
1059 circuit: &mut InterfaceCircuit,
1060 oracle: &F,
1061 num_qubits: usize,
1062 iteration: usize,
1063 ) -> Result<()>
1064 where
1065 F: Fn(usize) -> bool + Send + Sync,
1066 {
1067 Self::add_oracle_to_circuit(circuit, oracle, num_qubits)?;
1069
1070 if self.config.optimization_level == OptimizationLevel::Maximum && iteration > 0 {
1072 let correction_angle = PI / (2.0 * (iteration + 1) as f64);
1073 circuit.add_gate(InterfaceGate::new(
1074 InterfaceGateType::Phase(correction_angle),
1075 vec![0], ));
1077 }
1078
1079 Ok(())
1080 }
1081
1082 fn add_enhanced_diffusion(
1084 &self,
1085 circuit: &mut InterfaceCircuit,
1086 num_qubits: usize,
1087 iteration: usize,
1088 total_iterations: usize,
1089 ) -> Result<()> {
1090 Self::add_diffusion_to_circuit(circuit, num_qubits)?;
1092
1093 if self.config.optimization_level == OptimizationLevel::Maximum {
1095 let progress = iteration as f64 / total_iterations as f64;
1096 let amplification_angle = PI * 0.1 * (1.0 - progress); for qubit in 0..num_qubits {
1099 circuit.add_gate(InterfaceGate::new(
1100 InterfaceGateType::RZ(amplification_angle),
1101 vec![qubit],
1102 ));
1103 }
1104 }
1105
1106 Ok(())
1107 }
1108
1109 fn add_pre_measurement_amplification<F>(
1111 circuit: &mut InterfaceCircuit,
1112 oracle: &F,
1113 num_qubits: usize,
1114 ) -> Result<()>
1115 where
1116 F: Fn(usize) -> bool + Send + Sync,
1117 {
1118 let final_angle = PI / (4.0 * num_qubits as f64);
1120
1121 for qubit in 0..num_qubits {
1122 circuit.add_gate(InterfaceGate::new(
1123 InterfaceGateType::RY(final_angle),
1124 vec![qubit],
1125 ));
1126 }
1127
1128 for state in 0..(1 << num_qubits) {
1130 if oracle(state) {
1131 circuit.add_gate(InterfaceGate::new(
1133 InterfaceGateType::Phase(PI / 8.0),
1134 vec![0], ));
1136 break; }
1138 }
1139
1140 Ok(())
1141 }
1142
1143 fn apply_oracle_phase<F>(
1145 simulator: &mut StateVectorSimulator,
1146 oracle: &F,
1147 num_qubits: usize,
1148 ) -> Result<()>
1149 where
1150 F: Fn(usize) -> bool + Send + Sync,
1151 {
1152 let mut state = simulator.get_state();
1154
1155 for (index, amplitude) in state.iter_mut().enumerate() {
1156 if oracle(index) {
1157 *amplitude = -*amplitude;
1158 }
1159 }
1160
1161 simulator.set_state(state)?;
1162 Ok(())
1163 }
1164
1165 fn add_oracle_to_circuit<F>(
1167 circuit: &mut InterfaceCircuit,
1168 oracle: &F,
1169 num_qubits: usize,
1170 ) -> Result<()>
1171 where
1172 F: Fn(usize) -> bool + Send + Sync,
1173 {
1174 for state in 0..(1 << num_qubits) {
1176 if oracle(state) {
1177 let mut control_qubits = Vec::new();
1179 let target_qubit = num_qubits - 1; for qubit in 0..num_qubits {
1182 if qubit == target_qubit {
1183 continue; }
1185
1186 if (state >> qubit) & 1 == 0 {
1187 circuit
1189 .add_gate(InterfaceGate::new(InterfaceGateType::PauliX, vec![qubit]));
1190 }
1191 control_qubits.push(qubit);
1192 }
1193
1194 if control_qubits.is_empty() {
1196 circuit.add_gate(InterfaceGate::new(
1198 InterfaceGateType::PauliZ,
1199 vec![target_qubit],
1200 ));
1201 } else {
1202 let mut qubits = control_qubits.clone();
1203 qubits.push(target_qubit);
1204 circuit.add_gate(InterfaceGate::new(
1205 InterfaceGateType::MultiControlledZ(control_qubits.len()),
1206 qubits,
1207 ));
1208 }
1209
1210 for qubit in 0..num_qubits {
1212 if qubit != target_qubit && (state >> qubit) & 1 == 0 {
1213 circuit
1214 .add_gate(InterfaceGate::new(InterfaceGateType::PauliX, vec![qubit]));
1215 }
1216 }
1217 }
1218 }
1219 Ok(())
1220 }
1221
1222 fn add_diffusion_to_circuit(circuit: &mut InterfaceCircuit, num_qubits: usize) -> Result<()> {
1224 for qubit in 0..num_qubits {
1228 circuit.add_gate(InterfaceGate::new(InterfaceGateType::Hadamard, vec![qubit]));
1229 }
1230
1231 if num_qubits > 1 {
1233 let mut control_qubits: Vec<usize> = (1..num_qubits).collect();
1234 control_qubits.push(0); circuit.add_gate(InterfaceGate::new(
1236 InterfaceGateType::MultiControlledZ(num_qubits - 1),
1237 control_qubits,
1238 ));
1239 } else {
1240 circuit.add_gate(InterfaceGate::new(InterfaceGateType::PauliZ, vec![0]));
1241 }
1242
1243 for qubit in 0..num_qubits {
1245 circuit.add_gate(InterfaceGate::new(InterfaceGateType::Hadamard, vec![qubit]));
1246 }
1247
1248 Ok(())
1249 }
1250
1251 fn apply_diffusion_operator(
1253 simulator: &mut StateVectorSimulator,
1254 num_qubits: usize,
1255 ) -> Result<()> {
1256 for qubit in 0..num_qubits {
1260 simulator.apply_h(qubit)?;
1261 }
1262
1263 let mut state = simulator.get_state();
1265 state[0] = -state[0];
1266 simulator.set_state(state)?;
1267
1268 for qubit in 0..num_qubits {
1270 simulator.apply_h(qubit)?;
1271 }
1272
1273 Ok(())
1274 }
1275}
1276
1277pub struct EnhancedPhaseEstimation {
1279 config: QuantumAlgorithmConfig,
1281 backend: Option<SciRS2Backend>,
1283 circuit_interface: CircuitInterface,
1285 qft_engine: SciRS2QFT,
1287}
1288
1289impl EnhancedPhaseEstimation {
1290 pub fn new(config: QuantumAlgorithmConfig) -> Result<Self> {
1292 let circuit_interface = CircuitInterface::new(Default::default())?;
1293 let qft_config = QFTConfig {
1294 method: QFTMethod::SciRS2Exact,
1295 bit_reversal: true,
1296 parallel: config.enable_parallel,
1297 precision_threshold: config.precision_tolerance,
1298 ..Default::default()
1299 };
1300 let qft_engine = SciRS2QFT::new(0, qft_config)?;
1301
1302 Ok(Self {
1303 config,
1304 backend: None,
1305 circuit_interface,
1306 qft_engine,
1307 })
1308 }
1309
1310 pub fn with_backend(mut self) -> Result<Self> {
1312 self.backend = Some(SciRS2Backend::new());
1313 self.circuit_interface = self.circuit_interface.with_backend()?;
1314 self.qft_engine = self.qft_engine.with_backend()?;
1315 Ok(self)
1316 }
1317
1318 pub fn estimate_eigenvalues<U>(
1320 &mut self,
1321 unitary_operator: U,
1322 eigenstate: &Array1<Complex64>,
1323 target_precision: f64,
1324 ) -> Result<PhaseEstimationResult>
1325 where
1326 U: Fn(&mut StateVectorSimulator, usize) -> Result<()> + Send + Sync,
1327 {
1328 let start_time = std::time::Instant::now();
1329
1330 let mut phase_qubits = self.calculate_required_phase_qubits(target_precision);
1332 let system_qubits = (eigenstate.len() as f64).log2().ceil() as usize;
1333 let mut total_qubits = phase_qubits + system_qubits;
1334
1335 let mut best_precision = f64::INFINITY;
1336 let mut best_eigenvalues = Vec::new();
1337 let mut best_eigenvectors: Option<Array2<Complex64>> = None;
1338 let mut precision_iterations = 0;
1339
1340 let max_iterations = match self.config.optimization_level {
1342 OptimizationLevel::Maximum => 20,
1343 OptimizationLevel::Hardware => 15,
1344 _ => 10,
1345 };
1346
1347 for iteration in 0..max_iterations {
1348 precision_iterations += 1;
1349
1350 let iteration_result = self.run_enhanced_phase_estimation_iteration(
1352 &unitary_operator,
1353 eigenstate,
1354 phase_qubits,
1355 system_qubits,
1356 iteration,
1357 )?;
1358
1359 let achieved_precision = 1.0 / f64::from(1 << phase_qubits);
1361
1362 if achieved_precision < best_precision {
1363 best_precision = achieved_precision;
1364 best_eigenvalues = iteration_result.eigenvalues;
1365 best_eigenvectors = iteration_result.eigenvectors;
1366 }
1367
1368 if achieved_precision <= target_precision {
1370 break;
1371 }
1372
1373 if iteration < max_iterations - 1 {
1375 phase_qubits =
1376 Self::adapt_phase_qubits(phase_qubits, achieved_precision, target_precision);
1377 total_qubits = phase_qubits + system_qubits;
1378
1379 let qft_config = crate::scirs2_qft::QFTConfig {
1381 method: crate::scirs2_qft::QFTMethod::SciRS2Exact,
1382 bit_reversal: true,
1383 parallel: self.config.enable_parallel,
1384 precision_threshold: self.config.precision_tolerance,
1385 ..Default::default()
1386 };
1387 self.qft_engine = crate::scirs2_qft::SciRS2QFT::new(phase_qubits, qft_config)?;
1388 }
1389 }
1390
1391 let resource_stats =
1393 Self::estimate_qpe_resources(phase_qubits, system_qubits, precision_iterations);
1394
1395 Ok(PhaseEstimationResult {
1396 eigenvalues: best_eigenvalues,
1397 precisions: vec![best_precision],
1398 eigenvectors: best_eigenvectors,
1399 phase_qubits,
1400 precision_iterations,
1401 execution_time_ms: start_time.elapsed().as_secs_f64() * 1000.0,
1402 resource_stats,
1403 })
1404 }
1405
1406 fn run_phase_estimation_iteration<U>(
1408 &mut self,
1409 unitary_operator: &U,
1410 eigenstate: &Array1<Complex64>,
1411 phase_qubits: usize,
1412 system_qubits: usize,
1413 ) -> Result<f64>
1414 where
1415 U: Fn(&mut StateVectorSimulator, usize) -> Result<()> + Send + Sync,
1416 {
1417 let total_qubits = phase_qubits + system_qubits;
1418 let mut simulator = StateVectorSimulator::new();
1419
1420 simulator.initialize_state(phase_qubits + system_qubits)?;
1425
1426 for qubit in system_qubits..(system_qubits + phase_qubits) {
1428 simulator.apply_h(qubit)?;
1429 }
1430
1431 for i in 0..system_qubits {
1433 if i < eigenstate.len() && eigenstate[i].norm_sqr() > 0.5 {
1434 simulator.apply_x(i)?;
1435 }
1436 }
1437
1438 for (i, control_qubit) in (system_qubits..(system_qubits + phase_qubits)).enumerate() {
1440 let power = 1 << i;
1441
1442 for _ in 0..power {
1444 for target_qubit in 0..system_qubits {
1446 unitary_operator(&mut simulator, target_qubit)?;
1449 }
1450 }
1451 }
1452
1453 let mut state_vec = simulator.get_state_mut();
1456 let mut state_array = Array1::from_vec(state_vec);
1457 self.qft_engine.apply_inverse_qft(&mut state_array)?;
1458
1459 let new_state = state_array.to_vec();
1461 simulator.set_state(new_state)?;
1462
1463 let amplitudes = simulator.get_state();
1465 let mut max_prob = 0.0;
1466 let mut best_measurement = 0;
1467
1468 for (state_index, amplitude) in amplitudes.iter().enumerate() {
1469 let phase_measurement = (state_index >> system_qubits) & ((1 << phase_qubits) - 1);
1470 let prob = amplitude.norm_sqr();
1471
1472 if prob > max_prob {
1473 max_prob = prob;
1474 best_measurement = phase_measurement;
1475 }
1476 }
1477
1478 let eigenvalue =
1480 best_measurement as f64 / f64::from(1 << phase_qubits) * 2.0 * std::f64::consts::PI;
1481 Ok(eigenvalue)
1482 }
1483
1484 fn calculate_required_phase_qubits(&self, target_precision: f64) -> usize {
1486 let base_qubits = (-target_precision.log2()).ceil() as usize + 2;
1487
1488 match self.config.optimization_level {
1490 OptimizationLevel::Maximum => {
1491 (base_qubits as f64 * 1.5).ceil() as usize
1493 }
1494 OptimizationLevel::Memory => {
1495 (base_qubits * 3 / 4).max(3)
1497 }
1498 _ => base_qubits,
1499 }
1500 }
1501
1502 fn adapt_phase_qubits(
1504 current_qubits: usize,
1505 achieved_precision: f64,
1506 target_precision: f64,
1507 ) -> usize {
1508 if achieved_precision > target_precision * 2.0 {
1509 (current_qubits + 2).min(30) } else if achieved_precision < target_precision * 0.5 {
1512 (current_qubits - 1).max(3)
1514 } else {
1515 current_qubits
1516 }
1517 }
1518}
1519
1520struct QPEIterationResult {
1522 eigenvalues: Vec<f64>,
1523 eigenvectors: Option<Array2<Complex64>>,
1524 measurement_probabilities: Vec<f64>,
1525}
1526
1527impl EnhancedPhaseEstimation {
1528 fn run_enhanced_phase_estimation_iteration<U>(
1530 &mut self,
1531 unitary_operator: &U,
1532 eigenstate: &Array1<Complex64>,
1533 phase_qubits: usize,
1534 system_qubits: usize,
1535 iteration: usize,
1536 ) -> Result<QPEIterationResult>
1537 where
1538 U: Fn(&mut StateVectorSimulator, usize) -> Result<()> + Send + Sync,
1539 {
1540 let total_qubits = phase_qubits + system_qubits;
1541 let mut simulator = StateVectorSimulator::new();
1542
1543 simulator.initialize_state(total_qubits)?;
1545
1546 for qubit in system_qubits..(system_qubits + phase_qubits) {
1548 simulator.apply_h(qubit)?;
1549
1550 if self.config.optimization_level == OptimizationLevel::Maximum && iteration > 0 {
1552 }
1556 }
1557
1558 Self::prepare_enhanced_eigenstate(&mut simulator, eigenstate, system_qubits)?;
1560
1561 for (i, control_qubit) in (system_qubits..(system_qubits + phase_qubits)).enumerate() {
1563 let power = 1 << i;
1564
1565 for _ in 0..power {
1567 for target_qubit in 0..system_qubits {
1568 self.apply_enhanced_controlled_unitary(
1570 &mut simulator,
1571 unitary_operator,
1572 control_qubit,
1573 target_qubit,
1574 iteration,
1575 )?;
1576 }
1577 }
1578 }
1579
1580 self.apply_enhanced_inverse_qft(&mut simulator, system_qubits, phase_qubits)?;
1582
1583 let amplitudes = simulator.get_state();
1585 let eigenvalues =
1586 self.extract_enhanced_eigenvalues(&litudes, phase_qubits, system_qubits)?;
1587 let measurement_probs =
1588 Self::calculate_measurement_probabilities(&litudes, phase_qubits);
1589
1590 let eigenvectors = if self.config.optimization_level == OptimizationLevel::Maximum {
1592 Some(Self::extract_eigenvectors(&litudes, system_qubits)?)
1593 } else {
1594 None
1595 };
1596
1597 Ok(QPEIterationResult {
1598 eigenvalues,
1599 eigenvectors,
1600 measurement_probabilities: measurement_probs,
1601 })
1602 }
1603
1604 fn prepare_enhanced_eigenstate(
1606 simulator: &mut StateVectorSimulator,
1607 eigenstate: &Array1<Complex64>,
1608 system_qubits: usize,
1609 ) -> Result<()> {
1610 for i in 0..system_qubits.min(eigenstate.len()) {
1612 let amplitude = eigenstate[i];
1613 let probability = amplitude.norm_sqr();
1614
1615 if probability > 0.5 {
1617 simulator.apply_x(i)?;
1618
1619 if amplitude.arg().abs() > 1e-10 {
1621 }
1623 } else if probability > 0.25 {
1624 let _theta = 2.0 * probability.sqrt().acos();
1626 if amplitude.arg().abs() > 1e-10 {
1629 }
1631 }
1632 }
1633
1634 Ok(())
1635 }
1636
1637 fn apply_enhanced_controlled_unitary<U>(
1639 &self,
1640 simulator: &mut StateVectorSimulator,
1641 unitary_operator: &U,
1642 control_qubit: usize,
1643 target_qubit: usize,
1644 iteration: usize,
1645 ) -> Result<()>
1646 where
1647 U: Fn(&mut StateVectorSimulator, usize) -> Result<()> + Send + Sync,
1648 {
1649 unitary_operator(simulator, target_qubit)?;
1652
1653 if self.config.enable_error_mitigation && iteration > 0 {
1655 }
1658
1659 Ok(())
1660 }
1661
1662 fn apply_enhanced_inverse_qft(
1664 &mut self,
1665 simulator: &mut StateVectorSimulator,
1666 system_qubits: usize,
1667 phase_qubits: usize,
1668 ) -> Result<()> {
1669 let mut state = Array1::from_vec(simulator.get_state());
1671
1672 let phase_start = system_qubits;
1674 let phase_end = system_qubits + phase_qubits;
1675
1676 let state_size = 1 << phase_qubits;
1678 let mut phase_state = Array1::zeros(state_size);
1679
1680 for i in 0..state_size {
1681 let full_index = i << system_qubits; if full_index < state.len() {
1683 phase_state[i] = state[full_index];
1684 }
1685 }
1686
1687 self.qft_engine.apply_inverse_qft(&mut phase_state)?;
1689
1690 for i in 0..state_size {
1692 let full_index = i << system_qubits;
1693 if full_index < state.len() {
1694 state[full_index] = phase_state[i];
1695 }
1696 }
1697
1698 simulator.set_state(state.to_vec())?;
1700
1701 Ok(())
1702 }
1703
1704 fn extract_enhanced_eigenvalues(
1706 &self,
1707 amplitudes: &[Complex64],
1708 phase_qubits: usize,
1709 system_qubits: usize,
1710 ) -> Result<Vec<f64>> {
1711 let mut eigenvalues = Vec::new();
1712 let phase_states = 1 << phase_qubits;
1713
1714 let mut max_prob = 0.0;
1716 let mut best_measurement = 0;
1717
1718 for phase_val in 0..phase_states {
1719 let mut total_prob = 0.0;
1720
1721 for sys_val in 0..(1 << system_qubits) {
1723 let full_index = phase_val << system_qubits | sys_val;
1724 if full_index < amplitudes.len() {
1725 total_prob += amplitudes[full_index].norm_sqr();
1726 }
1727 }
1728
1729 if total_prob > max_prob {
1730 max_prob = total_prob;
1731 best_measurement = phase_val;
1732 }
1733 }
1734
1735 let eigenvalue = best_measurement as f64 / phase_states as f64 * 2.0 * PI;
1737 eigenvalues.push(eigenvalue);
1738
1739 if self.config.optimization_level == OptimizationLevel::Maximum {
1741 for phase_val in 0..phase_states {
1743 if phase_val == best_measurement {
1744 continue;
1745 }
1746
1747 let mut total_prob = 0.0;
1748 for sys_val in 0..(1 << system_qubits) {
1749 let full_index = phase_val << system_qubits | sys_val;
1750 if full_index < amplitudes.len() {
1751 total_prob += amplitudes[full_index].norm_sqr();
1752 }
1753 }
1754
1755 if total_prob > max_prob * 0.1 {
1757 let secondary_eigenvalue = phase_val as f64 / phase_states as f64 * 2.0 * PI;
1758 eigenvalues.push(secondary_eigenvalue);
1759 }
1760 }
1761 }
1762
1763 Ok(eigenvalues)
1764 }
1765
1766 fn calculate_measurement_probabilities(
1768 amplitudes: &[Complex64],
1769 phase_qubits: usize,
1770 ) -> Vec<f64> {
1771 let phase_states = 1 << phase_qubits;
1772 let mut probabilities = vec![0.0; phase_states];
1773
1774 for (i, amplitude) in amplitudes.iter().enumerate() {
1775 let trailing_zeros = amplitudes.len().trailing_zeros();
1776 let phase_qubits_u32 = phase_qubits as u32;
1777
1778 let phase_val = if trailing_zeros >= phase_qubits_u32 {
1779 i >> (trailing_zeros - phase_qubits_u32)
1780 } else {
1781 i << (phase_qubits_u32 - trailing_zeros)
1782 };
1783
1784 if phase_val < phase_states {
1785 probabilities[phase_val] += amplitude.norm_sqr();
1786 }
1787 }
1788
1789 probabilities
1790 }
1791
1792 fn extract_eigenvectors(
1794 amplitudes: &[Complex64],
1795 system_qubits: usize,
1796 ) -> Result<Array2<Complex64>> {
1797 let system_states = 1 << system_qubits;
1798 let mut eigenvectors = Array2::zeros((system_states, 1));
1799
1800 for i in 0..system_states.min(amplitudes.len()) {
1802 eigenvectors[[i, 0]] = amplitudes[i];
1803 }
1804
1805 Ok(eigenvectors)
1806 }
1807
1808 const fn estimate_qpe_resources(
1810 phase_qubits: usize,
1811 system_qubits: usize,
1812 iterations: usize,
1813 ) -> AlgorithmResourceStats {
1814 let total_qubits = phase_qubits + system_qubits;
1815
1816 let controlled_operations = phase_qubits * system_qubits * iterations;
1818 let qft_gates = phase_qubits * phase_qubits / 2; let base_gate_count = controlled_operations * 10 + qft_gates * 5;
1820
1821 AlgorithmResourceStats {
1822 qubits_used: total_qubits,
1823 circuit_depth: phase_qubits * 50 * iterations, gate_count: base_gate_count,
1825 measurement_count: phase_qubits,
1826 memory_usage_bytes: (1 << total_qubits) * 16,
1827 cnot_count: controlled_operations,
1828 t_gate_count: qft_gates / 2, }
1830 }
1831
1832 fn apply_controlled_modular_exp(
1834 simulator: &mut StateVectorSimulator,
1835 control_qubit: usize,
1836 target_range: std::ops::Range<usize>,
1837 base: u64,
1838 power: usize,
1839 modulus: u64,
1840 ) -> Result<()> {
1841 let mut exp_base = base;
1843 for _ in 0..power {
1844 exp_base = (exp_base * exp_base) % modulus;
1845 }
1846
1847 let num_targets = target_range.len();
1850
1851 for x in 0..(1 << num_targets) {
1853 if x < modulus as usize {
1854 let result = ((x as u64 * exp_base) % modulus) as usize;
1855
1856 if x != result {
1858 for i in 0..num_targets {
1860 let x_bit = (x >> i) & 1;
1861 let result_bit = (result >> i) & 1;
1862
1863 if x_bit != result_bit {
1864 let target_qubit = target_range.start + i;
1866 simulator.apply_cnot_public(control_qubit, target_qubit)?;
1867 }
1868 }
1869 }
1870 }
1871 }
1872
1873 Ok(())
1874 }
1875}
1876
1877pub fn benchmark_quantum_algorithms() -> Result<HashMap<String, f64>> {
1879 let mut results = HashMap::new();
1880
1881 let shor_start = std::time::Instant::now();
1883 let config = QuantumAlgorithmConfig::default();
1884 let mut shor = OptimizedShorAlgorithm::new(config)?;
1885 let _shor_result = shor.factor(15)?; results.insert(
1887 "shor_15".to_string(),
1888 shor_start.elapsed().as_secs_f64() * 1000.0,
1889 );
1890
1891 let grover_start = std::time::Instant::now();
1893 let config = QuantumAlgorithmConfig::default();
1894 let mut grover = OptimizedGroverAlgorithm::new(config)?;
1895 let oracle = |x: usize| x == 5 || x == 10; let _grover_result = grover.search(4, oracle, 2)?;
1897 results.insert(
1898 "grover_4qubits".to_string(),
1899 grover_start.elapsed().as_secs_f64() * 1000.0,
1900 );
1901
1902 let qpe_start = std::time::Instant::now();
1904 let config = QuantumAlgorithmConfig::default();
1905 let mut qpe = EnhancedPhaseEstimation::new(config)?;
1906 let eigenstate = Array1::from_vec(vec![Complex64::new(1.0, 0.0), Complex64::new(0.0, 0.0)]);
1907 let unitary = |sim: &mut StateVectorSimulator, target_qubit: usize| -> Result<()> {
1908 sim.apply_z_public(target_qubit)?;
1910 Ok(())
1911 };
1912 let _qpe_result = qpe.estimate_eigenvalues(unitary, &eigenstate, 1e-3)?;
1913 results.insert(
1914 "phase_estimation".to_string(),
1915 qpe_start.elapsed().as_secs_f64() * 1000.0,
1916 );
1917
1918 Ok(results)
1919}
1920
1921#[cfg(test)]
1922mod tests {
1923 use super::*;
1924
1925 #[test]
1926 fn test_shor_algorithm_creation() {
1927 let config = QuantumAlgorithmConfig::default();
1928 let shor = OptimizedShorAlgorithm::new(config);
1929 assert!(shor.is_ok());
1930 }
1931
1932 #[test]
1933 fn test_shor_trivial_cases() {
1934 let config = QuantumAlgorithmConfig::default();
1935 let mut shor =
1936 OptimizedShorAlgorithm::new(config).expect("Shor algorithm creation should succeed");
1937
1938 let result = shor.factor(14).expect("Factoring 14 should succeed");
1940 assert!(result.factors.contains(&2));
1941 assert!(result.factors.contains(&7));
1942
1943 }
1945
1946 #[test]
1947 fn test_grover_algorithm_creation() {
1948 let config = QuantumAlgorithmConfig::default();
1949 let grover = OptimizedGroverAlgorithm::new(config);
1950 assert!(grover.is_ok());
1951 }
1952
1953 #[test]
1954 fn test_grover_optimal_iterations() {
1955 let config = QuantumAlgorithmConfig::default();
1956 let grover = OptimizedGroverAlgorithm::new(config)
1957 .expect("Grover algorithm creation should succeed");
1958
1959 let num_items = 16; let num_targets = 1;
1961 let iterations = grover.calculate_optimal_iterations(num_items, num_targets);
1962
1963 assert!((3..=4).contains(&iterations));
1965 }
1966
1967 #[test]
1968 fn test_phase_estimation_creation() {
1969 let config = QuantumAlgorithmConfig::default();
1970 let qpe = EnhancedPhaseEstimation::new(config);
1971 assert!(qpe.is_ok());
1972 }
1973
1974 #[test]
1975 fn test_continued_fractions() {
1976 let config = QuantumAlgorithmConfig::default();
1977 let _shor =
1978 OptimizedShorAlgorithm::new(config).expect("Shor algorithm creation should succeed");
1979
1980 let convergents = OptimizedShorAlgorithm::continued_fractions(0.375, 100); assert!(!convergents.is_empty());
1982
1983 assert!(convergents.iter().any(|&(num, den)| num == 3 && den == 8));
1985 }
1986
1987 #[test]
1988 fn test_modular_exponentiation() {
1989 let config = QuantumAlgorithmConfig::default();
1990 let _shor =
1991 OptimizedShorAlgorithm::new(config).expect("Shor algorithm creation should succeed");
1992
1993 assert_eq!(OptimizedShorAlgorithm::mod_exp(2, 3, 5), 3); assert_eq!(OptimizedShorAlgorithm::mod_exp(3, 4, 7), 4); }
1996
1997 #[test]
1998 fn test_phase_estimation_simple() {
1999 let config = QuantumAlgorithmConfig::default();
2000 let mut qpe =
2001 EnhancedPhaseEstimation::new(config).expect("Phase estimation creation should succeed");
2002
2003 let eigenstate = Array1::from_vec(vec![Complex64::new(1.0, 0.0), Complex64::new(0.0, 0.0)]);
2005
2006 let z_unitary = |sim: &mut StateVectorSimulator, _target_qubit: usize| -> Result<()> {
2008 Ok(()) };
2011
2012 let result = qpe.estimate_eigenvalues(z_unitary, &eigenstate, 1e-2);
2013 assert!(result.is_ok());
2014
2015 let qpe_result = result.expect("Phase estimation should succeed");
2016 assert!(!qpe_result.eigenvalues.is_empty());
2017 assert_eq!(qpe_result.eigenvalues.len(), qpe_result.precisions.len());
2018 }
2019
2020 #[test]
2021 fn test_grover_search_functionality() {
2022 let config = QuantumAlgorithmConfig::default();
2023 let mut grover = OptimizedGroverAlgorithm::new(config)
2024 .expect("Grover algorithm creation should succeed");
2025
2026 let oracle = |x: usize| x == 3;
2028
2029 let result = grover.search(3, oracle, 1);
2030 if let Err(e) = &result {
2031 eprintln!("Grover search failed: {e:?}");
2032 }
2033 assert!(result.is_ok());
2034
2035 let grover_result = result.expect("Grover search should succeed");
2036 assert_eq!(grover_result.iterations, grover_result.optimal_iterations);
2037 assert!(grover_result.success_probability >= 0.0);
2038 assert!(grover_result.success_probability <= 1.0);
2039 }
2040
2041 #[test]
2042 fn test_shor_algorithm_classical_cases() {
2043 let config = QuantumAlgorithmConfig::default();
2044 let mut shor =
2045 OptimizedShorAlgorithm::new(config).expect("Shor algorithm creation should succeed");
2046
2047 let result = shor.factor(10).expect("Factoring 10 should succeed");
2049 assert!(!result.factors.is_empty());
2050 assert!(result.factors.contains(&2) || result.factors.contains(&5));
2051
2052 let result = shor.factor(7).expect("Factoring 7 should succeed");
2054 if !result.factors.is_empty() {
2055 let product: u64 = result.factors.iter().product();
2057 assert_eq!(product, 7);
2058 }
2059 }
2060
2061 #[test]
2062 fn test_quantum_algorithm_benchmarks() {
2063 let benchmarks = benchmark_quantum_algorithms();
2064 assert!(benchmarks.is_ok());
2065
2066 let results = benchmarks.expect("Benchmarks should succeed");
2067 assert!(results.contains_key("shor_15"));
2068 assert!(results.contains_key("grover_4qubits"));
2069 assert!(results.contains_key("phase_estimation"));
2070
2071 for (algorithm, time) in results {
2073 assert!(
2074 time >= 0.0,
2075 "Algorithm {algorithm} had negative execution time"
2076 );
2077 }
2078 }
2079
2080 #[test]
2081 fn test_grover_optimal_iterations_calculation() {
2082 let config = QuantumAlgorithmConfig::default();
2083 let grover = OptimizedGroverAlgorithm::new(config)
2084 .expect("Grover algorithm creation should succeed");
2085
2086 assert_eq!(grover.calculate_optimal_iterations(4, 1), 1); assert_eq!(grover.calculate_optimal_iterations(16, 1), 3); let iterations_64_1 = grover.calculate_optimal_iterations(64, 1); assert!((6..=8).contains(&iterations_64_1));
2092 }
2093
2094 #[test]
2095 fn test_phase_estimation_precision_control() {
2096 let config = QuantumAlgorithmConfig {
2097 precision_tolerance: 1e-3,
2098 ..Default::default()
2099 };
2100 let mut qpe =
2101 EnhancedPhaseEstimation::new(config).expect("Phase estimation creation should succeed");
2102
2103 let eigenstate = Array1::from_vec(vec![Complex64::new(1.0, 0.0)]);
2105 let identity_op =
2106 |_sim: &mut StateVectorSimulator, _target: usize| -> Result<()> { Ok(()) };
2107
2108 let result = qpe.estimate_eigenvalues(identity_op, &eigenstate, 1e-3);
2109 assert!(result.is_ok());
2110
2111 let qpe_result = result.expect("Phase estimation should succeed");
2112 assert!(qpe_result.precisions[0] <= 1e-3);
2113 assert!(qpe_result.phase_qubits >= 3); }
2115
2116 #[test]
2117 fn test_grover_multiple_targets() {
2118 let config = QuantumAlgorithmConfig::default();
2119 let mut grover = OptimizedGroverAlgorithm::new(config)
2120 .expect("Grover algorithm creation should succeed");
2121
2122 let oracle = |x: usize| x == 2 || x == 5;
2124
2125 let result = grover.search(3, oracle, 2);
2126 assert!(result.is_ok());
2127
2128 let grover_result = result.expect("Grover search should succeed");
2129 assert!(grover_result.success_probability >= 0.0);
2130 assert!(grover_result.success_probability <= 1.0);
2131 assert!(grover_result.iterations > 0);
2132 }
2133
2134 #[test]
2135 fn test_grover_four_qubits() {
2136 let config = QuantumAlgorithmConfig::default();
2137 let mut grover = OptimizedGroverAlgorithm::new(config)
2138 .expect("Grover algorithm creation should succeed");
2139
2140 let oracle = |x: usize| x == 7;
2142
2143 let result = grover.search(4, oracle, 1);
2144 assert!(result.is_ok());
2145
2146 let grover_result = result.expect("Grover search should succeed");
2147 assert!(grover_result.resource_stats.qubits_used >= 4);
2148 assert!(grover_result.iterations >= 2 && grover_result.iterations <= 5);
2149 }
2150
2151 #[test]
2152 fn test_shor_perfect_square() {
2153 let config = QuantumAlgorithmConfig::default();
2154 let mut shor =
2155 OptimizedShorAlgorithm::new(config).expect("Shor algorithm creation should succeed");
2156
2157 let result = shor.factor(16).expect("Factoring 16 should succeed");
2159 assert!(result.factors.contains(&4) || result.factors.contains(&2));
2161 }
2162
2163 #[test]
2164 fn test_shor_semiprime() {
2165 let config = QuantumAlgorithmConfig::default();
2166 let mut shor =
2167 OptimizedShorAlgorithm::new(config).expect("Shor algorithm creation should succeed");
2168
2169 let result = shor.factor(15).expect("Factoring 15 should succeed");
2172
2173 assert!(result.execution_time_ms >= 0.0);
2175
2176 if !result.factors.is_empty() {
2178 for &factor in &result.factors {
2180 assert!(15 % factor == 0 || factor == 15);
2181 }
2182 }
2183 }
2184
2185 #[test]
2186 fn test_optimization_levels() {
2187 let levels = vec![
2189 OptimizationLevel::Basic,
2190 OptimizationLevel::Memory,
2191 OptimizationLevel::Speed,
2192 OptimizationLevel::Hardware,
2193 OptimizationLevel::Maximum,
2194 ];
2195
2196 for level in levels {
2197 let config = QuantumAlgorithmConfig {
2198 optimization_level: level,
2199 ..Default::default()
2200 };
2201
2202 let grover = OptimizedGroverAlgorithm::new(config.clone());
2204 assert!(grover.is_ok());
2205
2206 let shor = OptimizedShorAlgorithm::new(config.clone());
2208 assert!(shor.is_ok());
2209
2210 let qpe = EnhancedPhaseEstimation::new(config);
2212 assert!(qpe.is_ok());
2213 }
2214 }
2215
2216 #[test]
2217 fn test_resource_stats() {
2218 let config = QuantumAlgorithmConfig::default();
2219 let mut shor =
2220 OptimizedShorAlgorithm::new(config).expect("Shor algorithm creation should succeed");
2221
2222 let result = shor.factor(6).expect("Factoring 6 should succeed");
2223 let stats = &result.resource_stats;
2224
2225 assert!(!result.factors.is_empty() || stats.qubits_used == 0);
2229 }
2230
2231 #[test]
2232 fn test_grover_resource_stats() {
2233 let config = QuantumAlgorithmConfig::default();
2234 let mut grover = OptimizedGroverAlgorithm::new(config)
2235 .expect("Grover algorithm creation should succeed");
2236
2237 let oracle = |x: usize| x == 1;
2238 let result = grover
2239 .search(2, oracle, 1)
2240 .expect("Grover search should succeed");
2241
2242 assert!(result.resource_stats.qubits_used > 0);
2244 assert!(result.resource_stats.gate_count > 0);
2245 }
2246
2247 #[test]
2248 fn test_phase_estimation_resource_stats() {
2249 let config = QuantumAlgorithmConfig::default();
2250 let mut qpe =
2251 EnhancedPhaseEstimation::new(config).expect("Phase estimation creation should succeed");
2252
2253 let eigenstate = Array1::from_vec(vec![Complex64::new(1.0, 0.0)]);
2254 let identity_op =
2255 |_sim: &mut StateVectorSimulator, _target: usize| -> Result<()> { Ok(()) };
2256
2257 let result = qpe
2258 .estimate_eigenvalues(identity_op, &eigenstate, 1e-2)
2259 .expect("Phase estimation should succeed");
2260
2261 assert!(result.resource_stats.qubits_used > 0);
2263 }
2264
2265 #[test]
2266 fn test_config_defaults() {
2267 let config = QuantumAlgorithmConfig::default();
2268
2269 assert_eq!(config.optimization_level, OptimizationLevel::Maximum);
2270 assert!(config.use_classical_preprocessing);
2271 assert!(config.enable_error_mitigation);
2272 assert_eq!(config.max_circuit_depth, 1000);
2273 assert!((config.precision_tolerance - 1e-10).abs() < 1e-15);
2274 assert!(config.enable_parallel);
2275 }
2276
2277 #[test]
2278 fn test_shor_result_structure() {
2279 let config = QuantumAlgorithmConfig::default();
2280 let mut shor =
2281 OptimizedShorAlgorithm::new(config).expect("Shor algorithm creation should succeed");
2282
2283 let result = shor.factor(6).expect("Factoring 6 should succeed");
2284
2285 assert_eq!(result.n, 6);
2287 assert!(result.execution_time_ms >= 0.0);
2288 assert!(result.classical_preprocessing_ms >= 0.0);
2289 assert!(result.quantum_computation_ms >= 0.0);
2290 assert!(result.success_probability >= 0.0);
2291 assert!(result.success_probability <= 1.0);
2292 }
2293
2294 #[test]
2295 fn test_grover_result_structure() {
2296 let config = QuantumAlgorithmConfig::default();
2297 let mut grover = OptimizedGroverAlgorithm::new(config)
2298 .expect("Grover algorithm creation should succeed");
2299
2300 let oracle = |x: usize| x == 0;
2301 let result = grover
2302 .search(2, oracle, 1)
2303 .expect("Grover search should succeed");
2304
2305 assert!(result.resource_stats.qubits_used > 0);
2307 assert!(result.success_probability >= 0.0);
2308 assert!(result.success_probability <= 1.0);
2309 assert!(result.execution_time_ms >= 0.0);
2310 }
2311
2312 #[test]
2313 fn test_modular_exponentiation_edge_cases() {
2314 let config = QuantumAlgorithmConfig::default();
2315 let _shor =
2316 OptimizedShorAlgorithm::new(config).expect("Shor algorithm creation should succeed");
2317
2318 assert_eq!(OptimizedShorAlgorithm::mod_exp(1, 100, 7), 1); assert_eq!(OptimizedShorAlgorithm::mod_exp(5, 0, 7), 1); assert_eq!(OptimizedShorAlgorithm::mod_exp(2, 10, 1024), 0); }
2323
2324 #[test]
2325 fn test_continued_fractions_edge_cases() {
2326 let config = QuantumAlgorithmConfig::default();
2327 let _shor =
2328 OptimizedShorAlgorithm::new(config).expect("Shor algorithm creation should succeed");
2329
2330 let convergents = OptimizedShorAlgorithm::continued_fractions(0.5, 10);
2332 assert!(convergents.iter().any(|&(num, den)| num == 1 && den == 2));
2333
2334 let convergents = OptimizedShorAlgorithm::continued_fractions(1.0 / 3.0, 20);
2336 assert!(convergents.iter().any(|&(num, den)| num == 1 && den == 3));
2337 }
2338
2339 #[test]
2340 fn test_grover_iterations_scaling() {
2341 let config = QuantumAlgorithmConfig::default();
2342 let grover = OptimizedGroverAlgorithm::new(config)
2343 .expect("Grover algorithm creation should succeed");
2344
2345 let iter_8 = grover.calculate_optimal_iterations(8, 1);
2347 let iter_32 = grover.calculate_optimal_iterations(32, 1);
2348
2349 let ratio = iter_32 as f64 / iter_8 as f64;
2351 assert!((1.5..=2.5).contains(&ratio));
2352 }
2353
2354 #[test]
2355 fn test_error_mitigation_disabled() {
2356 let config = QuantumAlgorithmConfig {
2357 enable_error_mitigation: false,
2358 ..Default::default()
2359 };
2360 let mut grover = OptimizedGroverAlgorithm::new(config)
2361 .expect("Grover algorithm creation should succeed");
2362
2363 let oracle = |x: usize| x == 1;
2364 let result = grover.search(2, oracle, 1);
2365 assert!(result.is_ok());
2366 }
2367
2368 #[test]
2369 fn test_parallel_disabled() {
2370 let config = QuantumAlgorithmConfig {
2371 enable_parallel: false,
2372 ..Default::default()
2373 };
2374 let mut shor =
2375 OptimizedShorAlgorithm::new(config).expect("Shor algorithm creation should succeed");
2376
2377 let result = shor.factor(6);
2378 assert!(result.is_ok());
2379 }
2380
2381 #[test]
2382 fn test_algorithm_resource_stats_default() {
2383 let stats = AlgorithmResourceStats::default();
2384
2385 assert_eq!(stats.qubits_used, 0);
2386 assert_eq!(stats.gate_count, 0);
2387 assert_eq!(stats.circuit_depth, 0);
2388 assert_eq!(stats.cnot_count, 0);
2389 assert_eq!(stats.t_gate_count, 0);
2390 assert_eq!(stats.memory_usage_bytes, 0);
2391 assert_eq!(stats.measurement_count, 0);
2392 }
2393
2394 #[test]
2395 fn test_shor_small_numbers() {
2396 let config = QuantumAlgorithmConfig::default();
2397 let mut shor =
2398 OptimizedShorAlgorithm::new(config).expect("Shor algorithm creation should succeed");
2399
2400 for n in [4, 6, 8, 9, 10, 12] {
2402 let result = shor.factor(n);
2403 assert!(result.is_ok(), "Failed to factor {n}");
2404 }
2405 }
2406
2407 #[test]
2408 fn test_grover_single_qubit() {
2409 let config = QuantumAlgorithmConfig::default();
2410 let mut grover = OptimizedGroverAlgorithm::new(config)
2411 .expect("Grover algorithm creation should succeed");
2412
2413 let oracle = |x: usize| x == 1;
2415 let result = grover.search(1, oracle, 1);
2416 assert!(result.is_ok());
2417 }
2418}