1use crate::embedding::{EmbeddingError, EmbeddingResult};
6use crate::ising::{IsingError, IsingModel};
7use crate::qubo::{QuboError, QuboFormulation};
8use crate::simulator::{AnnealingParams, AnnealingSolution};
9use scirs2_core::random::{ChaCha8Rng, Rng, SeedableRng};
10use scirs2_core::RngExt;
11use std::collections::{HashMap, HashSet, VecDeque};
12use std::time::{Duration, Instant};
13use thiserror::Error;
14
15use super::functions::{HardwareCompilationResult, PerformanceModel};
16
17#[derive(Debug, Clone)]
19pub struct CompilationMetadata {
20 pub compilation_time: Duration,
22 pub optimization_iterations: usize,
24 pub compilation_algorithm: String,
26 pub compilation_resources: HashMap<String, f64>,
28 pub warnings: Vec<String>,
30 pub optimization_trace: Vec<OptimizationStep>,
32}
33#[derive(Debug, Clone)]
35pub enum CompilationConstraint {
36 MaxCompilationTime(Duration),
38 MaxProblemSize(usize),
40 MinQualityThreshold(f64),
42 ResourceUsageLimits(HashMap<String, f64>),
44 EmbeddingConstraints(EmbeddingConstraints),
46}
47#[derive(Debug, Clone, PartialEq)]
49pub enum EmbeddingAlgorithm {
50 MinorMiner,
52 Clique,
54 Layered,
56 Spectral,
58 MLGuided,
60 Hybrid(Vec<Self>),
62}
63#[derive(Debug, Clone, PartialEq)]
65pub enum HardwareType {
66 DWaveChimera {
68 unit_cells: (usize, usize),
69 cell_size: usize,
70 },
71 DWavePegasus {
73 layers: usize,
74 nodes_per_layer: usize,
75 },
76 DWaveZephyr {
78 layers: usize,
79 tiles_per_layer: usize,
80 },
81 NeutralAtom {
83 grid_size: (usize, usize),
84 connectivity: ConnectivityPattern,
85 },
86 SuperconductingFlux {
88 topology: TopologyType,
89 num_qubits: usize,
90 },
91 Photonic {
93 mode_count: usize,
94 coupling_graph: Vec<Vec<bool>>,
95 },
96 Custom {
98 adjacency_matrix: Vec<Vec<bool>>,
99 characteristics: HardwareCharacteristics,
100 },
101 Ideal { num_qubits: usize },
103}
104#[derive(Debug, Clone)]
106pub struct ResourceUtilization {
107 pub qubit_utilization: f64,
109 pub coupling_utilization: f64,
111 pub control_resource_usage: HashMap<String, f64>,
113 pub estimated_energy: f64,
115}
116#[derive(Debug, Clone, PartialEq, Eq)]
118pub enum ProblemStructure {
119 Sparse,
121 Dense,
123 Structured,
125 Random,
127}
128#[derive(Debug, Clone, PartialEq)]
130pub enum OptimizationObjective {
131 MinimizeTime { weight: f64 },
133 MaximizeQuality { weight: f64 },
135 MinimizeEnergy { weight: f64 },
137 MaximizeSuccessProbability { weight: f64 },
139 MinimizeResourceUsage { weight: f64 },
141 MaximizeReproducibility { weight: f64 },
143}
144#[derive(Debug, Clone, PartialEq, Eq)]
146pub enum ParallelizationStrategy {
147 None,
149 ParallelEmbedding,
151 ParallelParameterSearch,
153 FullPipeline,
155}
156#[derive(Debug, Clone)]
158pub struct Chain {
159 pub logical_variable: usize,
161 pub physical_qubits: Vec<usize>,
163 pub chain_strength: f64,
165 pub connectivity: f64,
167}
168#[derive(Debug, Clone, PartialEq, Eq)]
170pub enum CouplingUtilization {
171 Conservative,
173 Aggressive,
175 Balanced,
177 Adaptive,
179}
180#[derive(Debug, Clone)]
182pub struct OptimizationStep {
183 pub description: String,
185 pub objective_value: f64,
187 pub parameters: HashMap<String, f64>,
189 pub step_time: Duration,
191}
192#[derive(Debug, Clone)]
194pub struct EmbeddingConstraints {
195 pub max_chain_length: Option<usize>,
197 pub preferred_algorithms: Vec<EmbeddingAlgorithm>,
199 pub chain_strength_optimization: bool,
201 pub quality_thresholds: EmbeddingQualityThresholds,
203}
204#[derive(Debug, Clone, PartialEq)]
206pub struct CouplingRange {
207 pub min_strength: f64,
209 pub max_strength: f64,
211 pub fidelity: f64,
213 pub crosstalk: f64,
215}
216#[derive(Debug, Clone, PartialEq, Eq)]
218pub enum QubitAllocationStrategy {
219 MinimizeCount,
221 MaximizeConnectivity,
223 LoadBalance,
225 PreferHighFidelity,
227 Custom,
229}
230#[derive(Debug, Clone)]
232pub struct PerformancePrediction {
233 pub success_probability: f64,
235 pub solution_quality: f64,
237 pub time_to_solution: f64,
239 pub confidence_intervals: HashMap<String, (f64, f64)>,
241 pub sensitivity_analysis: SensitivityAnalysis,
243}
244#[derive(Debug, Clone, PartialEq)]
246pub struct TemperatureProfile {
247 pub initial_temp: f64,
249 pub final_temp: f64,
251 pub temp_precision: f64,
253 pub cooling_rate_limits: (f64, f64),
255}
256#[derive(Debug, Clone, PartialEq)]
258pub enum HardwareConstraint {
259 MaxActiveQubits(usize),
261 MaxCouplingStrength(f64),
263 MinAnnealingTime(f64),
265 MaxAnnealingTime(f64),
267 ForbiddenPairs(Vec<(usize, usize)>),
269 CalibrationFrequency(Duration),
271 TemperatureStability(f64),
273}
274#[derive(Debug, Clone)]
276pub struct CompilationResult {
277 pub compiled_ising: IsingModel,
279 pub embedding: EmbeddingInfo,
281 pub annealing_params: AnnealingParams,
283 pub hardware_mapping: HardwareMapping,
285 pub performance_prediction: PerformancePrediction,
287 pub metadata: CompilationMetadata,
289}
290#[derive(Debug, Clone)]
292pub struct SensitivityAnalysis {
293 pub parameter_sensitivities: HashMap<String, f64>,
295 pub noise_sensitivity: f64,
297 pub temperature_sensitivity: f64,
299 pub robustness_measures: HashMap<String, f64>,
301}
302#[derive(Debug, Clone, PartialEq)]
304pub struct QubitNoise {
305 pub t1: f64,
307 pub t2: f64,
309 pub gate_fidelity: f64,
311 pub bias_noise: f64,
313 pub readout_fidelity: f64,
315}
316#[derive(Error, Debug)]
318pub enum HardwareCompilationError {
319 #[error("Ising error: {0}")]
321 IsingError(#[from] IsingError),
322 #[error("QUBO error: {0}")]
324 QuboError(#[from] QuboError),
325 #[error("Embedding error: {0}")]
327 EmbeddingError(#[from] EmbeddingError),
328 #[error("Hardware topology error: {0}")]
330 TopologyError(String),
331 #[error("Compilation error: {0}")]
333 CompilationError(String),
334 #[error("Optimization error: {0}")]
336 OptimizationError(String),
337 #[error("Hardware characterization error: {0}")]
339 CharacterizationError(String),
340 #[error("Invalid configuration: {0}")]
342 InvalidConfiguration(String),
343 #[error("Performance prediction error: {0}")]
345 PredictionError(String),
346}
347#[derive(Debug, Clone)]
349pub struct HardwareMapping {
350 pub qubit_assignments: HashMap<usize, usize>,
352 pub coupling_assignments: HashMap<(usize, usize), (usize, usize)>,
354 pub resource_utilization: ResourceUtilization,
356 pub constraints_satisfied: Vec<bool>,
358}
359#[derive(Debug, Clone)]
361pub struct PerformanceData {
362 pub success_probability: f64,
364 pub solution_quality: f64,
366 pub time_to_solution: f64,
368 pub additional_metrics: HashMap<String, f64>,
370}
371pub struct MLPerformanceModel {
373 parameters: HashMap<String, f64>,
375 pub(super) training_data: Vec<(Vec<f64>, PerformanceData)>,
377 pub(super) confidence: f64,
379}
380impl MLPerformanceModel {
381 #[must_use]
383 pub fn new() -> Self {
384 Self {
385 parameters: HashMap::new(),
386 training_data: Vec::new(),
387 confidence: 0.5,
388 }
389 }
390 pub(crate) fn extract_features(
392 &self,
393 problem: &IsingModel,
394 embedding: &EmbeddingInfo,
395 hardware: &HardwareCharacteristics,
396 ) -> Vec<f64> {
397 let mut features = Vec::new();
398 features.push(problem.num_qubits as f64);
399 features.push(embedding.chains.len() as f64);
400 features.push(embedding.quality_metrics.avg_chain_length);
401 features.push(embedding.quality_metrics.efficiency);
402 features.push(hardware.num_qubits as f64);
403 features.push(hardware.performance_metrics.success_probability);
404 features.push(hardware.performance_metrics.solution_quality);
405 let connectivity_density = hardware
406 .connectivity
407 .iter()
408 .flatten()
409 .filter(|&&connected| connected)
410 .count() as f64
411 / (hardware.num_qubits * hardware.num_qubits) as f64;
412 features.push(connectivity_density);
413 features
414 }
415}
416pub struct HardwareCompiler {
418 target_hardware: CompilationTarget,
420 config: CompilerConfig,
422 embedding_cache: HashMap<String, EmbeddingResult>,
424 performance_model: Box<dyn PerformanceModel>,
426 optimization_engine: OptimizationEngine,
428}
429impl HardwareCompiler {
430 #[must_use]
432 pub fn new(target_hardware: CompilationTarget, config: CompilerConfig) -> Self {
433 Self {
434 target_hardware,
435 config,
436 embedding_cache: HashMap::new(),
437 performance_model: Box::new(MLPerformanceModel::new()),
438 optimization_engine: OptimizationEngine::new(OptimizationConfig {
439 max_iterations: 100,
440 tolerance: 1e-6,
441 algorithm: OptimizationAlgorithm::SimulatedAnnealing,
442 objective_weights: HashMap::from([
443 ("time".to_string(), 0.3),
444 ("quality".to_string(), 0.4),
445 ("energy".to_string(), 0.2),
446 ("success_probability".to_string(), 0.1),
447 ]),
448 }),
449 }
450 }
451 pub fn compile(
453 &mut self,
454 problem: &IsingModel,
455 ) -> HardwareCompilationResult<CompilationResult> {
456 let start_time = Instant::now();
457 let problem_analysis = self.analyze_problem(problem)?;
458 let embedding_info = self.generate_embedding(problem)?;
459 let annealing_params = self.optimize_annealing_parameters(problem, &embedding_info)?;
460 let hardware_mapping = self.create_hardware_mapping(problem, &embedding_info)?;
461 let performance_prediction = self.performance_model.predict_performance(
462 problem,
463 &embedding_info,
464 &self.target_hardware.characteristics,
465 )?;
466 let compiled_ising = self.apply_embedding_to_problem(problem, &embedding_info)?;
467 let compilation_time = start_time.elapsed();
468 Ok(CompilationResult {
469 compiled_ising,
470 embedding: embedding_info,
471 annealing_params,
472 hardware_mapping,
473 performance_prediction,
474 metadata: CompilationMetadata {
475 compilation_time,
476 optimization_iterations: self.optimization_engine.state.iteration,
477 compilation_algorithm: "HardwareAwareCompiler".to_string(),
478 compilation_resources: HashMap::from([
479 ("memory_usage".to_string(), 100.0),
480 ("cpu_time".to_string(), compilation_time.as_secs_f64()),
481 ]),
482 warnings: Vec::new(),
483 optimization_trace: self.optimization_engine.history.clone(),
484 },
485 })
486 }
487 pub(crate) fn analyze_problem(
489 &self,
490 problem: &IsingModel,
491 ) -> HardwareCompilationResult<ProblemAnalysis> {
492 Ok(ProblemAnalysis {
493 num_variables: problem.num_qubits,
494 connectivity_density: self.calculate_connectivity_density(problem),
495 coupling_distribution: self.analyze_coupling_distribution(problem),
496 problem_structure: self.detect_problem_structure(problem),
497 complexity_estimate: self.estimate_complexity(problem),
498 })
499 }
500 fn calculate_connectivity_density(&self, problem: &IsingModel) -> f64 {
502 let mut num_couplings = 0;
503 for i in 0..problem.num_qubits {
504 for j in (i + 1)..problem.num_qubits {
505 if problem.get_coupling(i, j).unwrap_or(0.0).abs() > 1e-10 {
506 num_couplings += 1;
507 }
508 }
509 }
510 let max_couplings = problem.num_qubits * (problem.num_qubits - 1) / 2;
511 f64::from(num_couplings) / max_couplings as f64
512 }
513 fn analyze_coupling_distribution(&self, problem: &IsingModel) -> CouplingDistribution {
515 let mut couplings = Vec::new();
516 for i in 0..problem.num_qubits {
517 for j in (i + 1)..problem.num_qubits {
518 let coupling = problem.get_coupling(i, j).unwrap_or(0.0);
519 if coupling.abs() > 1e-10 {
520 couplings.push(coupling.abs());
521 }
522 }
523 }
524 if couplings.is_empty() {
525 return CouplingDistribution {
526 mean: 0.0,
527 std_dev: 0.0,
528 min: 0.0,
529 max: 0.0,
530 distribution_type: DistributionType::Uniform,
531 };
532 }
533 couplings.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
534 let mean = couplings.iter().sum::<f64>() / couplings.len() as f64;
535 let variance =
536 couplings.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / couplings.len() as f64;
537 CouplingDistribution {
538 mean,
539 std_dev: variance.sqrt(),
540 min: couplings[0],
541 max: couplings[couplings.len() - 1],
542 distribution_type: DistributionType::Normal,
543 }
544 }
545 fn detect_problem_structure(&self, problem: &IsingModel) -> ProblemStructure {
547 let connectivity_density = self.calculate_connectivity_density(problem);
548 if connectivity_density < 0.1 {
549 ProblemStructure::Sparse
550 } else if connectivity_density > 0.7 {
551 ProblemStructure::Dense
552 } else {
553 ProblemStructure::Structured
554 }
555 }
556 fn estimate_complexity(&self, problem: &IsingModel) -> f64 {
558 let size_factor = (problem.num_qubits as f64).ln();
559 let connectivity_factor = self.calculate_connectivity_density(problem);
560 size_factor * (1.0 + connectivity_factor)
561 }
562 fn generate_embedding(
564 &mut self,
565 problem: &IsingModel,
566 ) -> HardwareCompilationResult<EmbeddingInfo> {
567 let cache_key = self.generate_cache_key(problem);
568 if self.config.cache_embeddings {
569 if let Some(cached_result) = self.embedding_cache.get(&cache_key) {
570 return Ok(self.convert_embedding_result_to_info(cached_result));
571 }
572 }
573 let embedding_result = self.find_best_embedding(problem)?;
574 if self.config.cache_embeddings {
575 self.embedding_cache
576 .insert(cache_key, embedding_result.clone());
577 }
578 Ok(self.convert_embedding_result_to_info(&embedding_result))
579 }
580 fn find_best_embedding(
582 &self,
583 problem: &IsingModel,
584 ) -> HardwareCompilationResult<EmbeddingResult> {
585 let mut variable_mapping = HashMap::new();
586 let mut chains = Vec::new();
587 for i in 0..problem.num_qubits {
588 variable_mapping.insert(i, vec![i]);
589 chains.push(Chain {
590 logical_variable: i,
591 physical_qubits: vec![i],
592 chain_strength: 1.0,
593 connectivity: 1.0,
594 });
595 }
596 let quality_metrics = EmbeddingQualityMetrics {
597 avg_chain_length: 1.0,
598 max_chain_length: 1,
599 efficiency: 1.0,
600 chain_balance: 1.0,
601 connectivity_utilization: self.calculate_connectivity_density(problem),
602 };
603 Ok(EmbeddingResult {
604 embedding: variable_mapping.clone(),
605 chain_strength: 1.0,
606 success: true,
607 error_message: None,
608 })
609 }
610 fn convert_embedding_result_to_info(&self, result: &EmbeddingResult) -> EmbeddingInfo {
612 let mut chains = Vec::new();
613 for (logical, physical) in &result.embedding {
614 chains.push(Chain {
615 logical_variable: *logical,
616 physical_qubits: physical.clone(),
617 chain_strength: result.chain_strength,
618 connectivity: 1.0,
619 });
620 }
621 EmbeddingInfo {
622 variable_mapping: result.embedding.clone(),
623 chains,
624 quality_metrics: EmbeddingQualityMetrics {
625 avg_chain_length: 1.0,
626 max_chain_length: 1,
627 efficiency: 1.0,
628 chain_balance: 1.0,
629 connectivity_utilization: 0.5,
630 },
631 algorithm_used: EmbeddingAlgorithm::MinorMiner,
632 }
633 }
634 fn generate_cache_key(&self, problem: &IsingModel) -> String {
636 format!(
637 "{}_{:.6}",
638 problem.num_qubits,
639 self.calculate_connectivity_density(problem)
640 )
641 }
642 fn optimize_annealing_parameters(
644 &mut self,
645 problem: &IsingModel,
646 embedding: &EmbeddingInfo,
647 ) -> HardwareCompilationResult<AnnealingParams> {
648 let objective_fn = |params: &HashMap<String, f64>| -> f64 {
649 let mut score = 0.0;
650 for (key, &value) in params {
651 match key.as_str() {
652 "chain_strength" => {
653 if value < 0.1 || value > 10.0 {
654 score += 1000.0;
655 }
656 }
657 "annealing_time" => {
658 if value < 1.0 || value > 1000.0 {
659 score += 1000.0;
660 }
661 }
662 _ => {}
663 }
664 }
665 score += params.values().map(|v| v.ln().abs()).sum::<f64>();
666 score
667 };
668 let optimized_params = self.optimization_engine.optimize(objective_fn)?;
669 Ok(AnnealingParams {
670 num_sweeps: *optimized_params.get("num_reads").unwrap_or(&1000.0) as usize,
671 num_repetitions: 1,
672 initial_temperature: optimized_params
673 .get("temperature")
674 .unwrap_or(&1.0)
675 .max(0.01),
676 final_temperature: 0.01,
677 timeout: Some(optimized_params.get("annealing_time").unwrap_or(&20.0) / 1000.0),
678 ..Default::default()
679 })
680 }
681 fn create_hardware_mapping(
683 &self,
684 problem: &IsingModel,
685 embedding: &EmbeddingInfo,
686 ) -> HardwareCompilationResult<HardwareMapping> {
687 let mut qubit_assignments = HashMap::new();
688 let mut coupling_assignments = HashMap::new();
689 for (logical, physical_vec) in &embedding.variable_mapping {
690 if let Some(&first_physical) = physical_vec.first() {
691 qubit_assignments.insert(*logical, first_physical);
692 }
693 }
694 for i in 0..problem.num_qubits {
695 for j in (i + 1)..problem.num_qubits {
696 if problem.get_coupling(i, j).unwrap_or(0.0).abs() > 1e-10 {
697 if let (Some(&phys_i), Some(&phys_j)) =
698 (qubit_assignments.get(&i), qubit_assignments.get(&j))
699 {
700 coupling_assignments.insert((i, j), (phys_i, phys_j));
701 }
702 }
703 }
704 }
705 let resource_utilization = ResourceUtilization {
706 qubit_utilization: problem.num_qubits as f64
707 / self.target_hardware.characteristics.num_qubits as f64,
708 coupling_utilization: coupling_assignments.len() as f64 / 100.0,
709 control_resource_usage: HashMap::from([
710 ("memory".to_string(), 0.1),
711 ("control_lines".to_string(), 0.2),
712 ]),
713 estimated_energy: problem.num_qubits as f64 * 0.001,
714 };
715 Ok(HardwareMapping {
716 qubit_assignments,
717 coupling_assignments,
718 resource_utilization,
719 constraints_satisfied: vec![true; self.target_hardware.constraints.len()],
720 })
721 }
722 fn apply_embedding_to_problem(
724 &self,
725 problem: &IsingModel,
726 embedding: &EmbeddingInfo,
727 ) -> HardwareCompilationResult<IsingModel> {
728 let mut compiled = IsingModel::new(problem.num_qubits);
729 for i in 0..problem.num_qubits {
730 compiled.set_bias(i, problem.get_bias(i).unwrap_or(0.0))?;
731 }
732 for i in 0..problem.num_qubits {
733 for j in (i + 1)..problem.num_qubits {
734 let coupling = problem.get_coupling(i, j).unwrap_or(0.0);
735 if coupling.abs() > 1e-10 {
736 compiled.set_coupling(i, j, coupling)?;
737 }
738 }
739 }
740 Ok(compiled)
741 }
742}
743pub struct OptimizationEngine {
745 state: OptimizationState,
747 history: Vec<OptimizationStep>,
749 config: OptimizationConfig,
751}
752impl OptimizationEngine {
753 #[must_use]
755 pub fn new(config: OptimizationConfig) -> Self {
756 Self {
757 state: OptimizationState {
758 objective_value: f64::INFINITY,
759 parameters: HashMap::new(),
760 iteration: 0,
761 converged: false,
762 },
763 history: Vec::new(),
764 config,
765 }
766 }
767 pub fn optimize<F>(
769 &mut self,
770 objective_function: F,
771 ) -> HardwareCompilationResult<HashMap<String, f64>>
772 where
773 F: Fn(&HashMap<String, f64>) -> f64,
774 {
775 let start_time = Instant::now();
776 let mut current_params = HashMap::from([
777 ("chain_strength".to_string(), 1.0),
778 ("annealing_time".to_string(), 20.0),
779 ("temperature".to_string(), 0.01),
780 ("num_reads".to_string(), 1000.0),
781 ]);
782 let mut best_value = objective_function(¤t_params);
783 let mut best_params = current_params.clone();
784 for iteration in 0..self.config.max_iterations {
785 let mut candidate_params = current_params.clone();
786 let mut rng = ChaCha8Rng::seed_from_u64(iteration as u64);
787 for (key, value) in &mut candidate_params {
788 let perturbation = rng.random_range(-0.1..0.1) * *value;
789 *value = (*value + perturbation).max(0.01);
790 }
791 let candidate_value = objective_function(&candidate_params);
792 if candidate_value < best_value {
793 best_value = candidate_value;
794 best_params.clone_from(&candidate_params);
795 current_params.clone_from(&candidate_params);
796 }
797 self.history.push(OptimizationStep {
798 description: format!("Iteration {iteration}"),
799 objective_value: candidate_value,
800 parameters: candidate_params,
801 step_time: start_time.elapsed() / (iteration + 1) as u32,
802 });
803 if iteration > 10
804 && self.history[iteration].objective_value
805 - self.history[iteration - 10].objective_value
806 < self.config.tolerance
807 {
808 self.state.converged = true;
809 break;
810 }
811 }
812 self.state.parameters = best_params.clone();
813 self.state.objective_value = best_value;
814 Ok(best_params)
815 }
816}
817#[derive(Debug, Clone)]
819pub struct OptimizationConfig {
820 pub max_iterations: usize,
822 pub tolerance: f64,
824 pub algorithm: OptimizationAlgorithm,
826 pub objective_weights: HashMap<String, f64>,
828}
829#[derive(Debug, Clone)]
831pub struct EmbeddingQualityMetrics {
832 pub avg_chain_length: f64,
834 pub max_chain_length: usize,
836 pub efficiency: f64,
838 pub chain_balance: f64,
840 pub connectivity_utilization: f64,
842}
843#[derive(Debug, Clone, PartialEq, Eq)]
845pub enum DistributionType {
846 Uniform,
848 Normal,
850 Exponential,
852 PowerLaw,
854}
855#[derive(Debug, Clone, PartialEq)]
857pub enum TopologyType {
858 Grid2D { rows: usize, cols: usize },
860 Grid3D { x: usize, y: usize, z: usize },
862 SmallWorld { degree: usize, rewiring_prob: f64 },
864 ScaleFree {
866 num_nodes: usize,
867 attachment_param: usize,
868 },
869 Complete,
871 Tree {
873 branching_factor: usize,
874 depth: usize,
875 },
876}
877#[derive(Debug, Clone)]
879pub struct ResourceAllocation {
880 pub qubit_allocation: QubitAllocationStrategy,
882 pub coupling_utilization: CouplingUtilization,
884 pub parallelization: ParallelizationStrategy,
886}
887#[derive(Debug, Clone)]
889pub struct ProblemAnalysis {
890 pub num_variables: usize,
892 pub connectivity_density: f64,
894 pub coupling_distribution: CouplingDistribution,
896 pub problem_structure: ProblemStructure,
898 pub complexity_estimate: f64,
900}
901#[derive(Debug, Clone)]
903pub struct CouplingDistribution {
904 pub mean: f64,
906 pub std_dev: f64,
908 pub min: f64,
910 pub max: f64,
912 pub distribution_type: DistributionType,
914}
915#[derive(Debug, Clone)]
917pub struct EmbeddingQualityThresholds {
918 pub max_avg_chain_length: f64,
920 pub min_efficiency: f64,
922 pub max_overhead: f64,
924}
925#[derive(Debug, Clone, PartialEq)]
927pub struct ControlPrecision {
928 pub bias_precision: usize,
930 pub coupling_precision: usize,
932 pub timing_precision: f64,
934}
935#[derive(Debug, Clone, PartialEq)]
937pub struct PerformanceMetrics {
938 pub success_probability: f64,
940 pub solution_quality: f64,
942 pub time_to_solution: Vec<f64>,
944 pub energy_resolution: f64,
946 pub reproducibility: f64,
948}
949#[derive(Debug, Clone)]
951pub struct OptimizationState {
952 pub objective_value: f64,
954 pub parameters: HashMap<String, f64>,
956 pub iteration: usize,
958 pub converged: bool,
960}
961#[derive(Debug, Clone, PartialEq, Eq)]
963pub enum OptimizationAlgorithm {
964 SimulatedAnnealing,
966 GeneticAlgorithm,
968 ParticleSwarm,
970 BayesianOptimization,
972 NSGAII,
974}
975#[derive(Debug, Clone)]
977pub struct EmbeddingInfo {
978 pub variable_mapping: HashMap<usize, Vec<usize>>,
980 pub chains: Vec<Chain>,
982 pub quality_metrics: EmbeddingQualityMetrics,
984 pub algorithm_used: EmbeddingAlgorithm,
986}
987#[derive(Debug, Clone)]
989pub struct CompilerConfig {
990 pub aggressive_optimization: bool,
992 pub cache_embeddings: bool,
994 pub parallel_compilation: bool,
996 pub max_compilation_time: Duration,
998 pub optimization_tolerance: f64,
1000 pub seed: Option<u64>,
1002}
1003#[derive(Debug, Clone)]
1005pub struct CompilationTarget {
1006 pub hardware_type: HardwareType,
1008 pub characteristics: HardwareCharacteristics,
1010 pub objectives: Vec<OptimizationObjective>,
1012 pub constraints: Vec<CompilationConstraint>,
1014 pub resource_allocation: ResourceAllocation,
1016}
1017#[derive(Debug, Clone, PartialEq, Eq)]
1019pub enum ConnectivityPattern {
1020 NearestNeighbor,
1022 AllToAll,
1024 KingsGraph,
1026 Triangular,
1028 Custom(Vec<Vec<bool>>),
1030}
1031#[derive(Debug, Clone, PartialEq)]
1033pub struct HardwareCharacteristics {
1034 pub num_qubits: usize,
1036 pub connectivity: Vec<Vec<bool>>,
1038 pub qubit_noise: Vec<QubitNoise>,
1040 pub coupling_ranges: Vec<Vec<CouplingRange>>,
1042 pub annealing_time_range: (f64, f64),
1044 pub temperature_characteristics: TemperatureProfile,
1046 pub control_precision: ControlPrecision,
1048 pub constraints: Vec<HardwareConstraint>,
1050 pub performance_metrics: PerformanceMetrics,
1052}