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

Source§

impl<T> Ungil for T
where T: Send,