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