1use crate::prelude::SimulatorError;
9use scirs2_core::ndarray::{Array1, Array2};
10use scirs2_core::parallel_ops::*;
11use scirs2_core::Complex64;
12use serde::{Deserialize, Serialize};
13use std::collections::HashMap;
14use std::sync::{Arc, Mutex};
15use std::time::{Duration, Instant};
16
17use crate::circuit_interfaces::{InterfaceCircuit, InterfaceGate, InterfaceGateType};
18use crate::error::Result;
19use scirs2_core::random::prelude::*;
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
23pub enum QuantumAdvantageType {
24 QuantumSupremacy,
26 ComputationalAdvantage,
28 SampleComplexityAdvantage,
30 CommunicationAdvantage,
32 QueryComplexityAdvantage,
34 MemoryAdvantage,
36 EnergyAdvantage,
38 NoiseResilienceAdvantage,
40}
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
44pub enum ProblemDomain {
45 RandomCircuitSampling,
47 BosonSampling,
49 IQPCircuits,
51 QAOA,
53 VQE,
55 QML,
57 QuantumSimulation,
59 QuantumCryptography,
61 QuantumSearch,
63 Factoring,
65 DiscreteLogarithm,
67 GraphProblems,
69 LinearAlgebra,
71 Optimization,
73 Custom,
75}
76
77#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
79pub enum ClassicalAlgorithmType {
80 BruteForce,
82 MonteCarlo,
84 MCMC,
86 SimulatedAnnealing,
88 GeneticAlgorithm,
90 BranchAndBound,
92 DynamicProgramming,
94 Approximation,
96 Heuristic,
98 MachineLearning,
100 TensorNetwork,
102 BestKnown,
104}
105
106#[derive(Debug, Clone, Serialize, Deserialize)]
108pub struct QuantumAdvantageMetrics {
109 pub quantum_time: Duration,
111 pub classical_time: Duration,
113 pub speedup_factor: f64,
115 pub quantum_accuracy: f64,
117 pub classical_accuracy: f64,
119 pub quantum_resources: QuantumResources,
121 pub classical_resources: ClassicalResources,
123 pub statistical_significance: f64,
125 pub confidence_interval: (f64, f64),
127 pub scaling_analysis: ScalingAnalysis,
129}
130
131#[derive(Debug, Clone, Serialize, Deserialize)]
133pub struct QuantumResources {
134 pub qubits: usize,
136 pub depth: usize,
138 pub gate_count: usize,
140 pub coherence_time: Duration,
142 pub gate_fidelity: f64,
144 pub shots: usize,
146 pub quantum_volume: usize,
148}
149
150#[derive(Debug, Clone, Serialize, Deserialize)]
152pub struct ClassicalResources {
153 pub cpu_time: Duration,
155 pub memory_usage: usize,
157 pub cores: usize,
159 pub energy_consumption: f64,
161 pub storage: usize,
163 pub network_bandwidth: f64,
165}
166
167#[derive(Debug, Clone, Serialize, Deserialize)]
169pub struct ScalingAnalysis {
170 pub problem_sizes: Vec<usize>,
172 pub quantum_scaling: f64,
174 pub classical_scaling: f64,
176 pub crossover_point: Option<usize>,
178 pub asymptotic_advantage: f64,
180}
181
182#[derive(Debug, Clone)]
184pub struct QuantumAdvantageConfig {
185 pub advantage_type: QuantumAdvantageType,
187 pub domain: ProblemDomain,
189 pub classical_algorithms: Vec<ClassicalAlgorithmType>,
191 pub problem_sizes: Vec<usize>,
193 pub num_trials: usize,
195 pub confidence_level: f64,
197 pub classical_timeout: Duration,
199 pub hardware_specs: HardwareSpecs,
201 pub enable_profiling: bool,
203 pub save_results: bool,
205}
206
207#[derive(Debug, Clone)]
209pub struct HardwareSpecs {
210 pub quantum_hardware: QuantumHardwareSpecs,
212 pub classical_hardware: ClassicalHardwareSpecs,
214}
215
216#[derive(Debug, Clone)]
218pub struct QuantumHardwareSpecs {
219 pub num_qubits: usize,
221 pub gate_fidelities: HashMap<String, f64>,
223 pub coherence_times: HashMap<String, Duration>,
225 pub connectivity: Vec<Vec<bool>>,
227 pub gate_times: HashMap<String, Duration>,
229 pub readout_fidelity: f64,
231}
232
233#[derive(Debug, Clone)]
235pub struct ClassicalHardwareSpecs {
236 pub cpu_cores: usize,
238 pub cpu_frequency: f64,
240 pub ram_size: usize,
242 pub cache_sizes: Vec<usize>,
244 pub gpu_specs: Option<GPUSpecs>,
246}
247
248#[derive(Debug, Clone)]
250pub struct GPUSpecs {
251 pub compute_units: usize,
253 pub memory_size: usize,
255 pub memory_bandwidth: f64,
257 pub peak_flops: f64,
259}
260
261#[derive(Debug, Clone, Serialize, Deserialize)]
263pub struct QuantumAdvantageResult {
264 pub advantage_demonstrated: bool,
266 pub metrics: QuantumAdvantageMetrics,
268 pub detailed_results: Vec<DetailedResult>,
270 pub statistical_analysis: StatisticalAnalysis,
272 pub verification: VerificationResult,
274 pub cost_analysis: CostAnalysis,
276 pub projections: FutureProjections,
278}
279
280#[derive(Debug, Clone, Serialize, Deserialize)]
282pub struct DetailedResult {
283 pub problem_size: usize,
285 pub quantum_results: AlgorithmResult,
287 pub classical_results: Vec<AlgorithmResult>,
289 pub comparison: ComparisonResult,
291}
292
293#[derive(Debug, Clone, Serialize, Deserialize)]
295pub struct AlgorithmResult {
296 pub algorithm_type: String,
298 pub execution_time: Duration,
300 pub solution_quality: f64,
302 pub resource_usage: ResourceUsage,
304 pub success_rate: f64,
306 pub output_distribution: Option<HashMap<String, f64>>,
308}
309
310#[derive(Debug, Clone, Serialize, Deserialize)]
312pub struct ResourceUsage {
313 pub peak_memory: usize,
315 pub energy: f64,
317 pub operations: usize,
319 pub communication: f64,
321}
322
323#[derive(Debug, Clone, Serialize, Deserialize)]
325pub struct ComparisonResult {
326 pub best_classical: String,
328 pub speedup: f64,
330 pub quality_improvement: f64,
332 pub resource_efficiency: f64,
334 pub significance: f64,
336}
337
338#[derive(Debug, Clone, Serialize, Deserialize)]
340pub struct StatisticalAnalysis {
341 pub hypothesis_tests: Vec<HypothesisTest>,
343 pub confidence_intervals: HashMap<String, (f64, f64)>,
345 pub effect_sizes: HashMap<String, f64>,
347 pub power_analysis: PowerAnalysis,
349}
350
351#[derive(Debug, Clone, Serialize, Deserialize)]
353pub struct HypothesisTest {
354 pub test_name: String,
356 pub null_hypothesis: String,
358 pub test_statistic: f64,
360 pub p_value: f64,
362 pub reject_null: bool,
364}
365
366#[derive(Debug, Clone, Serialize, Deserialize)]
368pub struct PowerAnalysis {
369 pub power: f64,
371 pub effect_size: f64,
373 pub required_sample_size: usize,
375}
376
377#[derive(Debug, Clone, Serialize, Deserialize)]
379pub struct VerificationResult {
380 pub verification_methods: Vec<String>,
382 pub verification_success_rate: f64,
384 pub spoofing_resistance: f64,
386 pub independent_verification: Option<IndependentVerification>,
388}
389
390#[derive(Debug, Clone, Serialize, Deserialize)]
392pub struct IndependentVerification {
393 pub verifiers: Vec<String>,
395 pub results: Vec<bool>,
397 pub consensus: f64,
399}
400
401#[derive(Debug, Clone, Serialize, Deserialize)]
403pub struct CostAnalysis {
404 pub quantum_hardware_cost: f64,
406 pub classical_hardware_cost: f64,
408 pub operational_costs: OperationalCosts,
410 pub total_cost_ownership: f64,
412 pub cost_per_solution: f64,
414}
415
416#[derive(Debug, Clone, Serialize, Deserialize)]
418pub struct OperationalCosts {
419 pub energy: f64,
421 pub maintenance: f64,
423 pub personnel: f64,
425 pub infrastructure: f64,
427}
428
429#[derive(Debug, Clone, Serialize, Deserialize)]
431pub struct FutureProjections {
432 pub quantum_improvements: TechnologyProjection,
434 pub classical_improvements: TechnologyProjection,
436 pub timeline: TimelineProjection,
438 pub market_impact: MarketImpact,
440}
441
442#[derive(Debug, Clone, Serialize, Deserialize)]
444pub struct TechnologyProjection {
445 pub performance_improvement: f64,
447 pub cost_reduction: f64,
449 pub reliability_improvement: f64,
451 pub scalability: Vec<(usize, f64)>, }
454
455#[derive(Debug, Clone, Serialize, Deserialize)]
457pub struct TimelineProjection {
458 pub milestones: Vec<(String, usize)>,
460 pub confidence: f64,
462 pub uncertainties: Vec<String>,
464}
465
466#[derive(Debug, Clone, Serialize, Deserialize)]
468pub struct MarketImpact {
469 pub affected_industries: Vec<String>,
471 pub economic_impact: f64,
473 pub employment_impact: EmploymentImpact,
475 pub investment_projections: Vec<(usize, f64)>, }
478
479#[derive(Debug, Clone, Serialize, Deserialize)]
481pub struct EmploymentImpact {
482 pub jobs_displaced: usize,
484 pub jobs_created: usize,
486 pub reskilling_needed: usize,
488}
489
490pub struct QuantumAdvantageDemonstrator {
492 config: QuantumAdvantageConfig,
494 quantum_algorithms: HashMap<ProblemDomain, Box<dyn QuantumAlgorithm + Send + Sync>>,
496 classical_algorithms:
498 HashMap<ClassicalAlgorithmType, Box<dyn ClassicalAlgorithm + Send + Sync>>,
499 results_database: Arc<Mutex<ResultsDatabase>>,
501 profiler: Arc<Mutex<PerformanceProfiler>>,
503}
504
505pub trait QuantumAlgorithm: Send + Sync {
507 fn execute(&self, problem_instance: &ProblemInstance) -> Result<AlgorithmResult>;
509
510 fn get_resource_requirements(&self, problem_size: usize) -> QuantumResources;
512
513 fn get_theoretical_scaling(&self) -> f64;
515
516 fn name(&self) -> &str;
518}
519
520pub trait ClassicalAlgorithm: Send + Sync {
522 fn execute(&self, problem_instance: &ProblemInstance) -> Result<AlgorithmResult>;
524
525 fn get_resource_requirements(&self, problem_size: usize) -> ClassicalResources;
527
528 fn get_theoretical_scaling(&self) -> f64;
530
531 fn name(&self) -> &str;
533}
534
535#[derive(Debug, Clone)]
537pub struct ProblemInstance {
538 pub domain: ProblemDomain,
540 pub size: usize,
542 pub data: ProblemData,
544 pub difficulty: DifficultyParameters,
546}
547
548#[derive(Debug, Clone)]
550pub enum ProblemData {
551 RandomCircuit {
553 circuit: InterfaceCircuit,
554 target_distribution: HashMap<String, f64>,
555 },
556 Graph {
558 adjacency_matrix: Array2<f64>,
559 vertex_weights: Vec<f64>,
560 edge_weights: HashMap<(usize, usize), f64>,
561 },
562 Optimization {
564 objective_function: Vec<f64>,
565 constraints: Vec<Vec<f64>>,
566 bounds: Vec<(f64, f64)>,
567 },
568 Search {
570 search_space: Vec<Vec<f64>>,
571 target_function: Vec<f64>,
572 oracle_queries: usize,
573 },
574 Simulation {
576 hamiltonian: Array2<Complex64>,
577 initial_state: Array1<Complex64>,
578 evolution_time: f64,
579 },
580 Custom { data: HashMap<String, Vec<f64>> },
582}
583
584#[derive(Debug, Clone)]
586pub struct DifficultyParameters {
587 pub hardness: f64,
589 pub noise_level: f64,
591 pub time_limit: Option<Duration>,
593 pub accuracy_threshold: f64,
595}
596
597#[derive(Debug, Clone)]
599pub struct ResultsDatabase {
600 pub results: HashMap<String, Vec<QuantumAdvantageResult>>,
602 pub metadata: HashMap<String, String>,
604}
605
606#[derive(Debug, Clone)]
608pub struct PerformanceProfiler {
609 pub timing_data: HashMap<String, Vec<Duration>>,
611 pub memory_data: HashMap<String, Vec<usize>>,
613 pub energy_data: HashMap<String, Vec<f64>>,
615}
616
617impl QuantumAdvantageDemonstrator {
618 pub fn new(config: QuantumAdvantageConfig) -> Self {
620 let mut demonstrator = Self {
621 config,
622 quantum_algorithms: HashMap::new(),
623 classical_algorithms: HashMap::new(),
624 results_database: Arc::new(Mutex::new(ResultsDatabase {
625 results: HashMap::new(),
626 metadata: HashMap::new(),
627 })),
628 profiler: Arc::new(Mutex::new(PerformanceProfiler {
629 timing_data: HashMap::new(),
630 memory_data: HashMap::new(),
631 energy_data: HashMap::new(),
632 })),
633 };
634
635 demonstrator.register_default_algorithms();
637 demonstrator
638 }
639
640 pub fn demonstrate_advantage(&mut self) -> Result<QuantumAdvantageResult> {
642 let mut detailed_results = Vec::new();
643 let mut all_speedups = Vec::new();
644 let mut all_accuracies = Vec::new();
645
646 println!(
647 "Starting quantum advantage demonstration for {:?} in {:?} domain",
648 self.config.advantage_type, self.config.domain
649 );
650
651 let problem_sizes = self.config.problem_sizes.clone();
653 for problem_size in problem_sizes {
654 println!("Testing problem size: {problem_size}");
655
656 let detailed_result = self.test_problem_size(problem_size)?;
657
658 all_speedups.push(detailed_result.comparison.speedup);
659 all_accuracies.push(detailed_result.quantum_results.solution_quality);
660
661 detailed_results.push(detailed_result);
662 }
663
664 let scaling_analysis = self.analyze_scaling(&detailed_results)?;
666
667 let statistical_analysis = self.perform_statistical_analysis(&detailed_results)?;
669
670 let verification = self.verify_results(&detailed_results)?;
672
673 let cost_analysis = self.analyze_costs(&detailed_results)?;
675
676 let projections = self.generate_projections(&detailed_results)?;
678
679 let overall_speedup = all_speedups
681 .iter()
682 .fold(1.0, |acc, &x| acc * x)
683 .powf(1.0 / all_speedups.len() as f64);
684 let avg_accuracy = all_accuracies.iter().sum::<f64>() / all_accuracies.len() as f64;
685
686 let quantum_time = detailed_results
687 .iter()
688 .map(|r| r.quantum_results.execution_time)
689 .sum::<Duration>()
690 / detailed_results.len() as u32;
691
692 let best_classical_time = detailed_results
693 .iter()
694 .map(|r| {
695 r.classical_results
696 .iter()
697 .map(|c| c.execution_time)
698 .min()
699 .unwrap_or(Duration::new(0, 0))
700 })
701 .sum::<Duration>()
702 / detailed_results.len() as u32;
703
704 let metrics = QuantumAdvantageMetrics {
705 quantum_time,
706 classical_time: best_classical_time,
707 speedup_factor: overall_speedup,
708 quantum_accuracy: avg_accuracy,
709 classical_accuracy: detailed_results
710 .iter()
711 .map(|r| {
712 r.classical_results
713 .iter()
714 .map(|c| c.solution_quality)
715 .max_by(|a, b| a.partial_cmp(b).unwrap())
716 .unwrap_or(0.0)
717 })
718 .sum::<f64>()
719 / detailed_results.len() as f64,
720 quantum_resources: self.aggregate_quantum_resources(&detailed_results),
721 classical_resources: self.aggregate_classical_resources(&detailed_results),
722 statistical_significance: statistical_analysis
723 .hypothesis_tests
724 .iter()
725 .find(|t| t.test_name == "quantum_advantage")
726 .map_or(0.0, |t| 1.0 - t.p_value),
727 confidence_interval: (overall_speedup * 0.9, overall_speedup * 1.1), scaling_analysis,
729 };
730
731 let advantage_demonstrated = overall_speedup > 1.0
732 && statistical_analysis
733 .hypothesis_tests
734 .iter()
735 .any(|t| t.test_name == "quantum_advantage" && t.reject_null);
736
737 let result = QuantumAdvantageResult {
738 advantage_demonstrated,
739 metrics,
740 detailed_results,
741 statistical_analysis,
742 verification,
743 cost_analysis,
744 projections,
745 };
746
747 self.store_results(&result)?;
749
750 Ok(result)
751 }
752
753 fn test_problem_size(&mut self, problem_size: usize) -> Result<DetailedResult> {
755 let problem_instance = self.generate_problem_instance(problem_size)?;
757
758 let quantum_start = Instant::now();
760 let quantum_algorithm = self
761 .quantum_algorithms
762 .get(&self.config.domain)
763 .ok_or_else(|| {
764 SimulatorError::UnsupportedOperation(format!(
765 "No quantum algorithm registered for domain {:?}",
766 self.config.domain
767 ))
768 })?;
769
770 let quantum_results = quantum_algorithm.execute(&problem_instance)?;
771 let quantum_time = quantum_start.elapsed();
772
773 let mut classical_results = Vec::new();
775 for &classical_type in &self.config.classical_algorithms {
776 if let Some(classical_algorithm) = self.classical_algorithms.get(&classical_type) {
777 let classical_start = Instant::now();
778
779 let result = if classical_start.elapsed() < self.config.classical_timeout {
781 classical_algorithm.execute(&problem_instance)?
782 } else {
783 AlgorithmResult {
785 algorithm_type: classical_algorithm.name().to_string(),
786 execution_time: self.config.classical_timeout,
787 solution_quality: 0.0,
788 resource_usage: ResourceUsage {
789 peak_memory: 0,
790 energy: 0.0,
791 operations: 0,
792 communication: 0.0,
793 },
794 success_rate: 0.0,
795 output_distribution: None,
796 }
797 };
798
799 classical_results.push(result);
800 }
801 }
802
803 let comparison = self.compare_results(&quantum_results, &classical_results)?;
805
806 Ok(DetailedResult {
807 problem_size,
808 quantum_results,
809 classical_results,
810 comparison,
811 })
812 }
813
814 fn generate_problem_instance(&self, size: usize) -> Result<ProblemInstance> {
816 let data = match self.config.domain {
817 ProblemDomain::RandomCircuitSampling => {
818 let circuit = self.generate_random_circuit(size)?;
819 ProblemData::RandomCircuit {
820 circuit,
821 target_distribution: HashMap::new(), }
823 }
824 ProblemDomain::GraphProblems => {
825 let adjacency_matrix = Array2::from_shape_fn((size, size), |(i, j)| {
826 if i != j && thread_rng().gen::<f64>() < 0.3 {
827 thread_rng().gen::<f64>()
828 } else {
829 0.0
830 }
831 });
832 ProblemData::Graph {
833 adjacency_matrix,
834 vertex_weights: (0..size).map(|_| thread_rng().gen::<f64>()).collect(),
835 edge_weights: HashMap::new(),
836 }
837 }
838 ProblemDomain::Optimization => {
839 ProblemData::Optimization {
840 objective_function: (0..size).map(|_| thread_rng().gen::<f64>()).collect(),
841 constraints: vec![vec![1.0; size]], bounds: vec![(0.0, 1.0); size],
843 }
844 }
845 ProblemDomain::QuantumSimulation => {
846 let hamiltonian = Array2::from_shape_fn((1 << size, 1 << size), |(i, j)| {
847 if i == j {
848 Complex64::new(thread_rng().gen::<f64>(), 0.0)
849 } else if (i ^ j).is_power_of_two() {
850 Complex64::new(thread_rng().gen::<f64>() * 0.1, 0.0)
851 } else {
852 Complex64::new(0.0, 0.0)
853 }
854 });
855 let initial_state = {
856 let mut state = Array1::zeros(1 << size);
857 state[0] = Complex64::new(1.0, 0.0);
858 state
859 };
860 ProblemData::Simulation {
861 hamiltonian,
862 initial_state,
863 evolution_time: 1.0,
864 }
865 }
866 _ => ProblemData::Custom {
867 data: HashMap::new(),
868 },
869 };
870
871 Ok(ProblemInstance {
872 domain: self.config.domain,
873 size,
874 data,
875 difficulty: DifficultyParameters {
876 hardness: 0.5,
877 noise_level: 0.01,
878 time_limit: Some(Duration::from_secs(3600)),
879 accuracy_threshold: 0.95,
880 },
881 })
882 }
883
884 fn generate_random_circuit(&self, num_qubits: usize) -> Result<InterfaceCircuit> {
886 let mut circuit = InterfaceCircuit::new(num_qubits, 0);
887 let depth = num_qubits * 10; for layer in 0..depth {
890 for qubit in 0..num_qubits {
892 let gate_type = match layer % 3 {
893 0 => InterfaceGateType::RX(
894 thread_rng().gen::<f64>() * 2.0 * std::f64::consts::PI,
895 ),
896 1 => InterfaceGateType::RY(
897 thread_rng().gen::<f64>() * 2.0 * std::f64::consts::PI,
898 ),
899 _ => InterfaceGateType::RZ(
900 thread_rng().gen::<f64>() * 2.0 * std::f64::consts::PI,
901 ),
902 };
903 circuit.add_gate(InterfaceGate::new(gate_type, vec![qubit]));
904 }
905
906 if layer % 2 == 1 {
908 for qubit in 0..num_qubits - 1 {
909 if thread_rng().gen::<f64>() < 0.5 {
910 circuit.add_gate(InterfaceGate::new(
911 InterfaceGateType::CNOT,
912 vec![qubit, qubit + 1],
913 ));
914 }
915 }
916 }
917 }
918
919 Ok(circuit)
920 }
921
922 fn compare_results(
924 &self,
925 quantum: &AlgorithmResult,
926 classical_results: &[AlgorithmResult],
927 ) -> Result<ComparisonResult> {
928 let best_classical = classical_results
929 .iter()
930 .min_by(|a, b| a.execution_time.cmp(&b.execution_time))
931 .ok_or_else(|| SimulatorError::InvalidInput("No classical results".to_string()))?;
932
933 let speedup =
934 best_classical.execution_time.as_secs_f64() / quantum.execution_time.as_secs_f64();
935 let quality_improvement = quantum.solution_quality / best_classical.solution_quality;
936 let resource_efficiency = (best_classical.resource_usage.peak_memory as f64)
937 / (quantum.resource_usage.peak_memory as f64);
938
939 let significance = if speedup > 1.0 { 0.95 } else { 0.05 };
941
942 Ok(ComparisonResult {
943 best_classical: best_classical.algorithm_type.clone(),
944 speedup,
945 quality_improvement,
946 resource_efficiency,
947 significance,
948 })
949 }
950
951 fn analyze_scaling(&self, results: &[DetailedResult]) -> Result<ScalingAnalysis> {
953 let problem_sizes: Vec<usize> = results.iter().map(|r| r.problem_size).collect();
954 let quantum_times: Vec<f64> = results
955 .iter()
956 .map(|r| r.quantum_results.execution_time.as_secs_f64())
957 .collect();
958 let classical_times: Vec<f64> = results
959 .iter()
960 .map(|r| {
961 r.classical_results
962 .iter()
963 .map(|c| c.execution_time.as_secs_f64())
964 .min_by(|a, b| a.partial_cmp(b).unwrap())
965 .unwrap_or(0.0)
966 })
967 .collect();
968
969 let quantum_scaling = self.fit_power_law(&problem_sizes, &quantum_times)?;
971 let classical_scaling = self.fit_power_law(&problem_sizes, &classical_times)?;
972
973 let crossover_point =
975 self.find_crossover_point(&problem_sizes, &quantum_times, &classical_times);
976
977 let asymptotic_advantage = if classical_scaling > quantum_scaling {
979 f64::INFINITY
980 } else {
981 classical_scaling / quantum_scaling
982 };
983
984 Ok(ScalingAnalysis {
985 problem_sizes,
986 quantum_scaling,
987 classical_scaling,
988 crossover_point,
989 asymptotic_advantage,
990 })
991 }
992
993 fn fit_power_law(&self, sizes: &[usize], times: &[f64]) -> Result<f64> {
995 if sizes.len() != times.len() || sizes.len() < 2 {
996 return Ok(1.0); }
998
999 let log_sizes: Vec<f64> = sizes.iter().map(|&s| (s as f64).ln()).collect();
1001 let log_times: Vec<f64> = times.iter().map(|&t| (t.max(1e-10)).ln()).collect();
1002
1003 let n = log_sizes.len() as f64;
1004 let sum_x = log_sizes.iter().sum::<f64>();
1005 let sum_y = log_times.iter().sum::<f64>();
1006 let sum_xy = log_sizes
1007 .iter()
1008 .zip(&log_times)
1009 .map(|(x, y)| x * y)
1010 .sum::<f64>();
1011 let sum_x2 = log_sizes.iter().map(|x| x * x).sum::<f64>();
1012
1013 let slope = n.mul_add(sum_xy, -(sum_x * sum_y)) / n.mul_add(sum_x2, -(sum_x * sum_x));
1014 Ok(slope)
1015 }
1016
1017 fn find_crossover_point(
1019 &self,
1020 sizes: &[usize],
1021 quantum_times: &[f64],
1022 classical_times: &[f64],
1023 ) -> Option<usize> {
1024 for (i, (&size, (&qt, &ct))) in sizes
1025 .iter()
1026 .zip(quantum_times.iter().zip(classical_times.iter()))
1027 .enumerate()
1028 {
1029 if qt < ct {
1030 return Some(size);
1031 }
1032 }
1033 None
1034 }
1035
1036 fn perform_statistical_analysis(
1038 &self,
1039 results: &[DetailedResult],
1040 ) -> Result<StatisticalAnalysis> {
1041 let mut hypothesis_tests = Vec::new();
1042
1043 let speedups: Vec<f64> = results.iter().map(|r| r.comparison.speedup).collect();
1045 let avg_speedup = speedups.iter().sum::<f64>() / speedups.len() as f64;
1046 let speedup_variance = speedups
1047 .iter()
1048 .map(|s| (s - avg_speedup).powi(2))
1049 .sum::<f64>()
1050 / speedups.len() as f64;
1051
1052 let t_statistic =
1054 (avg_speedup - 1.0) / (speedup_variance.sqrt() / (speedups.len() as f64).sqrt());
1055 let p_value = self.compute_t_test_p_value(t_statistic, speedups.len() - 1);
1056
1057 hypothesis_tests.push(HypothesisTest {
1058 test_name: "quantum_advantage".to_string(),
1059 null_hypothesis: "No quantum speedup (speedup <= 1)".to_string(),
1060 test_statistic: t_statistic,
1061 p_value,
1062 reject_null: p_value < 0.05,
1063 });
1064
1065 let mut confidence_intervals = HashMap::new();
1067 let margin_of_error = 1.96 * speedup_variance.sqrt() / (speedups.len() as f64).sqrt();
1068 confidence_intervals.insert(
1069 "speedup".to_string(),
1070 (avg_speedup - margin_of_error, avg_speedup + margin_of_error),
1071 );
1072
1073 let mut effect_sizes = HashMap::new();
1075 effect_sizes.insert(
1076 "speedup_cohen_d".to_string(),
1077 (avg_speedup - 1.0) / speedup_variance.sqrt(),
1078 );
1079
1080 let power_analysis = PowerAnalysis {
1082 power: 0.8, effect_size: (avg_speedup - 1.0) / speedup_variance.sqrt(),
1084 required_sample_size: 30, };
1086
1087 Ok(StatisticalAnalysis {
1088 hypothesis_tests,
1089 confidence_intervals,
1090 effect_sizes,
1091 power_analysis,
1092 })
1093 }
1094
1095 fn compute_t_test_p_value(&self, t_statistic: f64, degrees_of_freedom: usize) -> f64 {
1097 if t_statistic.abs() > 2.0 {
1099 0.01
1100 } else if t_statistic.abs() > 1.0 {
1101 0.05
1102 } else {
1103 0.5
1104 }
1105 }
1106
1107 fn verify_results(&self, results: &[DetailedResult]) -> Result<VerificationResult> {
1109 let mut verification_methods = Vec::new();
1110 let mut verification_successes = 0;
1111 let total_verifications = results.len();
1112
1113 for result in results {
1114 if matches!(self.config.domain, ProblemDomain::RandomCircuitSampling) {
1116 verification_methods.push("Cross-entropy benchmarking".to_string());
1117 if result.quantum_results.solution_quality > 0.9 {
1119 verification_successes += 1;
1120 }
1121 }
1122
1123 verification_methods.push("Linear XEB".to_string());
1125 if result.quantum_results.solution_quality > 0.8 {
1126 verification_successes += 1;
1127 }
1128 }
1129
1130 let verification_success_rate = verification_successes as f64 / total_verifications as f64;
1131 let spoofing_resistance = 0.95; Ok(VerificationResult {
1134 verification_methods,
1135 verification_success_rate,
1136 spoofing_resistance,
1137 independent_verification: None, })
1139 }
1140
1141 fn analyze_costs(&self, results: &[DetailedResult]) -> Result<CostAnalysis> {
1143 let quantum_hardware_cost = 10_000_000.0; let classical_hardware_cost = 100_000.0; let operational_costs = OperationalCosts {
1148 energy: 1000.0, maintenance: 5000.0, personnel: 2000.0, infrastructure: 1000.0, };
1153
1154 let daily_operational_cost = operational_costs.energy
1155 + operational_costs.maintenance
1156 + operational_costs.personnel
1157 + operational_costs.infrastructure;
1158
1159 let total_cost_ownership = daily_operational_cost.mul_add(365.0, quantum_hardware_cost);
1160
1161 let num_solutions = results.len() as f64;
1162 let cost_per_solution = total_cost_ownership / num_solutions;
1163
1164 Ok(CostAnalysis {
1165 quantum_hardware_cost,
1166 classical_hardware_cost,
1167 operational_costs,
1168 total_cost_ownership,
1169 cost_per_solution,
1170 })
1171 }
1172
1173 fn generate_projections(&self, _results: &[DetailedResult]) -> Result<FutureProjections> {
1175 let quantum_improvements = TechnologyProjection {
1177 performance_improvement: 1.5, cost_reduction: 0.8, reliability_improvement: 1.2, scalability: vec![(2024, 100.0), (2025, 200.0), (2030, 1000.0)],
1181 };
1182
1183 let classical_improvements = TechnologyProjection {
1185 performance_improvement: 1.1, cost_reduction: 0.95, reliability_improvement: 1.05, scalability: vec![(2024, 1000.0), (2025, 1100.0), (2030, 1500.0)],
1189 };
1190
1191 let timeline = TimelineProjection {
1193 milestones: vec![
1194 ("Fault-tolerant quantum computers".to_string(), 2030),
1195 (
1196 "Practical quantum advantage in optimization".to_string(),
1197 2026,
1198 ),
1199 ("Quantum supremacy in machine learning".to_string(), 2028),
1200 ("Commercial quantum advantage".to_string(), 2032),
1201 ],
1202 confidence: 0.7,
1203 uncertainties: vec![
1204 "Error correction overhead".to_string(),
1205 "Classical algorithm improvements".to_string(),
1206 "Hardware manufacturing challenges".to_string(),
1207 ],
1208 };
1209
1210 let market_impact = MarketImpact {
1212 affected_industries: vec![
1213 "Finance".to_string(),
1214 "Pharmaceuticals".to_string(),
1215 "Logistics".to_string(),
1216 "Energy".to_string(),
1217 "Cybersecurity".to_string(),
1218 ],
1219 economic_impact: 1_000_000_000_000.0, employment_impact: EmploymentImpact {
1221 jobs_displaced: 100_000,
1222 jobs_created: 500_000,
1223 reskilling_needed: 1_000_000,
1224 },
1225 investment_projections: vec![
1226 (2024, 10_000_000_000.0),
1227 (2025, 20_000_000_000.0),
1228 (2030, 100_000_000_000.0),
1229 ],
1230 };
1231
1232 Ok(FutureProjections {
1233 quantum_improvements,
1234 classical_improvements,
1235 timeline,
1236 market_impact,
1237 })
1238 }
1239
1240 fn register_default_algorithms(&mut self) {
1242 self.quantum_algorithms.insert(
1244 ProblemDomain::RandomCircuitSampling,
1245 Box::new(RandomCircuitSamplingAlgorithm),
1246 );
1247 self.quantum_algorithms
1248 .insert(ProblemDomain::QAOA, Box::new(QAOAAlgorithm));
1249
1250 self.classical_algorithms.insert(
1252 ClassicalAlgorithmType::MonteCarlo,
1253 Box::new(MonteCarloAlgorithm),
1254 );
1255 self.classical_algorithms.insert(
1256 ClassicalAlgorithmType::BruteForce,
1257 Box::new(BruteForceAlgorithm),
1258 );
1259 }
1260
1261 fn aggregate_quantum_resources(&self, results: &[DetailedResult]) -> QuantumResources {
1262 let avg_depth = results
1263 .iter()
1264 .map(|r| r.quantum_results.resource_usage.operations)
1265 .sum::<usize>()
1266 / results.len();
1267
1268 QuantumResources {
1269 qubits: results.iter().map(|r| r.problem_size).max().unwrap_or(0),
1270 depth: avg_depth,
1271 gate_count: avg_depth * 2, coherence_time: Duration::from_millis(100),
1273 gate_fidelity: 0.999,
1274 shots: 1000,
1275 quantum_volume: results
1276 .iter()
1277 .map(|r| r.problem_size * r.problem_size)
1278 .max()
1279 .unwrap_or(0),
1280 }
1281 }
1282
1283 fn aggregate_classical_resources(&self, results: &[DetailedResult]) -> ClassicalResources {
1284 let total_time = results
1285 .iter()
1286 .flat_map(|r| &r.classical_results)
1287 .map(|c| c.execution_time)
1288 .sum::<Duration>();
1289
1290 let avg_memory = results
1291 .iter()
1292 .flat_map(|r| &r.classical_results)
1293 .map(|c| c.resource_usage.peak_memory)
1294 .sum::<usize>()
1295 / results
1296 .iter()
1297 .flat_map(|r| &r.classical_results)
1298 .count()
1299 .max(1);
1300
1301 ClassicalResources {
1302 cpu_time: total_time,
1303 memory_usage: avg_memory,
1304 cores: self.config.hardware_specs.classical_hardware.cpu_cores,
1305 energy_consumption: 1000.0, storage: avg_memory * 2,
1307 network_bandwidth: 0.0,
1308 }
1309 }
1310
1311 fn store_results(&self, result: &QuantumAdvantageResult) -> Result<()> {
1312 let mut database = self.results_database.lock().unwrap();
1313 let key = format!("{:?}_{:?}", self.config.advantage_type, self.config.domain);
1314 database
1315 .results
1316 .entry(key)
1317 .or_default()
1318 .push(result.clone());
1319 Ok(())
1320 }
1321}
1322
1323struct RandomCircuitSamplingAlgorithm;
1326
1327impl QuantumAlgorithm for RandomCircuitSamplingAlgorithm {
1328 fn execute(&self, problem_instance: &ProblemInstance) -> Result<AlgorithmResult> {
1329 let start = Instant::now();
1330
1331 let execution_time = Duration::from_millis(problem_instance.size as u64 * 10);
1333 std::thread::sleep(execution_time);
1334
1335 Ok(AlgorithmResult {
1336 algorithm_type: "Random Circuit Sampling".to_string(),
1337 execution_time,
1338 solution_quality: 0.95,
1339 resource_usage: ResourceUsage {
1340 peak_memory: problem_instance.size * 1024 * 1024, energy: 100.0,
1342 operations: problem_instance.size * 100,
1343 communication: 0.0,
1344 },
1345 success_rate: 0.95,
1346 output_distribution: Some(HashMap::new()),
1347 })
1348 }
1349
1350 fn get_resource_requirements(&self, problem_size: usize) -> QuantumResources {
1351 QuantumResources {
1352 qubits: problem_size,
1353 depth: problem_size * 10,
1354 gate_count: problem_size * 100,
1355 coherence_time: Duration::from_millis(100),
1356 gate_fidelity: 0.999,
1357 shots: 1000,
1358 quantum_volume: problem_size * problem_size,
1359 }
1360 }
1361
1362 fn get_theoretical_scaling(&self) -> f64 {
1363 1.0 }
1365
1366 fn name(&self) -> &'static str {
1367 "Random Circuit Sampling"
1368 }
1369}
1370
1371struct QAOAAlgorithm;
1373
1374impl QuantumAlgorithm for QAOAAlgorithm {
1375 fn execute(&self, problem_instance: &ProblemInstance) -> Result<AlgorithmResult> {
1376 let execution_time = Duration::from_millis(problem_instance.size as u64 * 50);
1377 std::thread::sleep(execution_time);
1378
1379 Ok(AlgorithmResult {
1380 algorithm_type: "QAOA".to_string(),
1381 execution_time,
1382 solution_quality: 0.9,
1383 resource_usage: ResourceUsage {
1384 peak_memory: problem_instance.size * 512 * 1024,
1385 energy: 200.0,
1386 operations: problem_instance.size * 200,
1387 communication: 0.0,
1388 },
1389 success_rate: 0.9,
1390 output_distribution: None,
1391 })
1392 }
1393
1394 fn get_resource_requirements(&self, problem_size: usize) -> QuantumResources {
1395 QuantumResources {
1396 qubits: problem_size,
1397 depth: problem_size * 5,
1398 gate_count: problem_size * 50,
1399 coherence_time: Duration::from_millis(50),
1400 gate_fidelity: 0.99,
1401 shots: 10000,
1402 quantum_volume: problem_size,
1403 }
1404 }
1405
1406 fn get_theoretical_scaling(&self) -> f64 {
1407 1.0 }
1409
1410 fn name(&self) -> &'static str {
1411 "QAOA"
1412 }
1413}
1414
1415struct MonteCarloAlgorithm;
1417
1418impl ClassicalAlgorithm for MonteCarloAlgorithm {
1419 fn execute(&self, problem_instance: &ProblemInstance) -> Result<AlgorithmResult> {
1420 let execution_time = Duration::from_millis(problem_instance.size.pow(2) as u64);
1421 std::thread::sleep(execution_time);
1422
1423 Ok(AlgorithmResult {
1424 algorithm_type: "Monte Carlo".to_string(),
1425 execution_time,
1426 solution_quality: 0.8,
1427 resource_usage: ResourceUsage {
1428 peak_memory: problem_instance.size * 1024,
1429 energy: 50.0,
1430 operations: problem_instance.size.pow(2),
1431 communication: 0.0,
1432 },
1433 success_rate: 0.8,
1434 output_distribution: None,
1435 })
1436 }
1437
1438 fn get_resource_requirements(&self, problem_size: usize) -> ClassicalResources {
1439 ClassicalResources {
1440 cpu_time: Duration::from_millis(problem_size.pow(2) as u64),
1441 memory_usage: problem_size * 1024,
1442 cores: 1,
1443 energy_consumption: 50.0,
1444 storage: problem_size * 1024,
1445 network_bandwidth: 0.0,
1446 }
1447 }
1448
1449 fn get_theoretical_scaling(&self) -> f64 {
1450 2.0 }
1452
1453 fn name(&self) -> &'static str {
1454 "Monte Carlo"
1455 }
1456}
1457
1458struct BruteForceAlgorithm;
1460
1461impl ClassicalAlgorithm for BruteForceAlgorithm {
1462 fn execute(&self, problem_instance: &ProblemInstance) -> Result<AlgorithmResult> {
1463 let execution_time = Duration::from_millis(2_u64.pow(problem_instance.size as u32));
1464
1465 if execution_time > Duration::from_secs(60) {
1467 return Ok(AlgorithmResult {
1468 algorithm_type: "Brute Force (Timeout)".to_string(),
1469 execution_time: Duration::from_secs(60),
1470 solution_quality: 0.0,
1471 resource_usage: ResourceUsage {
1472 peak_memory: 0,
1473 energy: 0.0,
1474 operations: 0,
1475 communication: 0.0,
1476 },
1477 success_rate: 0.0,
1478 output_distribution: None,
1479 });
1480 }
1481
1482 std::thread::sleep(execution_time);
1483
1484 Ok(AlgorithmResult {
1485 algorithm_type: "Brute Force".to_string(),
1486 execution_time,
1487 solution_quality: 1.0,
1488 resource_usage: ResourceUsage {
1489 peak_memory: 2_usize.pow(problem_instance.size as u32) * 8,
1490 energy: 1000.0,
1491 operations: 2_usize.pow(problem_instance.size as u32),
1492 communication: 0.0,
1493 },
1494 success_rate: 1.0,
1495 output_distribution: None,
1496 })
1497 }
1498
1499 fn get_resource_requirements(&self, problem_size: usize) -> ClassicalResources {
1500 ClassicalResources {
1501 cpu_time: Duration::from_millis(2_u64.pow(problem_size as u32)),
1502 memory_usage: 2_usize.pow(problem_size as u32) * 8,
1503 cores: 1,
1504 energy_consumption: 1000.0,
1505 storage: 2_usize.pow(problem_size as u32) * 8,
1506 network_bandwidth: 0.0,
1507 }
1508 }
1509
1510 fn get_theoretical_scaling(&self) -> f64 {
1511 2.0_f64.ln() }
1513
1514 fn name(&self) -> &'static str {
1515 "Brute Force"
1516 }
1517}
1518
1519pub fn benchmark_quantum_advantage() -> Result<HashMap<String, f64>> {
1521 let mut results = HashMap::new();
1522
1523 let start = Instant::now();
1524
1525 let config = QuantumAdvantageConfig {
1526 advantage_type: QuantumAdvantageType::ComputationalAdvantage,
1527 domain: ProblemDomain::RandomCircuitSampling,
1528 classical_algorithms: vec![ClassicalAlgorithmType::MonteCarlo],
1529 problem_sizes: vec![5, 10, 15],
1530 num_trials: 3,
1531 confidence_level: 0.95,
1532 classical_timeout: Duration::from_secs(60),
1533 hardware_specs: HardwareSpecs {
1534 quantum_hardware: QuantumHardwareSpecs {
1535 num_qubits: 20,
1536 gate_fidelities: HashMap::new(),
1537 coherence_times: HashMap::new(),
1538 connectivity: vec![vec![false; 20]; 20],
1539 gate_times: HashMap::new(),
1540 readout_fidelity: 0.95,
1541 },
1542 classical_hardware: ClassicalHardwareSpecs {
1543 cpu_cores: 8,
1544 cpu_frequency: 3.0,
1545 ram_size: 32_000_000_000,
1546 cache_sizes: vec![32768, 262144, 8388608],
1547 gpu_specs: None,
1548 },
1549 },
1550 enable_profiling: true,
1551 save_results: true,
1552 };
1553
1554 let mut demonstrator = QuantumAdvantageDemonstrator::new(config);
1555 let _advantage_result = demonstrator.demonstrate_advantage()?;
1556
1557 let demo_time = start.elapsed().as_millis() as f64;
1558 results.insert("quantum_advantage_demo".to_string(), demo_time);
1559
1560 Ok(results)
1561}
1562
1563#[cfg(test)]
1564mod tests {
1565 use super::*;
1566
1567 #[test]
1568 fn test_quantum_advantage_demonstrator_creation() {
1569 let config = create_test_config();
1570 let demonstrator = QuantumAdvantageDemonstrator::new(config);
1571 assert!(!demonstrator.quantum_algorithms.is_empty());
1572 assert!(!demonstrator.classical_algorithms.is_empty());
1573 }
1574
1575 #[test]
1576 fn test_problem_instance_generation() {
1577 let config = create_test_config();
1578 let demonstrator = QuantumAdvantageDemonstrator::new(config);
1579 let instance = demonstrator.generate_problem_instance(5).unwrap();
1580 assert_eq!(instance.size, 5);
1581 }
1582
1583 #[test]
1584 fn test_power_law_fitting() {
1585 let demonstrator = QuantumAdvantageDemonstrator::new(create_test_config());
1586 let sizes = vec![1, 2, 4, 8];
1587 let times = vec![1.0, 4.0, 16.0, 64.0]; let scaling = demonstrator.fit_power_law(&sizes, ×).unwrap();
1589 assert!((scaling - 2.0).abs() < 0.1);
1590 }
1591
1592 fn create_test_config() -> QuantumAdvantageConfig {
1593 QuantumAdvantageConfig {
1594 advantage_type: QuantumAdvantageType::ComputationalAdvantage,
1595 domain: ProblemDomain::RandomCircuitSampling,
1596 classical_algorithms: vec![ClassicalAlgorithmType::MonteCarlo],
1597 problem_sizes: vec![3, 5],
1598 num_trials: 2,
1599 confidence_level: 0.95,
1600 classical_timeout: Duration::from_secs(10),
1601 hardware_specs: HardwareSpecs {
1602 quantum_hardware: QuantumHardwareSpecs {
1603 num_qubits: 10,
1604 gate_fidelities: HashMap::new(),
1605 coherence_times: HashMap::new(),
1606 connectivity: vec![vec![false; 10]; 10],
1607 gate_times: HashMap::new(),
1608 readout_fidelity: 0.95,
1609 },
1610 classical_hardware: ClassicalHardwareSpecs {
1611 cpu_cores: 4,
1612 cpu_frequency: 2.0,
1613 ram_size: 8_000_000_000,
1614 cache_sizes: vec![32768, 262144],
1615 gpu_specs: None,
1616 },
1617 },
1618 enable_profiling: false,
1619 save_results: false,
1620 }
1621 }
1622}