quantrs2_device/compiler_passes/
test_utils.rs

1//! Test utilities and helper functions
2
3use std::collections::HashSet;
4
5use super::config::*;
6use super::types::*;
7use crate::backend_traits::BackendCapabilities;
8
9/// Utility functions for creating test configurations
10pub fn create_test_ibm_target() -> CompilationTarget {
11    CompilationTarget::IBMQuantum {
12        backend_name: "test_backend".to_string(),
13        coupling_map: vec![(0, 1), (1, 2), (2, 3)],
14        native_gates: ["rz", "sx", "cx"].iter().map(|s| s.to_string()).collect(),
15        basis_gates: vec!["rz".to_string(), "sx".to_string(), "cx".to_string()],
16        max_shots: 1024,
17        simulator: true,
18    }
19}
20
21pub fn create_test_scirs2_config() -> SciRS2Config {
22    SciRS2Config {
23        enable_graph_optimization: true,
24        enable_statistical_analysis: true,
25        enable_advanced_optimization: false, // Disable for testing
26        enable_linalg_optimization: true,
27        optimization_method: SciRS2OptimizationMethod::NelderMead,
28        significance_threshold: 0.01,
29    }
30}
31
32pub fn create_test_compiler_config() -> CompilerConfig {
33    CompilerConfig {
34        enable_gate_synthesis: true,
35        enable_error_optimization: true,
36        enable_timing_optimization: true,
37        enable_crosstalk_mitigation: false, // Disable for simpler testing
38        enable_resource_optimization: true,
39        max_iterations: 100,
40        tolerance: 1e-6,
41        target: create_test_ibm_target(),
42        objectives: vec![OptimizationObjective::MinimizeError],
43        constraints: HardwareConstraints {
44            max_depth: Some(100),
45            max_gates: Some(1000),
46            max_execution_time: Some(10000.0),
47            min_fidelity_threshold: 0.95,
48            max_error_rate: 0.05,
49            forbidden_pairs: HashSet::new(),
50            min_idle_time: 50.0,
51        },
52        scirs2_config: create_test_scirs2_config(),
53        parallel_config: ParallelConfig {
54            enable_parallel_passes: false, // Disable for deterministic testing
55            num_threads: 1,
56            chunk_size: 10,
57            enable_simd: false,
58        },
59        adaptive_config: None,
60        performance_monitoring: true,
61        analysis_depth: AnalysisDepth::Basic,
62    }
63}
64
65/// Helper function to create test grid topology
66pub fn create_test_grid_topology() -> GridTopology {
67    GridTopology {
68        rows: 2,
69        cols: 2,
70        connectivity: ConnectivityPattern::Square,
71    }
72}
73
74/// Helper function to create test rigetti lattice
75pub fn create_test_rigetti_lattice() -> RigettiLattice {
76    RigettiLattice::Custom(vec![(0, 1), (1, 2), (2, 3)])
77}
78
79/// Helper function to create test performance prediction
80pub fn create_test_performance_prediction() -> PerformancePrediction {
81    PerformancePrediction {
82        execution_time: std::time::Duration::from_micros(500),
83        fidelity: 0.92,
84        error_rate: 0.08,
85        success_probability: 0.85,
86        confidence_interval: (0.80, 0.90),
87        model: "Test Model".to_string(),
88    }
89}
90
91/// Helper function to create test advanced metrics
92pub fn create_test_advanced_metrics() -> AdvancedMetrics {
93    AdvancedMetrics {
94        quantum_volume: 32,
95        expressivity: 0.75,
96        entanglement_entropy: 1.5,
97        complexity_score: 0.65,
98        resource_efficiency: 0.85,
99        error_resilience: 0.88,
100        compatibility_score: 0.92,
101    }
102}
103
104/// Helper function to create test optimization stats
105pub fn create_test_optimization_stats() -> OptimizationStats {
106    OptimizationStats {
107        original_gate_count: 20,
108        optimized_gate_count: 15,
109        original_depth: 10,
110        optimized_depth: 8,
111        error_improvement: 0.12,
112        fidelity_improvement: 0.08,
113        efficiency_gain: 0.25,
114        overall_improvement: 0.15,
115    }
116}
117
118/// Helper function to create test hardware allocation
119pub fn create_test_hardware_allocation() -> HardwareAllocation {
120    let mut qubit_mapping = std::collections::HashMap::new();
121    qubit_mapping.insert(0, 0);
122    qubit_mapping.insert(1, 1);
123    qubit_mapping.insert(2, 2);
124    qubit_mapping.insert(3, 3);
125
126    HardwareAllocation {
127        qubit_mapping,
128        allocated_qubits: vec![0, 1, 2, 3],
129        resource_utilization: 0.75,
130        strategy: AllocationStrategy::OptimalMapping,
131        quality_score: 0.90,
132    }
133}
134
135/// Helper function to create test verification results
136pub fn create_test_verification_results() -> VerificationResults {
137    VerificationResults {
138        equivalence_verified: true,
139        constraints_satisfied: true,
140        semantic_correctness: true,
141        verification_time: std::time::Duration::from_millis(50),
142        verification_report: "All verifications passed".to_string(),
143    }
144}
145
146/// Helper function to create test pass info
147pub fn create_test_pass_info(name: &str) -> PassInfo {
148    let mut metrics = std::collections::HashMap::new();
149    metrics.insert("improvement".to_string(), 0.1);
150    metrics.insert("efficiency".to_string(), 0.85);
151
152    PassInfo {
153        name: name.to_string(),
154        execution_time: std::time::Duration::from_millis(100),
155        gates_modified: 5,
156        improvement: 0.1,
157        metrics,
158        success: true,
159        error_message: None,
160    }
161}
162
163/// Helper function to create test compilation result
164pub fn create_test_compilation_result() -> CompilationResult {
165    CompilationResult {
166        original_circuit: "Original Circuit".to_string(),
167        optimized_circuit: "Optimized Circuit".to_string(),
168        optimization_stats: create_test_optimization_stats(),
169        applied_passes: vec![
170            create_test_pass_info("gate_synthesis"),
171            create_test_pass_info("error_optimization"),
172        ],
173        hardware_allocation: create_test_hardware_allocation(),
174        predicted_performance: create_test_performance_prediction(),
175        compilation_time: std::time::Duration::from_millis(500),
176        advanced_metrics: create_test_advanced_metrics(),
177        optimization_history: vec![],
178        platform_specific: PlatformSpecificResults {
179            platform: "Test Platform".to_string(),
180            metrics: std::collections::HashMap::new(),
181            transformations: vec!["Test Transformation".to_string()],
182        },
183        verification_results: create_test_verification_results(),
184    }
185}
186
187/// Helper trait for creating mock results
188pub trait MockResults {
189    /// Create mock optimization result
190    fn create_mock_optimization_result() -> AdvancedOptimizationResult {
191        AdvancedOptimizationResult {
192            method: "Mock".to_string(),
193            converged: true,
194            objective_value: 0.95,
195            iterations: 50,
196            parameter_evolution: vec![scirs2_core::ndarray::Array1::zeros(4)],
197            success: true,
198            x: scirs2_core::ndarray::Array1::zeros(4),
199            improvement: 0.15,
200        }
201    }
202
203    /// Create mock linalg result
204    fn create_mock_linalg_result() -> LinalgOptimizationResult {
205        LinalgOptimizationResult {
206            decomposition_improvements: std::collections::HashMap::new(),
207            stability_metrics: NumericalStabilityMetrics {
208                condition_number: 5.0,
209                numerical_rank: 4,
210                spectral_radius: 1.1,
211            },
212            eigenvalue_analysis: EigenvalueAnalysis {
213                eigenvalue_distribution: vec![],
214                spectral_gap: 0.2,
215                entanglement_spectrum: vec![],
216            },
217        }
218    }
219}
220
221/// Test data generator
222pub struct TestDataGenerator;
223
224impl TestDataGenerator {
225    /// Generate test circuit metrics
226    pub fn generate_circuit_metrics() -> std::collections::HashMap<String, f64> {
227        let mut metrics = std::collections::HashMap::new();
228        metrics.insert("gate_count".to_string(), 15.0);
229        metrics.insert("depth".to_string(), 8.0);
230        metrics.insert("fidelity".to_string(), 0.92);
231        metrics.insert("error_rate".to_string(), 0.08);
232        metrics
233    }
234
235    /// Generate test objective values
236    pub fn generate_objective_values() -> Vec<f64> {
237        vec![0.95, 0.88, 0.91, 0.87]
238    }
239
240    /// Generate test performance data
241    pub fn generate_performance_data() -> Vec<f64> {
242        vec![0.92, 0.89, 0.95, 0.87, 0.93, 0.91, 0.88, 0.94]
243    }
244}
245
246/// Configuration builder for tests
247pub struct TestConfigBuilder {
248    config: CompilerConfig,
249}
250
251impl TestConfigBuilder {
252    /// Create new test config builder
253    pub fn new() -> Self {
254        Self {
255            config: create_test_compiler_config(),
256        }
257    }
258
259    /// Enable specific optimization
260    pub fn enable_optimization(mut self, optimization: &str, enabled: bool) -> Self {
261        match optimization {
262            "gate_synthesis" => self.config.enable_gate_synthesis = enabled,
263            "error_optimization" => self.config.enable_error_optimization = enabled,
264            "timing_optimization" => self.config.enable_timing_optimization = enabled,
265            "crosstalk_mitigation" => self.config.enable_crosstalk_mitigation = enabled,
266            "resource_optimization" => self.config.enable_resource_optimization = enabled,
267            _ => {}
268        }
269        self
270    }
271
272    /// Set target platform
273    pub fn with_target(mut self, target: CompilationTarget) -> Self {
274        self.config.target = target;
275        self
276    }
277
278    /// Set analysis depth
279    pub fn with_analysis_depth(mut self, depth: AnalysisDepth) -> Self {
280        self.config.analysis_depth = depth;
281        self
282    }
283
284    /// Build the configuration
285    pub fn build(self) -> CompilerConfig {
286        self.config
287    }
288}
289
290impl Default for TestConfigBuilder {
291    fn default() -> Self {
292        Self::new()
293    }
294}