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