QuantumCircuit

Struct QuantumCircuit 

Source
pub struct QuantumCircuit {
    pub gates: Vec<QuantumGate>,
    pub qubits: usize,
}

Fields§

§gates: Vec<QuantumGate>§qubits: usize

Implementations§

Source§

impl QuantumCircuit

Source

pub fn num_qubits(&self) -> usize

Examples found in repository?
examples/advanced_error_mitigation_demo.rs (line 59)
18fn main() -> Result<()> {
19    println!("=== Advanced Quantum ML Error Mitigation Demo ===\n");
20
21    // Step 1: Initialize noise model and calibration data
22    println!("1. Setting up noise model and calibration data...");
23
24    let noise_model = create_realistic_noise_model()?;
25    println!(
26        "   - Noise model configured with {} gate types",
27        noise_model.gate_errors.len()
28    );
29    println!(
30        "   - Average gate error rate: {:.4}",
31        calculate_average_error_rate(&noise_model)
32    );
33    println!(
34        "   - Measurement fidelity: {:.3}",
35        noise_model.measurement_errors.readout_fidelity
36    );
37
38    // Step 2: Create different mitigation strategies
39    println!("\n2. Creating error mitigation strategies...");
40
41    let strategies = create_mitigation_strategies()?;
42    println!(
43        "   - Created {} different mitigation strategies",
44        strategies.len()
45    );
46
47    for (i, strategy) in strategies.iter().enumerate() {
48        println!("   {}. {}", i + 1, get_strategy_name(strategy));
49    }
50
51    // Step 3: Initialize quantum ML circuit for testing
52    println!("\n3. Initializing quantum ML circuit...");
53
54    let test_circuit = create_test_qml_circuit(4, 3)?; // 4 qubits, 3 layers
55    let initial_parameters = Array1::from_vec(vec![0.1, 0.2, 0.3, 0.4, 0.5, 0.6]);
56
57    println!(
58        "   - Circuit: {} qubits, {} parameters",
59        test_circuit.num_qubits(),
60        initial_parameters.len()
61    );
62    println!(
63        "   - Circuit depth: approximately {} gates",
64        estimate_circuit_depth(&test_circuit)
65    );
66
67    // Step 4: Simulate noisy measurements
68    println!("\n4. Simulating noisy quantum measurements...");
69
70    let noisy_measurements = simulate_noisy_measurements(&test_circuit, &noise_model, 1000)?;
71    let noisy_gradients =
72        simulate_noisy_gradients(&test_circuit, &initial_parameters, &noise_model)?;
73
74    println!(
75        "   - Generated {} measurement shots",
76        noisy_measurements.nrows()
77    );
78    println!(
79        "   - Noise level in measurements: {:.3}",
80        assess_noise_level(&noisy_measurements)
81    );
82    println!(
83        "   - Gradient noise standard deviation: {:.4}",
84        noisy_gradients.std(0.0)
85    );
86
87    // Step 5: Apply different mitigation strategies
88    println!("\n5. Applying different error mitigation strategies...");
89
90    let mut mitigation_results = Vec::new();
91
92    for (strategy_idx, strategy) in strategies.iter().enumerate() {
93        println!(
94            "   Testing strategy {}: {}",
95            strategy_idx + 1,
96            get_strategy_name(strategy)
97        );
98
99        let mut mitigator = QuantumMLErrorMitigator::new(strategy.clone(), noise_model.clone())?;
100
101        let mitigated_data = mitigator.mitigate_training_errors(
102            &test_circuit,
103            &initial_parameters,
104            &noisy_measurements,
105            &noisy_gradients,
106        )?;
107
108        let improvement = calculate_improvement(&noisy_measurements, &mitigated_data.measurements)?;
109        println!(
110            "     - Measurement improvement: {:.1}%",
111            improvement * 100.0
112        );
113        println!(
114            "     - Confidence score: {:.3}",
115            mitigated_data.confidence_scores.mean().unwrap()
116        );
117        println!(
118            "     - Mitigation overhead: {:.1}%",
119            mitigated_data.mitigation_overhead * 100.0
120        );
121
122        mitigation_results.push((strategy_idx, improvement, mitigated_data));
123    }
124
125    // Step 6: Compare mitigation effectiveness
126    println!("\n6. Comparing mitigation effectiveness...");
127
128    let mut sorted_results = mitigation_results.clone();
129    sorted_results.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap());
130
131    println!("   Ranking by improvement:");
132    for (rank, (strategy_idx, improvement, _)) in sorted_results.iter().enumerate() {
133        println!(
134            "   {}. {}: {:.1}% improvement",
135            rank + 1,
136            get_strategy_name(&strategies[*strategy_idx]),
137            improvement * 100.0
138        );
139    }
140
141    // Step 7: Demonstrate adaptive mitigation
142    println!("\n7. Demonstrating adaptive error mitigation...");
143
144    let adaptive_strategy = MitigationStrategy::AdaptiveMultiStrategy {
145        strategies: strategies.clone(),
146        selection_policy: create_smart_selection_policy()?,
147        performance_tracker: create_performance_tracker()?,
148    };
149
150    let mut adaptive_mitigator =
151        QuantumMLErrorMitigator::new(adaptive_strategy, noise_model.clone())?;
152
153    // Simulate training loop with adaptive mitigation
154    println!("   Simulating training with adaptive mitigation:");
155    let num_training_steps = 10;
156    let mut training_history = Vec::new();
157
158    for step in 0..num_training_steps {
159        // Simulate changing noise conditions
160        let dynamic_noise = simulate_dynamic_noise(&noise_model, step)?;
161        adaptive_mitigator.noise_model = dynamic_noise;
162
163        let step_measurements = simulate_training_step_measurements(&test_circuit, step)?;
164        let step_gradients = simulate_training_step_gradients(&test_circuit, step)?;
165
166        let mitigated_step = adaptive_mitigator.mitigate_training_errors(
167            &test_circuit,
168            &initial_parameters,
169            &step_measurements,
170            &step_gradients,
171        )?;
172
173        let step_improvement =
174            calculate_improvement(&step_measurements, &mitigated_step.measurements)?;
175        training_history.push(step_improvement);
176
177        if step % 3 == 0 {
178            println!(
179                "     Step {}: {:.1}% improvement, confidence: {:.3}",
180                step + 1,
181                step_improvement * 100.0,
182                mitigated_step.confidence_scores.mean().unwrap()
183            );
184        }
185    }
186
187    let avg_adaptive_improvement =
188        training_history.iter().sum::<f64>() / training_history.len() as f64;
189    println!(
190        "   Average adaptive improvement: {:.1}%",
191        avg_adaptive_improvement * 100.0
192    );
193
194    // Step 8: Demonstrate specialized mitigation techniques
195    println!("\n8. Demonstrating specialized mitigation techniques...");
196
197    // Zero Noise Extrapolation
198    let zne_demo = demonstrate_zne_mitigation(&test_circuit, &noise_model)?;
199    println!("   Zero Noise Extrapolation:");
200    println!(
201        "     - Extrapolated fidelity: {:.4}",
202        zne_demo.extrapolated_fidelity
203    );
204    println!(
205        "     - Confidence interval: [{:.4}, {:.4}]",
206        zne_demo.confidence_interval.0, zne_demo.confidence_interval.1
207    );
208
209    // Readout Error Mitigation
210    let readout_demo = demonstrate_readout_mitigation(&test_circuit, &noise_model)?;
211    println!("   Readout Error Mitigation:");
212    println!(
213        "     - Correction accuracy: {:.1}%",
214        readout_demo.correction_accuracy * 100.0
215    );
216    println!(
217        "     - Assignment matrix condition number: {:.2}",
218        readout_demo.condition_number
219    );
220
221    // Clifford Data Regression
222    let cdr_demo = demonstrate_cdr_mitigation(&test_circuit, &noise_model)?;
223    println!("   Clifford Data Regression:");
224    println!("     - Regression R²: {:.3}", cdr_demo.r_squared);
225    println!(
226        "     - Prediction accuracy: {:.1}%",
227        cdr_demo.prediction_accuracy * 100.0
228    );
229
230    // Virtual Distillation
231    let vd_demo = demonstrate_virtual_distillation(&test_circuit, &noise_model)?;
232    println!("   Virtual Distillation:");
233    println!(
234        "     - Distillation fidelity: {:.4}",
235        vd_demo.distillation_fidelity
236    );
237    println!(
238        "     - Resource overhead: {:.1}x",
239        vd_demo.resource_overhead
240    );
241
242    // Step 9: ML-based error mitigation
243    println!("\n9. Demonstrating ML-based error mitigation...");
244
245    let ml_mitigation_demo = demonstrate_ml_mitigation(&test_circuit, &noise_model)?;
246    println!("   Machine Learning-based Mitigation:");
247    println!(
248        "     - Neural network accuracy: {:.1}%",
249        ml_mitigation_demo.nn_accuracy * 100.0
250    );
251    println!(
252        "     - Noise prediction MSE: {:.6}",
253        ml_mitigation_demo.prediction_mse
254    );
255    println!(
256        "     - Correction effectiveness: {:.1}%",
257        ml_mitigation_demo.correction_effectiveness * 100.0
258    );
259
260    // Step 10: Real-time adaptive mitigation
261    println!("\n10. Real-time adaptive mitigation simulation...");
262
263    let realtime_results = simulate_realtime_mitigation(&test_circuit, &noise_model)?;
264    println!("    Real-time Adaptation Results:");
265    println!(
266        "    - Response time: {:.1} ms",
267        realtime_results.response_time_ms
268    );
269    println!(
270        "    - Adaptation accuracy: {:.1}%",
271        realtime_results.adaptation_accuracy * 100.0
272    );
273    println!(
274        "    - Overall performance gain: {:.1}%",
275        realtime_results.performance_gain * 100.0
276    );
277
278    // Step 11: Error mitigation for inference
279    println!("\n11. Error mitigation for quantum ML inference...");
280
281    let inference_measurements = simulate_inference_measurements(&test_circuit, 500)?;
282
283    let best_strategy = &strategies[sorted_results[0].0];
284    let mut inference_mitigator =
285        QuantumMLErrorMitigator::new(best_strategy.clone(), noise_model.clone())?;
286
287    let mitigated_inference =
288        inference_mitigator.mitigate_inference_errors(&test_circuit, &inference_measurements)?;
289
290    println!("    Inference Mitigation Results:");
291    println!(
292        "    - Uncertainty reduction: {:.1}%",
293        (1.0 - mitigated_inference.uncertainty.mean().unwrap()) * 100.0
294    );
295    println!(
296        "    - Reliability score: {:.3}",
297        mitigated_inference.reliability_score
298    );
299    println!(
300        "    - Prediction confidence: {:.1}%",
301        calculate_prediction_confidence(&mitigated_inference.measurements) * 100.0
302    );
303
304    // Step 12: Performance and resource analysis
305    println!("\n12. Performance and resource analysis...");
306
307    let resource_analysis = analyze_mitigation_resources(&mitigation_results)?;
308    println!("    Resource Analysis:");
309    println!(
310        "    - Average computational overhead: {:.1}x",
311        resource_analysis.avg_computational_overhead
312    );
313    println!(
314        "    - Memory usage increase: {:.1}%",
315        resource_analysis.memory_overhead * 100.0
316    );
317    println!(
318        "    - Classical processing time: {:.2} ms",
319        resource_analysis.classical_time_ms
320    );
321    println!(
322        "    - Quantum circuit overhead: {:.1}%",
323        resource_analysis.quantum_overhead * 100.0
324    );
325
326    // Step 13: Quantum advantage analysis with error mitigation
327    println!("\n13. Quantum advantage analysis with error mitigation...");
328
329    let quantum_advantage = analyze_quantum_advantage_with_mitigation(
330        &test_circuit,
331        &sorted_results[0].2, // Best mitigation result
332    )?;
333
334    println!("    Quantum Advantage Analysis:");
335    println!(
336        "    - Effective quantum volume: {}",
337        quantum_advantage.effective_quantum_volume
338    );
339    println!(
340        "    - Noise-mitigated fidelity: {:.4}",
341        quantum_advantage.mitigated_fidelity
342    );
343    println!(
344        "    - Classical simulation cost: {:.1}x harder",
345        quantum_advantage.classical_simulation_cost
346    );
347    println!(
348        "    - Practical quantum advantage: {}",
349        if quantum_advantage.practical_advantage {
350            "Yes"
351        } else {
352            "Not yet"
353        }
354    );
355
356    // Step 14: Generate comprehensive report
357    println!("\n14. Generating comprehensive error mitigation report...");
358
359    let comprehensive_report = generate_comprehensive_mitigation_report(
360        &strategies,
361        &mitigation_results,
362        &training_history,
363        &resource_analysis,
364        &quantum_advantage,
365    )?;
366
367    save_mitigation_report(&comprehensive_report, "error_mitigation_report.html")?;
368    println!("    Comprehensive report saved to: error_mitigation_report.html");
369
370    // Step 15: Future recommendations
371    println!("\n15. Error mitigation recommendations...");
372
373    let recommendations =
374        generate_mitigation_recommendations(&test_circuit, &noise_model, &mitigation_results)?;
375
376    println!("    Recommendations:");
377    for (i, recommendation) in recommendations.iter().enumerate() {
378        println!("    {}. {}", i + 1, recommendation);
379    }
380
381    println!("\n=== Advanced Error Mitigation Demo Complete ===");
382    println!("🎯 Successfully demonstrated comprehensive error mitigation capabilities");
383    println!("📊 All mitigation strategies evaluated and optimized");
384    println!("🚀 Quantum ML error mitigation framework ready for production");
385
386    Ok(())
387}
388
389// Helper functions for the demo
390
391fn create_realistic_noise_model() -> Result<NoiseModel> {
392    let mut gate_errors = HashMap::new();
393
394    // Single-qubit gate errors
395    gate_errors.insert(
396        "X".to_string(),
397        GateErrorModel {
398            error_rate: 0.001,
399            error_type: ErrorType::Depolarizing { strength: 0.002 },
400            coherence_limited: true,
401            gate_time: 50e-9, // 50 ns
402            fidelity_model: FidelityModel,
403        },
404    );
405
406    gate_errors.insert(
407        "RZ".to_string(),
408        GateErrorModel {
409            error_rate: 0.0005,
410            error_type: ErrorType::Phase {
411                dephasing_rate: 0.001,
412            },
413            coherence_limited: true,
414            gate_time: 0.0, // Virtual gate
415            fidelity_model: FidelityModel,
416        },
417    );
418
419    // Two-qubit gate errors
420    gate_errors.insert(
421        "CNOT".to_string(),
422        GateErrorModel {
423            error_rate: 0.01,
424            error_type: ErrorType::Depolarizing { strength: 0.02 },
425            coherence_limited: true,
426            gate_time: 200e-9, // 200 ns
427            fidelity_model: FidelityModel,
428        },
429    );
430
431    let measurement_errors = MeasurementErrorModel {
432        readout_fidelity: 0.95,
433        assignment_matrix: Array2::from_shape_vec((2, 2), vec![0.95, 0.05, 0.03, 0.97])?,
434        state_preparation_errors: Array1::from_vec(vec![0.01, 0.01, 0.01, 0.01]),
435        measurement_crosstalk: Array2::zeros((4, 4)),
436    };
437
438    let coherence_times = CoherenceTimeModel {
439        t1_times: Array1::from_vec(vec![100e-6, 80e-6, 120e-6, 90e-6]), // T1 times in seconds
440        t2_times: Array1::from_vec(vec![50e-6, 60e-6, 70e-6, 55e-6]),   // T2 times in seconds
441        t2_echo_times: Array1::from_vec(vec![150e-6, 140e-6, 160e-6, 145e-6]),
442        temporal_fluctuations: TemporalFluctuation,
443    };
444
445    Ok(NoiseModel {
446        gate_errors,
447        measurement_errors,
448        coherence_times,
449        crosstalk_matrix: Array2::zeros((4, 4)),
450        temporal_correlations: TemporalCorrelationModel {
451            correlation_function: CorrelationFunction::Exponential,
452            correlation_time: 1e-3,
453            noise_spectrum: NoiseSpectrum,
454        },
455    })
456}
457
458fn create_mitigation_strategies() -> Result<Vec<MitigationStrategy>> {
459    Ok(vec![
460        MitigationStrategy::ZNE {
461            scale_factors: vec![1.0, 2.0, 3.0],
462            extrapolation_method: ExtrapolationMethod::Polynomial { degree: 2 },
463            circuit_folding: CircuitFoldingMethod::GlobalFolding,
464        },
465        MitigationStrategy::ReadoutErrorMitigation {
466            calibration_matrix: Array2::from_shape_vec(
467                (4, 4),
468                vec![
469                    0.95, 0.02, 0.02, 0.01, 0.02, 0.96, 0.01, 0.01, 0.02, 0.01, 0.95, 0.02, 0.01,
470                    0.01, 0.02, 0.96,
471                ],
472            )?,
473            correction_method: ReadoutCorrectionMethod::MatrixInversion,
474            regularization: 1e-6,
475        },
476        MitigationStrategy::CDR {
477            training_circuits: vec![CliffordCircuit; 10],
478            regression_model: CDRModel,
479            feature_extraction:
480                quantrs2_ml::error_mitigation::FeatureExtractionMethod::CircuitDepth,
481        },
482        MitigationStrategy::SymmetryVerification {
483            symmetry_groups: vec![SymmetryGroup; 2],
484            verification_circuits: vec![VerificationCircuit; 5],
485            post_selection: true,
486        },
487        MitigationStrategy::VirtualDistillation {
488            distillation_rounds: 2,
489            entanglement_protocol: EntanglementProtocol::Bell,
490            purification_threshold: 0.8,
491        },
492        MitigationStrategy::MLMitigation {
493            noise_predictor: NoisePredictorModel,
494            correction_network: CorrectionNetwork,
495            training_data: TrainingDataSet,
496        },
497    ])
498}
499
500const fn get_strategy_name(strategy: &MitigationStrategy) -> &'static str {
501    match strategy {
502        MitigationStrategy::ZNE { .. } => "Zero Noise Extrapolation",
503        MitigationStrategy::ReadoutErrorMitigation { .. } => "Readout Error Mitigation",
504        MitigationStrategy::CDR { .. } => "Clifford Data Regression",
505        MitigationStrategy::SymmetryVerification { .. } => "Symmetry Verification",
506        MitigationStrategy::VirtualDistillation { .. } => "Virtual Distillation",
507        MitigationStrategy::MLMitigation { .. } => "ML-based Mitigation",
508        MitigationStrategy::HybridErrorCorrection { .. } => "Hybrid Error Correction",
509        MitigationStrategy::AdaptiveMultiStrategy { .. } => "Adaptive Multi-Strategy",
510    }
511}
512
513fn create_test_qml_circuit(num_qubits: usize, num_layers: usize) -> Result<QuantumCircuit> {
514    let gates = vec![
515        QuantumGate {
516            name: "RY".to_string(),
517            qubits: vec![0],
518            parameters: Array1::from_vec(vec![0.1]),
519        };
520        num_layers * num_qubits
521    ];
522
523    Ok(QuantumCircuit {
524        gates,
525        qubits: num_qubits,
526    })
527}
528
529fn calculate_average_error_rate(noise_model: &NoiseModel) -> f64 {
530    noise_model
531        .gate_errors
532        .values()
533        .map(|error| error.error_rate)
534        .sum::<f64>()
535        / noise_model.gate_errors.len() as f64
536}
537
538fn estimate_circuit_depth(circuit: &QuantumCircuit) -> usize {
539    circuit.gates.len()
540}
541
542fn simulate_noisy_measurements(
543    circuit: &QuantumCircuit,
544    noise_model: &NoiseModel,
545    num_shots: usize,
546) -> Result<Array2<f64>> {
547    // Simulate noisy measurements with realistic noise
548    let mut measurements = Array2::zeros((num_shots, circuit.num_qubits()));
549
550    for i in 0..num_shots {
551        for j in 0..circuit.num_qubits() {
552            let ideal_prob = 0.5; // Ideal measurement probability
553            let noise_factor = fastrand::f64().mul_add(0.1, -0.05); // ±5% noise
554            let noisy_prob = (ideal_prob + noise_factor).max(0.0).min(1.0);
555            measurements[[i, j]] = if fastrand::f64() < noisy_prob {
556                1.0
557            } else {
558                0.0
559            };
560        }
561    }
562
563    Ok(measurements)
564}
565
566fn simulate_noisy_gradients(
567    circuit: &QuantumCircuit,
568    parameters: &Array1<f64>,
569    noise_model: &NoiseModel,
570) -> Result<Array1<f64>> {
571    // Simulate parameter shift gradients with noise
572    let mut gradients = Array1::zeros(parameters.len());
573
574    for i in 0..parameters.len() {
575        let ideal_gradient = (i as f64 + 1.0) * 0.1; // Mock ideal gradient
576        let noise_std = 0.05; // Gradient noise standard deviation
577        let noise = (fastrand::f64() * noise_std).mul_add(2.0, -noise_std);
578        gradients[i] = ideal_gradient + noise;
579    }
580
581    Ok(gradients)
582}
583
584fn assess_noise_level(measurements: &Array2<f64>) -> f64 {
585    // Calculate empirical noise level from measurements
586    let bit_flip_rate = measurements
587        .iter()
588        .zip(measurements.iter().skip(1))
589        .map(|(&a, &b)| if a == b { 0.0 } else { 1.0 })
590        .sum::<f64>()
591        / (measurements.len() - 1) as f64;
592
593    bit_flip_rate.min(0.5) // Cap at 50%
594}
595
596fn calculate_improvement(noisy: &Array2<f64>, mitigated: &Array2<f64>) -> Result<f64> {
597    // Calculate improvement metric (simplified)
598    let noisy_variance = noisy.var(0.0);
599    let mitigated_variance = mitigated.var(0.0);
600
601    Ok((noisy_variance - mitigated_variance) / noisy_variance)
602}
603
604// Additional helper functions for demonstrations
605
606fn demonstrate_zne_mitigation(
607    circuit: &QuantumCircuit,
608    noise_model: &NoiseModel,
609) -> Result<ZNEResult> {
610    Ok(ZNEResult {
611        extrapolated_fidelity: 0.98,
612        confidence_interval: (0.96, 0.99),
613        scaling_factors_used: vec![1.0, 2.0, 3.0],
614    })
615}
616
617const fn demonstrate_readout_mitigation(
618    circuit: &QuantumCircuit,
619    noise_model: &NoiseModel,
620) -> Result<ReadoutResult> {
621    Ok(ReadoutResult {
622        correction_accuracy: 0.92,
623        condition_number: 12.5,
624        assignment_matrix_rank: 4,
625    })
626}
627
628const fn demonstrate_cdr_mitigation(
629    circuit: &QuantumCircuit,
630    noise_model: &NoiseModel,
631) -> Result<CDRResult> {
632    Ok(CDRResult {
633        r_squared: 0.89,
634        prediction_accuracy: 0.87,
635        training_circuits_used: 100,
636    })
637}
638
639const fn demonstrate_virtual_distillation(
640    circuit: &QuantumCircuit,
641    noise_model: &NoiseModel,
642) -> Result<VDResult> {
643    Ok(VDResult {
644        distillation_fidelity: 0.94,
645        resource_overhead: 2.5,
646        distillation_rounds: 2,
647    })
648}
649
650const fn demonstrate_ml_mitigation(
651    circuit: &QuantumCircuit,
652    noise_model: &NoiseModel,
653) -> Result<MLMitigationResult> {
654    Ok(MLMitigationResult {
655        nn_accuracy: 0.91,
656        prediction_mse: 0.003,
657        correction_effectiveness: 0.85,
658    })
659}
660
661// Supporting structures for demo results
662
663#[derive(Debug)]
664struct ZNEResult {
665    extrapolated_fidelity: f64,
666    confidence_interval: (f64, f64),
667    scaling_factors_used: Vec<f64>,
668}
669
670#[derive(Debug)]
671struct ReadoutResult {
672    correction_accuracy: f64,
673    condition_number: f64,
674    assignment_matrix_rank: usize,
675}
676
677#[derive(Debug)]
678struct CDRResult {
679    r_squared: f64,
680    prediction_accuracy: f64,
681    training_circuits_used: usize,
682}
683
684#[derive(Debug)]
685struct VDResult {
686    distillation_fidelity: f64,
687    resource_overhead: f64,
688    distillation_rounds: usize,
689}
690
691#[derive(Debug)]
692struct MLMitigationResult {
693    nn_accuracy: f64,
694    prediction_mse: f64,
695    correction_effectiveness: f64,
696}
697
698#[derive(Debug)]
699struct RealtimeResults {
700    response_time_ms: f64,
701    adaptation_accuracy: f64,
702    performance_gain: f64,
703}
704
705#[derive(Debug)]
706struct ResourceAnalysis {
707    avg_computational_overhead: f64,
708    memory_overhead: f64,
709    classical_time_ms: f64,
710    quantum_overhead: f64,
711}
712
713#[derive(Debug)]
714struct QuantumAdvantageAnalysis {
715    effective_quantum_volume: usize,
716    mitigated_fidelity: f64,
717    classical_simulation_cost: f64,
718    practical_advantage: bool,
719}
720
721// Additional helper function implementations
722
723const fn create_smart_selection_policy() -> Result<StrategySelectionPolicy> {
724    Ok(StrategySelectionPolicy)
725}
726
727fn create_performance_tracker() -> Result<quantrs2_ml::error_mitigation::PerformanceTracker> {
728    Ok(quantrs2_ml::error_mitigation::PerformanceTracker::default())
729}
730
731fn simulate_dynamic_noise(base_noise: &NoiseModel, step: usize) -> Result<NoiseModel> {
732    // Simulate time-varying noise
733    let mut dynamic_noise = base_noise.clone();
734    let time_factor = 0.1f64.mul_add((step as f64 * 0.1).sin(), 1.0);
735
736    for error_model in dynamic_noise.gate_errors.values_mut() {
737        error_model.error_rate *= time_factor;
738    }
739
740    Ok(dynamic_noise)
741}
742
743fn simulate_training_step_measurements(
744    circuit: &QuantumCircuit,
745    step: usize,
746) -> Result<Array2<f64>> {
747    // Simulate measurements for a training step
748    let num_shots = 100;
749    let mut measurements = Array2::zeros((num_shots, circuit.num_qubits()));
750
751    for i in 0..num_shots {
752        for j in 0..circuit.num_qubits() {
753            let step_bias = step as f64 * 0.01;
754            let prob = fastrand::f64().mul_add(0.1, 0.5 + step_bias) - 0.05;
755            measurements[[i, j]] = if fastrand::f64() < prob.max(0.0).min(1.0) {
756                1.0
757            } else {
758                0.0
759            };
760        }
761    }
762
763    Ok(measurements)
764}
Source

pub fn with_parameters(&self, params: &Array1<f64>) -> Result<Self>

Source

pub fn clone(&self) -> Self

Trait Implementations§

Source§

impl Clone for QuantumCircuit

Source§

fn clone(&self) -> QuantumCircuit

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for QuantumCircuit

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DynClone for T
where T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<SS, SP> SupersetOf<SS> for SP
where SS: SubsetOf<SP>,

Source§

fn to_subset(&self) -> Option<SS>

The inverse inclusion map: attempts to construct self from the equivalent element of its superset. Read more
Source§

fn is_in_subset(&self) -> bool

Checks if self is actually part of its subset T (and can be converted to it).
Source§

fn to_subset_unchecked(&self) -> SS

Use with care! Same as self.to_subset but without any property checks. Always succeeds.
Source§

fn from_subset(element: &SS) -> SP

The inclusion map: converts self to the equivalent element of its superset.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V