quantrs2_device/
hardware_parallelization.rs

1//! Hardware-Aware Quantum Circuit Parallelization
2//!
3//! This module provides sophisticated parallelization capabilities that understand
4//! and respect hardware constraints, topology, and resource limitations to maximize
5//! throughput while maintaining circuit fidelity and correctness.
6
7use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
8use std::sync::{Arc, Mutex, RwLock};
9use std::time::{Duration, Instant, SystemTime};
10
11use quantrs2_circuit::prelude::*;
12use quantrs2_core::{
13    error::{QuantRS2Error, QuantRS2Result},
14    gate::GateOp,
15    platform::PlatformCapabilities,
16    qubit::QubitId,
17};
18
19// SciRS2 integration for advanced parallelization analysis
20#[cfg(feature = "scirs2")]
21use scirs2_graph::{
22    betweenness_centrality, closeness_centrality, dijkstra_path, minimum_spanning_tree,
23    strongly_connected_components, topological_sort, Graph,
24};
25#[cfg(feature = "scirs2")]
26use scirs2_optimize::{differential_evolution, minimize, OptimizeResult};
27#[cfg(feature = "scirs2")]
28use scirs2_stats::{corrcoef, mean, pearsonr, std};
29
30use scirs2_core::ndarray::{Array1, Array2, ArrayView1, ArrayView2};
31use serde::{Deserialize, Serialize};
32use tokio::sync::{Mutex as AsyncMutex, RwLock as AsyncRwLock, Semaphore};
33
34use crate::{
35    backend_traits::{query_backend_capabilities, BackendCapabilities},
36    calibration::{CalibrationManager, DeviceCalibration},
37    integrated_device_manager::{DeviceInfo, IntegratedQuantumDeviceManager},
38    routing_advanced::{AdvancedQubitRouter, AdvancedRoutingResult},
39    topology::HardwareTopology,
40    translation::HardwareBackend,
41    DeviceError, DeviceResult,
42};
43
44/// Hardware-aware parallelization configuration
45#[derive(Debug, Clone, Serialize, Deserialize)]
46pub struct ParallelizationConfig {
47    /// Parallelization strategy
48    pub strategy: ParallelizationStrategy,
49    /// Resource allocation settings
50    pub resource_allocation: ResourceAllocationConfig,
51    /// Scheduling configuration
52    pub scheduling_config: ParallelSchedulingConfig,
53    /// Hardware awareness settings
54    pub hardware_awareness: HardwareAwarenessConfig,
55    /// Performance optimization settings
56    pub performance_config: PerformanceOptimizationConfig,
57    /// Load balancing configuration
58    pub load_balancing: LoadBalancingConfig,
59    /// Resource monitoring settings
60    pub monitoring_config: ResourceMonitoringConfig,
61}
62
63/// Parallelization strategies
64#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
65pub enum ParallelizationStrategy {
66    /// Circuit-level parallelization (multiple independent circuits)
67    CircuitLevel,
68    /// Gate-level parallelization (parallel gate execution)
69    GateLevel,
70    /// Hybrid approach combining both strategies
71    Hybrid,
72    /// Topology-aware parallelization
73    TopologyAware,
74    /// Resource-constrained parallelization
75    ResourceConstrained,
76    /// SciRS2-powered intelligent parallelization
77    SciRS2Optimized,
78    /// Custom strategy with specific parameters
79    Custom {
80        circuit_concurrency: usize,
81        gate_concurrency: usize,
82        resource_weights: HashMap<String, f64>,
83    },
84}
85
86/// Resource allocation configuration
87#[derive(Debug, Clone, Serialize, Deserialize)]
88pub struct ResourceAllocationConfig {
89    /// Maximum concurrent circuits
90    pub max_concurrent_circuits: usize,
91    /// Maximum concurrent gates per circuit
92    pub max_concurrent_gates: usize,
93    /// CPU core allocation strategy
94    pub cpu_allocation: CpuAllocationStrategy,
95    /// Memory allocation limits
96    pub memory_limits: MemoryLimits,
97    /// QPU resource allocation
98    pub qpu_allocation: QpuAllocationConfig,
99    /// Network bandwidth allocation
100    pub network_allocation: NetworkAllocationConfig,
101}
102
103/// CPU allocation strategies
104#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
105pub enum CpuAllocationStrategy {
106    /// Use all available cores
107    AllCores,
108    /// Use fixed number of cores
109    FixedCores(usize),
110    /// Use percentage of available cores
111    PercentageCores(f64),
112    /// Adaptive allocation based on load
113    Adaptive,
114    /// NUMA-aware allocation
115    NumaAware,
116}
117
118/// Memory allocation limits
119#[derive(Debug, Clone, Serialize, Deserialize)]
120pub struct MemoryLimits {
121    /// Maximum total memory usage (MB)
122    pub max_total_memory_mb: f64,
123    /// Maximum memory per circuit (MB)
124    pub max_per_circuit_mb: f64,
125    /// Memory allocation strategy
126    pub allocation_strategy: MemoryAllocationStrategy,
127    /// Enable memory pooling
128    pub enable_pooling: bool,
129    /// Garbage collection threshold
130    pub gc_threshold: f64,
131}
132
133/// Memory allocation strategies
134#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
135pub enum MemoryAllocationStrategy {
136    /// Static allocation upfront
137    Static,
138    /// Dynamic allocation as needed
139    Dynamic,
140    /// Pooled allocation with reuse
141    Pooled,
142    /// Adaptive based on circuit complexity
143    Adaptive,
144}
145
146/// QPU resource allocation configuration
147#[derive(Debug, Clone, Serialize, Deserialize)]
148pub struct QpuAllocationConfig {
149    /// Maximum QPU time per circuit
150    pub max_qpu_time_per_circuit: Duration,
151    /// QPU sharing strategy
152    pub sharing_strategy: QpuSharingStrategy,
153    /// Queue management
154    pub queue_management: QueueManagementConfig,
155    /// Fairness parameters
156    pub fairness_config: FairnessConfig,
157}
158
159/// QPU sharing strategies
160#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
161pub enum QpuSharingStrategy {
162    /// Time slicing
163    TimeSlicing,
164    /// Space slicing (using different qubits)
165    SpaceSlicing,
166    /// Hybrid time/space slicing
167    HybridSlicing,
168    /// Exclusive access
169    Exclusive,
170    /// Best effort sharing
171    BestEffort,
172}
173
174/// Queue management configuration
175#[derive(Debug, Clone, Serialize, Deserialize)]
176pub struct QueueManagementConfig {
177    /// Queue scheduling algorithm
178    pub algorithm: QueueSchedulingAlgorithm,
179    /// Maximum queue size
180    pub max_queue_size: usize,
181    /// Priority levels
182    pub priority_levels: usize,
183    /// Enable preemption
184    pub enable_preemption: bool,
185    /// Timeout settings
186    pub timeout_config: TimeoutConfig,
187}
188
189/// Queue scheduling algorithms
190#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
191pub enum QueueSchedulingAlgorithm {
192    /// First-come, first-served
193    FCFS,
194    /// Shortest job first
195    SJF,
196    /// Priority-based scheduling
197    Priority,
198    /// Round-robin
199    RoundRobin,
200    /// Multilevel feedback queue
201    MLFQ,
202    /// SciRS2-optimized scheduling
203    SciRS2Optimized,
204}
205
206/// Timeout configuration
207#[derive(Debug, Clone, Serialize, Deserialize)]
208pub struct TimeoutConfig {
209    /// Circuit execution timeout
210    pub execution_timeout: Duration,
211    /// Queue wait timeout
212    pub queue_timeout: Duration,
213    /// Resource acquisition timeout
214    pub resource_timeout: Duration,
215    /// Enable adaptive timeouts
216    pub adaptive_timeouts: bool,
217}
218
219/// Fairness configuration
220#[derive(Debug, Clone, Serialize, Deserialize)]
221pub struct FairnessConfig {
222    /// Fairness algorithm
223    pub algorithm: FairnessAlgorithm,
224    /// Resource quotas per user/circuit
225    pub resource_quotas: ResourceQuotas,
226    /// Aging factor for starvation prevention
227    pub aging_factor: f64,
228    /// Enable burst allowances
229    pub enable_burst_allowances: bool,
230}
231
232/// Fairness algorithms
233#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
234pub enum FairnessAlgorithm {
235    /// Proportional fair sharing
236    ProportionalFair,
237    /// Max-min fairness
238    MaxMinFair,
239    /// Weighted fair queuing
240    WeightedFairQueuing,
241    /// Lottery scheduling
242    LotteryScheduling,
243    /// Game-theoretic fair scheduling
244    GameTheoretic,
245}
246
247/// Resource quotas
248#[derive(Debug, Clone, Serialize, Deserialize)]
249pub struct ResourceQuotas {
250    /// CPU time quota per user
251    pub cpu_quota: Option<Duration>,
252    /// QPU time quota per user
253    pub qpu_quota: Option<Duration>,
254    /// Memory quota per user (MB)
255    pub memory_quota: Option<f64>,
256    /// Circuit count quota per user
257    pub circuit_quota: Option<usize>,
258}
259
260/// Network allocation configuration
261#[derive(Debug, Clone, Serialize, Deserialize)]
262pub struct NetworkAllocationConfig {
263    /// Maximum bandwidth per circuit (Mbps)
264    pub max_bandwidth_per_circuit: f64,
265    /// Network QoS class
266    pub qos_class: NetworkQoSClass,
267    /// Compression settings
268    pub compression_config: CompressionConfig,
269    /// Latency optimization
270    pub latency_optimization: bool,
271}
272
273/// Network QoS classes
274#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
275pub enum NetworkQoSClass {
276    /// Best effort
277    BestEffort,
278    /// Assured forwarding
279    AssuredForwarding,
280    /// Expedited forwarding
281    ExpeditedForwarding,
282    /// Real-time
283    RealTime,
284}
285
286/// Compression configuration
287#[derive(Debug, Clone, Serialize, Deserialize)]
288pub struct CompressionConfig {
289    /// Enable compression
290    pub enabled: bool,
291    /// Compression algorithm
292    pub algorithm: CompressionAlgorithm,
293    /// Compression level (0-9)
294    pub level: u8,
295    /// Minimum size threshold for compression
296    pub size_threshold: usize,
297}
298
299/// Compression algorithms
300#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
301pub enum CompressionAlgorithm {
302    /// Gzip compression
303    Gzip,
304    /// Zstd compression
305    Zstd,
306    /// LZ4 compression
307    LZ4,
308    /// Brotli compression
309    Brotli,
310}
311
312/// Parallel scheduling configuration
313#[derive(Debug, Clone, Serialize, Deserialize)]
314pub struct ParallelSchedulingConfig {
315    /// Scheduling algorithm
316    pub algorithm: ParallelSchedulingAlgorithm,
317    /// Work stealing configuration
318    pub work_stealing: WorkStealingConfig,
319    /// Load balancing parameters
320    pub load_balancing_params: LoadBalancingParams,
321    /// Thread pool configuration
322    pub thread_pool_config: ThreadPoolConfig,
323}
324
325/// Parallel scheduling algorithms
326#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
327pub enum ParallelSchedulingAlgorithm {
328    /// Work stealing
329    WorkStealing,
330    /// Work sharing
331    WorkSharing,
332    /// Fork-join
333    ForkJoin,
334    /// Actor model
335    ActorModel,
336    /// Pipeline parallelism
337    Pipeline,
338    /// Data parallelism
339    DataParallel,
340    /// Task parallelism
341    TaskParallel,
342}
343
344/// Work stealing configuration
345#[derive(Debug, Clone, Serialize, Deserialize)]
346pub struct WorkStealingConfig {
347    /// Enable work stealing
348    pub enabled: bool,
349    /// Stealing strategy
350    pub strategy: WorkStealingStrategy,
351    /// Queue size per worker
352    pub queue_size: usize,
353    /// Stealing threshold
354    pub stealing_threshold: f64,
355}
356
357/// Work stealing strategies
358#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
359pub enum WorkStealingStrategy {
360    /// Random stealing
361    Random,
362    /// Round-robin stealing
363    RoundRobin,
364    /// Load-based stealing
365    LoadBased,
366    /// Locality-aware stealing
367    LocalityAware,
368}
369
370/// Load balancing parameters
371#[derive(Debug, Clone, Serialize, Deserialize)]
372pub struct LoadBalancingParams {
373    /// Rebalancing frequency
374    pub rebalancing_frequency: Duration,
375    /// Load threshold for rebalancing
376    pub load_threshold: f64,
377    /// Migration cost factor
378    pub migration_cost_factor: f64,
379    /// Enable adaptive load balancing
380    pub adaptive_balancing: bool,
381}
382
383/// Thread pool configuration
384#[derive(Debug, Clone, Serialize, Deserialize)]
385pub struct ThreadPoolConfig {
386    /// Core thread count
387    pub core_threads: usize,
388    /// Maximum thread count
389    pub max_threads: usize,
390    /// Keep-alive time for idle threads
391    pub keep_alive_time: Duration,
392    /// Thread priority
393    pub thread_priority: ThreadPriority,
394    /// Thread affinity settings
395    pub affinity_config: ThreadAffinityConfig,
396}
397
398/// Thread priority levels
399#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
400pub enum ThreadPriority {
401    /// Low priority
402    Low,
403    /// Normal priority
404    Normal,
405    /// High priority
406    High,
407    /// Real-time priority
408    RealTime,
409}
410
411/// Thread affinity configuration
412#[derive(Debug, Clone, Serialize, Deserialize)]
413pub struct ThreadAffinityConfig {
414    /// Enable CPU affinity
415    pub enabled: bool,
416    /// CPU core assignment strategy
417    pub assignment_strategy: CoreAssignmentStrategy,
418    /// NUMA node preference
419    pub numa_preference: NumaPreference,
420}
421
422/// Core assignment strategies
423#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
424pub enum CoreAssignmentStrategy {
425    /// Automatic assignment
426    Automatic,
427    /// Fixed core assignment
428    Fixed(Vec<usize>),
429    /// Round-robin assignment
430    RoundRobin,
431    /// Load-based assignment
432    LoadBased,
433}
434
435/// NUMA preferences
436#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
437pub enum NumaPreference {
438    /// No preference
439    None,
440    /// Local node preferred
441    LocalNode,
442    /// Specific node
443    SpecificNode(usize),
444    /// Interleaved across nodes
445    Interleaved,
446}
447
448/// Hardware awareness configuration
449#[derive(Debug, Clone, Serialize, Deserialize)]
450pub struct HardwareAwarenessConfig {
451    /// Topology awareness level
452    pub topology_awareness: TopologyAwarenessLevel,
453    /// Calibration integration
454    pub calibration_integration: CalibrationIntegrationConfig,
455    /// Error rate consideration
456    pub error_rate_config: ErrorRateConfig,
457    /// Connectivity constraints
458    pub connectivity_config: ConnectivityConfig,
459    /// Resource usage tracking
460    pub resource_tracking: ResourceTrackingConfig,
461}
462
463/// Topology awareness levels
464#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
465pub enum TopologyAwarenessLevel {
466    /// Basic awareness (qubit count only)
467    Basic,
468    /// Connectivity aware
469    Connectivity,
470    /// Calibration aware
471    Calibration,
472    /// Full topology optimization
473    Full,
474    /// SciRS2-powered topology analysis
475    SciRS2Enhanced,
476}
477
478/// Calibration integration configuration
479#[derive(Debug, Clone, Serialize, Deserialize)]
480pub struct CalibrationIntegrationConfig {
481    /// Use real-time calibration data
482    pub use_realtime_calibration: bool,
483    /// Calibration update frequency
484    pub update_frequency: Duration,
485    /// Quality threshold for gate selection
486    pub quality_threshold: f64,
487    /// Enable predictive calibration
488    pub enable_predictive: bool,
489}
490
491/// Error rate configuration
492#[derive(Debug, Clone, Serialize, Deserialize)]
493pub struct ErrorRateConfig {
494    /// Consider error rates in scheduling
495    pub consider_error_rates: bool,
496    /// Error rate threshold
497    pub error_threshold: f64,
498    /// Error mitigation strategy
499    pub mitigation_strategy: ErrorMitigationStrategy,
500    /// Error prediction model
501    pub prediction_model: ErrorPredictionModel,
502}
503
504/// Error mitigation strategies
505#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
506pub enum ErrorMitigationStrategy {
507    /// No mitigation
508    None,
509    /// Retry on high error
510    Retry,
511    /// Dynamical decoupling
512    DynamicalDecoupling,
513    /// Zero-noise extrapolation
514    ZeroNoiseExtrapolation,
515    /// Composite mitigation
516    Composite,
517}
518
519/// Error prediction models
520#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
521pub enum ErrorPredictionModel {
522    /// Static error model
523    Static,
524    /// Time-dependent model
525    TimeDependent,
526    /// Machine learning model
527    MachineLearning,
528    /// Physics-based model
529    PhysicsBased,
530}
531
532/// Connectivity configuration
533#[derive(Debug, Clone, Serialize, Deserialize)]
534pub struct ConnectivityConfig {
535    /// Enforce connectivity constraints
536    pub enforce_constraints: bool,
537    /// SWAP insertion strategy
538    pub swap_strategy: SwapInsertionStrategy,
539    /// Routing algorithm preference
540    pub routing_preference: RoutingPreference,
541    /// Connectivity optimization
542    pub optimization_config: ConnectivityOptimizationConfig,
543}
544
545/// SWAP insertion strategies
546#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
547pub enum SwapInsertionStrategy {
548    /// Minimal SWAP insertion
549    Minimal,
550    /// Lookahead SWAP insertion
551    Lookahead,
552    /// Global optimization
553    GlobalOptimal,
554    /// Heuristic-based
555    Heuristic,
556}
557
558/// Routing preferences
559#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
560pub enum RoutingPreference {
561    /// Shortest path
562    ShortestPath,
563    /// Minimum congestion
564    MinimumCongestion,
565    /// Load balancing
566    LoadBalancing,
567    /// Quality-aware routing
568    QualityAware,
569}
570
571/// Connectivity optimization configuration
572#[derive(Debug, Clone, Serialize, Deserialize)]
573pub struct ConnectivityOptimizationConfig {
574    /// Enable parallel routing
575    pub enable_parallel_routing: bool,
576    /// Routing optimization level
577    pub optimization_level: OptimizationLevel,
578    /// Use machine learning for routing
579    pub use_ml_routing: bool,
580    /// Precompute routing tables
581    pub precompute_tables: bool,
582}
583
584/// Optimization levels
585#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
586pub enum OptimizationLevel {
587    /// No optimization
588    None,
589    /// Basic optimization
590    Basic,
591    /// Moderate optimization
592    Moderate,
593    /// Aggressive optimization
594    Aggressive,
595    /// Experimental optimization
596    Experimental,
597}
598
599/// Resource tracking configuration
600#[derive(Debug, Clone, Serialize, Deserialize)]
601pub struct ResourceTrackingConfig {
602    /// Enable CPU usage tracking
603    pub track_cpu_usage: bool,
604    /// Enable memory usage tracking
605    pub track_memory_usage: bool,
606    /// Enable QPU usage tracking
607    pub track_qpu_usage: bool,
608    /// Enable network usage tracking
609    pub track_network_usage: bool,
610    /// Tracking granularity
611    pub tracking_granularity: TrackingGranularity,
612    /// Reporting frequency
613    pub reporting_frequency: Duration,
614}
615
616/// Tracking granularity levels
617#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
618pub enum TrackingGranularity {
619    /// Coarse-grained (per circuit)
620    Coarse,
621    /// Medium-grained (per gate group)
622    Medium,
623    /// Fine-grained (per gate)
624    Fine,
625    /// Ultra-fine (per operation)
626    UltraFine,
627}
628
629/// Performance optimization configuration
630#[derive(Debug, Clone, Serialize, Deserialize)]
631pub struct PerformanceOptimizationConfig {
632    /// Optimization objectives
633    pub objectives: Vec<OptimizationObjective>,
634    /// Caching configuration
635    pub caching_config: CachingConfig,
636    /// Prefetching settings
637    pub prefetching_config: PrefetchingConfig,
638    /// Batch processing settings
639    pub batch_config: BatchProcessingConfig,
640    /// Adaptive optimization
641    pub adaptive_config: AdaptiveOptimizationConfig,
642}
643
644/// Optimization objectives
645#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
646pub enum OptimizationObjective {
647    /// Minimize execution time
648    MinimizeTime,
649    /// Maximize throughput
650    MaximizeThroughput,
651    /// Minimize resource usage
652    MinimizeResources,
653    /// Maximize quality
654    MaximizeQuality,
655    /// Minimize cost
656    MinimizeCost,
657    /// Minimize energy consumption
658    MinimizeEnergy,
659    /// Balanced optimization
660    Balanced,
661}
662
663/// Caching configuration
664#[derive(Debug, Clone, Serialize, Deserialize)]
665pub struct CachingConfig {
666    /// Enable result caching
667    pub enable_result_caching: bool,
668    /// Enable compilation caching
669    pub enable_compilation_caching: bool,
670    /// Cache size limits
671    pub size_limits: CacheSizeLimits,
672    /// Cache eviction policy
673    pub eviction_policy: CacheEvictionPolicy,
674    /// Cache warming strategies
675    pub warming_strategies: Vec<CacheWarmingStrategy>,
676}
677
678/// Cache size limits
679#[derive(Debug, Clone, Serialize, Deserialize)]
680pub struct CacheSizeLimits {
681    /// Maximum cache entries
682    pub max_entries: usize,
683    /// Maximum memory usage (MB)
684    pub max_memory_mb: f64,
685    /// Maximum disk usage (MB)
686    pub max_disk_mb: f64,
687    /// Per-user cache limits
688    pub per_user_limits: Option<Box<CacheSizeLimits>>,
689}
690
691/// Cache eviction policies
692#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
693pub enum CacheEvictionPolicy {
694    /// Least recently used
695    LRU,
696    /// Least frequently used
697    LFU,
698    /// First in, first out
699    FIFO,
700    /// Random eviction
701    Random,
702    /// Time-based expiration
703    TimeExpiration,
704    /// Size-based eviction
705    SizeBased,
706}
707
708/// Cache warming strategies
709#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
710pub enum CacheWarmingStrategy {
711    /// Preload common circuits
712    PreloadCommon,
713    /// Predictive preloading
714    Predictive,
715    /// User pattern based
716    UserPatternBased,
717    /// Background warming
718    Background,
719}
720
721/// Prefetching configuration
722#[derive(Debug, Clone, Serialize, Deserialize)]
723pub struct PrefetchingConfig {
724    /// Enable prefetching
725    pub enabled: bool,
726    /// Prefetching strategy
727    pub strategy: PrefetchingStrategy,
728    /// Prefetch distance
729    pub prefetch_distance: usize,
730    /// Prefetch confidence threshold
731    pub confidence_threshold: f64,
732}
733
734/// Prefetching strategies
735#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
736pub enum PrefetchingStrategy {
737    /// Sequential prefetching
738    Sequential,
739    /// Pattern-based prefetching
740    PatternBased,
741    /// Machine learning prefetching
742    MachineLearning,
743    /// Adaptive prefetching
744    Adaptive,
745}
746
747/// Batch processing configuration
748#[derive(Debug, Clone, Serialize, Deserialize)]
749pub struct BatchProcessingConfig {
750    /// Enable batch processing
751    pub enabled: bool,
752    /// Batch size limits
753    pub size_limits: BatchSizeLimits,
754    /// Batching strategy
755    pub strategy: BatchingStrategy,
756    /// Batch timeout
757    pub timeout: Duration,
758}
759
760/// Batch size limits
761#[derive(Debug, Clone, Serialize, Deserialize)]
762pub struct BatchSizeLimits {
763    /// Minimum batch size
764    pub min_size: usize,
765    /// Maximum batch size
766    pub max_size: usize,
767    /// Optimal batch size
768    pub optimal_size: usize,
769    /// Dynamic sizing
770    pub dynamic_sizing: bool,
771}
772
773/// Batching strategies
774#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
775pub enum BatchingStrategy {
776    /// Fixed size batching
777    FixedSize,
778    /// Time-based batching
779    TimeBased,
780    /// Adaptive batching
781    Adaptive,
782    /// Circuit similarity batching
783    SimilarityBased,
784    /// Resource-aware batching
785    ResourceAware,
786}
787
788/// Adaptive optimization configuration
789#[derive(Debug, Clone, Serialize, Deserialize)]
790pub struct AdaptiveOptimizationConfig {
791    /// Enable adaptive optimization
792    pub enabled: bool,
793    /// Adaptation frequency
794    pub adaptation_frequency: Duration,
795    /// Performance monitoring window
796    pub monitoring_window: Duration,
797    /// Adaptation sensitivity
798    pub sensitivity: f64,
799    /// Machine learning config
800    pub ml_config: AdaptiveMLConfig,
801}
802
803/// Adaptive machine learning configuration
804#[derive(Debug, Clone, Serialize, Deserialize)]
805pub struct AdaptiveMLConfig {
806    /// Enable ML-based adaptation
807    pub enabled: bool,
808    /// ML model type
809    pub model_type: MLModelType,
810    /// Training frequency
811    pub training_frequency: Duration,
812    /// Feature engineering config
813    pub feature_config: FeatureEngineeringConfig,
814}
815
816/// ML model types
817#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
818pub enum MLModelType {
819    /// Linear regression
820    LinearRegression,
821    /// Random forest
822    RandomForest,
823    /// Neural network
824    NeuralNetwork,
825    /// Reinforcement learning
826    ReinforcementLearning,
827    /// Ensemble methods
828    Ensemble,
829}
830
831/// Feature engineering configuration
832#[derive(Debug, Clone, Serialize, Deserialize)]
833pub struct FeatureEngineeringConfig {
834    /// Circuit features to extract
835    pub circuit_features: Vec<CircuitFeature>,
836    /// Hardware features to extract
837    pub hardware_features: Vec<HardwareFeature>,
838    /// Performance features to extract
839    pub performance_features: Vec<PerformanceFeature>,
840    /// Feature normalization
841    pub normalization: FeatureNormalization,
842}
843
844/// Circuit features
845#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
846pub enum CircuitFeature {
847    /// Number of qubits
848    QubitCount,
849    /// Circuit depth
850    Depth,
851    /// Gate count
852    GateCount,
853    /// Gate type distribution
854    GateTypeDistribution,
855    /// Connectivity requirements
856    ConnectivityRequirements,
857    /// Parallelism potential
858    ParallelismPotential,
859}
860
861/// Hardware features
862#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
863pub enum HardwareFeature {
864    /// Available qubits
865    AvailableQubits,
866    /// Connectivity graph
867    ConnectivityGraph,
868    /// Error rates
869    ErrorRates,
870    /// Calibration quality
871    CalibrationQuality,
872    /// Queue status
873    QueueStatus,
874    /// Resource utilization
875    ResourceUtilization,
876}
877
878/// Performance features
879#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
880pub enum PerformanceFeature {
881    /// Execution time
882    ExecutionTime,
883    /// Throughput
884    Throughput,
885    /// Resource efficiency
886    ResourceEfficiency,
887    /// Quality metrics
888    QualityMetrics,
889    /// Cost metrics
890    CostMetrics,
891    /// Energy consumption
892    EnergyConsumption,
893}
894
895/// Feature normalization methods
896#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
897pub enum FeatureNormalization {
898    /// No normalization
899    None,
900    /// Min-max normalization
901    MinMax,
902    /// Z-score normalization
903    ZScore,
904    /// Robust normalization
905    Robust,
906    /// Unit vector normalization
907    UnitVector,
908}
909
910/// Load balancing configuration
911#[derive(Debug, Clone, Serialize, Deserialize)]
912pub struct LoadBalancingConfig {
913    /// Load balancing algorithm
914    pub algorithm: LoadBalancingAlgorithm,
915    /// Monitoring configuration
916    pub monitoring: LoadMonitoringConfig,
917    /// Rebalancing triggers
918    pub rebalancing_triggers: RebalancingTriggers,
919    /// Migration policies
920    pub migration_policies: MigrationPolicies,
921}
922
923/// Load balancing algorithms
924#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
925pub enum LoadBalancingAlgorithm {
926    /// Round-robin
927    RoundRobin,
928    /// Weighted round-robin
929    WeightedRoundRobin,
930    /// Least connections
931    LeastConnections,
932    /// Least response time
933    LeastResponseTime,
934    /// Resource-based balancing
935    ResourceBased,
936    /// Machine learning based
937    MachineLearningBased,
938}
939
940/// Load monitoring configuration
941#[derive(Debug, Clone, Serialize, Deserialize)]
942pub struct LoadMonitoringConfig {
943    /// Monitoring frequency
944    pub frequency: Duration,
945    /// Metrics to monitor
946    pub metrics: Vec<LoadMetric>,
947    /// Alerting thresholds
948    pub thresholds: LoadThresholds,
949    /// Historical data retention
950    pub retention_period: Duration,
951}
952
953/// Load metrics
954#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
955pub enum LoadMetric {
956    /// CPU utilization
957    CpuUtilization,
958    /// Memory utilization
959    MemoryUtilization,
960    /// QPU utilization
961    QpuUtilization,
962    /// Network utilization
963    NetworkUtilization,
964    /// Queue length
965    QueueLength,
966    /// Response time
967    ResponseTime,
968    /// Throughput
969    Throughput,
970    /// Error rate
971    ErrorRate,
972}
973
974/// Load thresholds
975#[derive(Debug, Clone, Serialize, Deserialize)]
976pub struct LoadThresholds {
977    /// CPU utilization threshold
978    pub cpu_threshold: f64,
979    /// Memory utilization threshold
980    pub memory_threshold: f64,
981    /// QPU utilization threshold
982    pub qpu_threshold: f64,
983    /// Network utilization threshold
984    pub network_threshold: f64,
985    /// Queue length threshold
986    pub queue_threshold: usize,
987    /// Response time threshold
988    pub response_time_threshold: Duration,
989}
990
991/// Rebalancing triggers
992#[derive(Debug, Clone, Serialize, Deserialize)]
993pub struct RebalancingTriggers {
994    /// CPU imbalance threshold
995    pub cpu_imbalance_threshold: f64,
996    /// Memory imbalance threshold
997    pub memory_imbalance_threshold: f64,
998    /// Queue imbalance threshold
999    pub queue_imbalance_threshold: f64,
1000    /// Time-based rebalancing interval
1001    pub time_interval: Option<Duration>,
1002    /// Event-based triggers
1003    pub event_triggers: Vec<RebalancingEvent>,
1004}
1005
1006/// Rebalancing events
1007#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1008pub enum RebalancingEvent {
1009    /// Node failure
1010    NodeFailure,
1011    /// Node recovery
1012    NodeRecovery,
1013    /// Capacity change
1014    CapacityChange,
1015    /// Load spike
1016    LoadSpike,
1017    /// Performance degradation
1018    PerformanceDegradation,
1019}
1020
1021/// Migration policies
1022#[derive(Debug, Clone, Serialize, Deserialize)]
1023pub struct MigrationPolicies {
1024    /// Migration cost threshold
1025    pub cost_threshold: f64,
1026    /// Maximum migrations per period
1027    pub max_migrations_per_period: usize,
1028    /// Migration period
1029    pub migration_period: Duration,
1030    /// Circuit migration strategy
1031    pub circuit_migration_strategy: CircuitMigrationStrategy,
1032    /// Data migration strategy
1033    pub data_migration_strategy: DataMigrationStrategy,
1034}
1035
1036/// Circuit migration strategies
1037#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1038pub enum CircuitMigrationStrategy {
1039    /// No migration
1040    None,
1041    /// Checkpoint and restart
1042    CheckpointRestart,
1043    /// Live migration
1044    LiveMigration,
1045    /// Incremental migration
1046    Incremental,
1047}
1048
1049/// Data migration strategies
1050#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1051pub enum DataMigrationStrategy {
1052    /// No data migration
1053    None,
1054    /// Copy-based migration
1055    Copy,
1056    /// Move-based migration
1057    Move,
1058    /// Distributed caching
1059    DistributedCaching,
1060}
1061
1062/// Resource monitoring configuration
1063#[derive(Debug, Clone, Serialize, Deserialize)]
1064pub struct ResourceMonitoringConfig {
1065    /// Enable real-time monitoring
1066    pub real_time_monitoring: bool,
1067    /// Monitoring granularity
1068    pub granularity: MonitoringGranularity,
1069    /// Metrics collection
1070    pub metrics_collection: MetricsCollectionConfig,
1071    /// Alerting configuration
1072    pub alerting: AlertingConfig,
1073    /// Reporting configuration
1074    pub reporting: ReportingConfig,
1075}
1076
1077/// Monitoring granularity
1078#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1079pub enum MonitoringGranularity {
1080    /// System-level monitoring
1081    System,
1082    /// Device-level monitoring
1083    Device,
1084    /// Circuit-level monitoring
1085    Circuit,
1086    /// Gate-level monitoring
1087    Gate,
1088    /// Operation-level monitoring
1089    Operation,
1090}
1091
1092/// Metrics collection configuration
1093#[derive(Debug, Clone, Serialize, Deserialize)]
1094pub struct MetricsCollectionConfig {
1095    /// Collection frequency
1096    pub frequency: Duration,
1097    /// Metrics to collect
1098    pub metrics: Vec<MonitoringMetric>,
1099    /// Data retention policy
1100    pub retention_policy: RetentionPolicy,
1101    /// Storage configuration
1102    pub storage_config: StorageConfig,
1103}
1104
1105/// Monitoring metrics
1106#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1107pub enum MonitoringMetric {
1108    /// Resource utilization
1109    ResourceUtilization,
1110    /// Performance metrics
1111    Performance,
1112    /// Quality metrics
1113    Quality,
1114    /// Cost metrics
1115    Cost,
1116    /// Energy metrics
1117    Energy,
1118    /// Availability metrics
1119    Availability,
1120    /// Security metrics
1121    Security,
1122}
1123
1124/// Data retention policy
1125#[derive(Debug, Clone, Serialize, Deserialize)]
1126pub struct RetentionPolicy {
1127    /// Raw data retention period
1128    pub raw_data_retention: Duration,
1129    /// Aggregated data retention period
1130    pub aggregated_data_retention: Duration,
1131    /// Archive policy
1132    pub archive_policy: ArchivePolicy,
1133    /// Compression settings
1134    pub compression: CompressionConfig,
1135}
1136
1137/// Archive policy
1138#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1139pub enum ArchivePolicy {
1140    /// No archiving
1141    None,
1142    /// Time-based archiving
1143    TimeBased(Duration),
1144    /// Size-based archiving
1145    SizeBased(usize),
1146    /// Custom archiving rules
1147    Custom(String),
1148}
1149
1150/// Storage configuration
1151#[derive(Debug, Clone, Serialize, Deserialize)]
1152pub struct StorageConfig {
1153    /// Storage backend
1154    pub backend: StorageBackend,
1155    /// Storage location
1156    pub location: String,
1157    /// Encryption settings
1158    pub encryption: EncryptionConfig,
1159    /// Replication settings
1160    pub replication: ReplicationConfig,
1161}
1162
1163/// Storage backends
1164#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1165pub enum StorageBackend {
1166    /// Local filesystem
1167    LocalFilesystem,
1168    /// Distributed filesystem
1169    DistributedFilesystem,
1170    /// Cloud storage
1171    CloudStorage,
1172    /// Database storage
1173    Database,
1174    /// Time-series database
1175    TimeSeriesDatabase,
1176}
1177
1178/// Encryption configuration
1179#[derive(Debug, Clone, Serialize, Deserialize)]
1180pub struct EncryptionConfig {
1181    /// Enable encryption
1182    pub enabled: bool,
1183    /// Encryption algorithm
1184    pub algorithm: EncryptionAlgorithm,
1185    /// Key management
1186    pub key_management: KeyManagementConfig,
1187}
1188
1189/// Encryption algorithms
1190#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1191pub enum EncryptionAlgorithm {
1192    /// AES-256
1193    AES256,
1194    /// ChaCha20-Poly1305
1195    ChaCha20Poly1305,
1196    /// XChaCha20-Poly1305
1197    XChaCha20Poly1305,
1198}
1199
1200/// Key management configuration
1201#[derive(Debug, Clone, Serialize, Deserialize)]
1202pub struct KeyManagementConfig {
1203    /// Key rotation frequency
1204    pub rotation_frequency: Duration,
1205    /// Key derivation function
1206    pub key_derivation: KeyDerivationFunction,
1207    /// Key storage backend
1208    pub storage_backend: KeyStorageBackend,
1209}
1210
1211/// Key derivation functions
1212#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1213pub enum KeyDerivationFunction {
1214    /// PBKDF2
1215    PBKDF2,
1216    /// Scrypt
1217    Scrypt,
1218    /// Argon2
1219    Argon2,
1220}
1221
1222/// Key storage backends
1223#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1224pub enum KeyStorageBackend {
1225    /// Local keystore
1226    Local,
1227    /// Hardware security module
1228    HSM,
1229    /// Cloud key management
1230    CloudKMS,
1231    /// Distributed keystore
1232    Distributed,
1233}
1234
1235/// Replication configuration
1236#[derive(Debug, Clone, Serialize, Deserialize)]
1237pub struct ReplicationConfig {
1238    /// Replication factor
1239    pub replication_factor: usize,
1240    /// Replication strategy
1241    pub strategy: ReplicationStrategy,
1242    /// Consistency level
1243    pub consistency_level: ConsistencyLevel,
1244}
1245
1246/// Replication strategies
1247#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1248pub enum ReplicationStrategy {
1249    /// Synchronous replication
1250    Synchronous,
1251    /// Asynchronous replication
1252    Asynchronous,
1253    /// Semi-synchronous replication
1254    SemiSynchronous,
1255    /// Multi-master replication
1256    MultiMaster,
1257}
1258
1259/// Consistency levels
1260#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1261pub enum ConsistencyLevel {
1262    /// Strong consistency
1263    Strong,
1264    /// Eventual consistency
1265    Eventual,
1266    /// Causal consistency
1267    Causal,
1268    /// Session consistency
1269    Session,
1270}
1271
1272/// Alerting configuration
1273#[derive(Debug, Clone, Serialize, Deserialize)]
1274pub struct AlertingConfig {
1275    /// Enable alerting
1276    pub enabled: bool,
1277    /// Alert rules
1278    pub rules: Vec<AlertRule>,
1279    /// Notification channels
1280    pub channels: Vec<NotificationChannel>,
1281    /// Alert aggregation
1282    pub aggregation: AlertAggregationConfig,
1283}
1284
1285/// Alert rule
1286#[derive(Debug, Clone, Serialize, Deserialize)]
1287pub struct AlertRule {
1288    /// Rule name
1289    pub name: String,
1290    /// Metric to monitor
1291    pub metric: MonitoringMetric,
1292    /// Threshold condition
1293    pub condition: ThresholdCondition,
1294    /// Alert severity
1295    pub severity: AlertSeverity,
1296    /// Evaluation frequency
1297    pub frequency: Duration,
1298}
1299
1300/// Threshold conditions
1301#[derive(Debug, Clone, Serialize, Deserialize)]
1302pub enum ThresholdCondition {
1303    /// Greater than threshold
1304    GreaterThan(f64),
1305    /// Less than threshold
1306    LessThan(f64),
1307    /// Equal to threshold
1308    EqualTo(f64),
1309    /// Within range
1310    WithinRange(f64, f64),
1311    /// Outside range
1312    OutsideRange(f64, f64),
1313}
1314
1315/// Alert severities
1316#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
1317pub enum AlertSeverity {
1318    /// Informational
1319    Info,
1320    /// Warning
1321    Warning,
1322    /// Error
1323    Error,
1324    /// Critical
1325    Critical,
1326}
1327
1328/// Notification channels
1329#[derive(Debug, Clone, Serialize, Deserialize)]
1330pub enum NotificationChannel {
1331    /// Email notification
1332    Email {
1333        recipients: Vec<String>,
1334        smtp_config: SmtpConfig,
1335    },
1336    /// Slack notification
1337    Slack {
1338        webhook_url: String,
1339        channel: String,
1340    },
1341    /// HTTP webhook
1342    Webhook {
1343        url: String,
1344        headers: HashMap<String, String>,
1345    },
1346    /// SMS notification
1347    SMS {
1348        phone_numbers: Vec<String>,
1349        provider_config: SmsProviderConfig,
1350    },
1351}
1352
1353/// SMTP configuration
1354#[derive(Debug, Clone, Serialize, Deserialize)]
1355pub struct SmtpConfig {
1356    /// SMTP server
1357    pub server: String,
1358    /// SMTP port
1359    pub port: u16,
1360    /// Username
1361    pub username: String,
1362    /// Use TLS
1363    pub use_tls: bool,
1364}
1365
1366/// SMS provider configuration
1367#[derive(Debug, Clone, Serialize, Deserialize)]
1368pub struct SmsProviderConfig {
1369    /// Provider name
1370    pub provider: String,
1371    /// API key
1372    pub api_key: String,
1373    /// API endpoint
1374    pub endpoint: String,
1375}
1376
1377/// Alert aggregation configuration
1378#[derive(Debug, Clone, Serialize, Deserialize)]
1379pub struct AlertAggregationConfig {
1380    /// Enable aggregation
1381    pub enabled: bool,
1382    /// Aggregation window
1383    pub window: Duration,
1384    /// Aggregation strategy
1385    pub strategy: AlertAggregationStrategy,
1386    /// Maximum alerts per window
1387    pub max_alerts_per_window: usize,
1388}
1389
1390/// Alert aggregation strategies
1391#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1392pub enum AlertAggregationStrategy {
1393    /// Count-based aggregation
1394    Count,
1395    /// Severity-based aggregation
1396    SeverityBased,
1397    /// Metric-based aggregation
1398    MetricBased,
1399    /// Time-based aggregation
1400    TimeBased,
1401}
1402
1403/// Reporting configuration
1404#[derive(Debug, Clone, Serialize, Deserialize)]
1405pub struct ReportingConfig {
1406    /// Enable automated reporting
1407    pub enabled: bool,
1408    /// Report types to generate
1409    pub report_types: Vec<ReportType>,
1410    /// Report frequency
1411    pub frequency: Duration,
1412    /// Report format
1413    pub format: ReportFormat,
1414    /// Report distribution
1415    pub distribution: ReportDistribution,
1416}
1417
1418/// Report types
1419#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1420pub enum ReportType {
1421    /// Performance report
1422    Performance,
1423    /// Resource utilization report
1424    ResourceUtilization,
1425    /// Quality metrics report
1426    QualityMetrics,
1427    /// Cost analysis report
1428    CostAnalysis,
1429    /// Capacity planning report
1430    CapacityPlanning,
1431    /// SLA compliance report
1432    SLACompliance,
1433}
1434
1435/// Report formats
1436#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1437pub enum ReportFormat {
1438    /// PDF format
1439    PDF,
1440    /// HTML format
1441    HTML,
1442    /// JSON format
1443    JSON,
1444    /// CSV format
1445    CSV,
1446    /// Excel format
1447    Excel,
1448}
1449
1450/// Report distribution
1451#[derive(Debug, Clone, Serialize, Deserialize)]
1452pub struct ReportDistribution {
1453    /// Email recipients
1454    pub email_recipients: Vec<String>,
1455    /// File system location
1456    pub file_location: Option<String>,
1457    /// Cloud storage location
1458    pub cloud_location: Option<String>,
1459    /// API endpoints
1460    pub api_endpoints: Vec<String>,
1461}
1462
1463impl Default for ParallelizationConfig {
1464    fn default() -> Self {
1465        Self {
1466            strategy: ParallelizationStrategy::Hybrid,
1467            resource_allocation: ResourceAllocationConfig::default(),
1468            scheduling_config: ParallelSchedulingConfig::default(),
1469            hardware_awareness: HardwareAwarenessConfig::default(),
1470            performance_config: PerformanceOptimizationConfig::default(),
1471            load_balancing: LoadBalancingConfig::default(),
1472            monitoring_config: ResourceMonitoringConfig::default(),
1473        }
1474    }
1475}
1476
1477impl Default for ResourceAllocationConfig {
1478    fn default() -> Self {
1479        Self {
1480            max_concurrent_circuits: PlatformCapabilities::detect().cpu.logical_cores,
1481            max_concurrent_gates: 16,
1482            cpu_allocation: CpuAllocationStrategy::PercentageCores(0.8),
1483            memory_limits: MemoryLimits::default(),
1484            qpu_allocation: QpuAllocationConfig::default(),
1485            network_allocation: NetworkAllocationConfig::default(),
1486        }
1487    }
1488}
1489
1490impl Default for MemoryLimits {
1491    fn default() -> Self {
1492        Self {
1493            max_total_memory_mb: 8192.0, // 8GB
1494            max_per_circuit_mb: 1024.0,  // 1GB
1495            allocation_strategy: MemoryAllocationStrategy::Dynamic,
1496            enable_pooling: true,
1497            gc_threshold: 0.8,
1498        }
1499    }
1500}
1501
1502impl Default for QpuAllocationConfig {
1503    fn default() -> Self {
1504        Self {
1505            max_qpu_time_per_circuit: Duration::from_secs(300), // 5 minutes
1506            sharing_strategy: QpuSharingStrategy::HybridSlicing,
1507            queue_management: QueueManagementConfig::default(),
1508            fairness_config: FairnessConfig::default(),
1509        }
1510    }
1511}
1512
1513impl Default for QueueManagementConfig {
1514    fn default() -> Self {
1515        Self {
1516            algorithm: QueueSchedulingAlgorithm::Priority,
1517            max_queue_size: 1000,
1518            priority_levels: 5,
1519            enable_preemption: true,
1520            timeout_config: TimeoutConfig::default(),
1521        }
1522    }
1523}
1524
1525impl Default for TimeoutConfig {
1526    fn default() -> Self {
1527        Self {
1528            execution_timeout: Duration::from_secs(3600), // 1 hour
1529            queue_timeout: Duration::from_secs(1800),     // 30 minutes
1530            resource_timeout: Duration::from_secs(300),   // 5 minutes
1531            adaptive_timeouts: true,
1532        }
1533    }
1534}
1535
1536impl Default for FairnessConfig {
1537    fn default() -> Self {
1538        Self {
1539            algorithm: FairnessAlgorithm::ProportionalFair,
1540            resource_quotas: ResourceQuotas::default(),
1541            aging_factor: 1.1,
1542            enable_burst_allowances: true,
1543        }
1544    }
1545}
1546
1547impl Default for ResourceQuotas {
1548    fn default() -> Self {
1549        Self {
1550            cpu_quota: Some(Duration::from_secs(3600 * 24)), // 24 hours per day
1551            qpu_quota: Some(Duration::from_secs(3600)),      // 1 hour per day
1552            memory_quota: Some(16384.0),                     // 16GB
1553            circuit_quota: Some(1000),                       // 1000 circuits per day
1554        }
1555    }
1556}
1557
1558impl Default for NetworkAllocationConfig {
1559    fn default() -> Self {
1560        Self {
1561            max_bandwidth_per_circuit: 100.0, // 100 Mbps
1562            qos_class: NetworkQoSClass::BestEffort,
1563            compression_config: CompressionConfig::default(),
1564            latency_optimization: true,
1565        }
1566    }
1567}
1568
1569impl Default for CompressionConfig {
1570    fn default() -> Self {
1571        Self {
1572            enabled: true,
1573            algorithm: CompressionAlgorithm::Zstd,
1574            level: 3,
1575            size_threshold: 1024, // 1KB
1576        }
1577    }
1578}
1579
1580impl Default for ParallelSchedulingConfig {
1581    fn default() -> Self {
1582        Self {
1583            algorithm: ParallelSchedulingAlgorithm::WorkStealing,
1584            work_stealing: WorkStealingConfig::default(),
1585            load_balancing_params: LoadBalancingParams::default(),
1586            thread_pool_config: ThreadPoolConfig::default(),
1587        }
1588    }
1589}
1590
1591impl Default for WorkStealingConfig {
1592    fn default() -> Self {
1593        Self {
1594            enabled: true,
1595            strategy: WorkStealingStrategy::LoadBased,
1596            queue_size: 1000,
1597            stealing_threshold: 0.5,
1598        }
1599    }
1600}
1601
1602impl Default for LoadBalancingParams {
1603    fn default() -> Self {
1604        Self {
1605            rebalancing_frequency: Duration::from_secs(30),
1606            load_threshold: 0.8,
1607            migration_cost_factor: 0.1,
1608            adaptive_balancing: true,
1609        }
1610    }
1611}
1612
1613impl Default for ThreadPoolConfig {
1614    fn default() -> Self {
1615        Self {
1616            core_threads: PlatformCapabilities::detect().cpu.logical_cores,
1617            max_threads: PlatformCapabilities::detect().cpu.logical_cores * 2,
1618            keep_alive_time: Duration::from_secs(60),
1619            thread_priority: ThreadPriority::Normal,
1620            affinity_config: ThreadAffinityConfig::default(),
1621        }
1622    }
1623}
1624
1625impl Default for ThreadAffinityConfig {
1626    fn default() -> Self {
1627        Self {
1628            enabled: false,
1629            assignment_strategy: CoreAssignmentStrategy::Automatic,
1630            numa_preference: NumaPreference::None,
1631        }
1632    }
1633}
1634
1635impl Default for HardwareAwarenessConfig {
1636    fn default() -> Self {
1637        Self {
1638            topology_awareness: TopologyAwarenessLevel::Connectivity,
1639            calibration_integration: CalibrationIntegrationConfig::default(),
1640            error_rate_config: ErrorRateConfig::default(),
1641            connectivity_config: ConnectivityConfig::default(),
1642            resource_tracking: ResourceTrackingConfig::default(),
1643        }
1644    }
1645}
1646
1647impl Default for CalibrationIntegrationConfig {
1648    fn default() -> Self {
1649        Self {
1650            use_realtime_calibration: true,
1651            update_frequency: Duration::from_secs(300),
1652            quality_threshold: 0.95,
1653            enable_predictive: true,
1654        }
1655    }
1656}
1657
1658impl Default for ErrorRateConfig {
1659    fn default() -> Self {
1660        Self {
1661            consider_error_rates: true,
1662            error_threshold: 0.01,
1663            mitigation_strategy: ErrorMitigationStrategy::Composite,
1664            prediction_model: ErrorPredictionModel::MachineLearning,
1665        }
1666    }
1667}
1668
1669impl Default for ConnectivityConfig {
1670    fn default() -> Self {
1671        Self {
1672            enforce_constraints: true,
1673            swap_strategy: SwapInsertionStrategy::Lookahead,
1674            routing_preference: RoutingPreference::QualityAware,
1675            optimization_config: ConnectivityOptimizationConfig::default(),
1676        }
1677    }
1678}
1679
1680impl Default for ConnectivityOptimizationConfig {
1681    fn default() -> Self {
1682        Self {
1683            enable_parallel_routing: true,
1684            optimization_level: OptimizationLevel::Moderate,
1685            use_ml_routing: true,
1686            precompute_tables: true,
1687        }
1688    }
1689}
1690
1691impl Default for ResourceTrackingConfig {
1692    fn default() -> Self {
1693        Self {
1694            track_cpu_usage: true,
1695            track_memory_usage: true,
1696            track_qpu_usage: true,
1697            track_network_usage: true,
1698            tracking_granularity: TrackingGranularity::Medium,
1699            reporting_frequency: Duration::from_secs(60),
1700        }
1701    }
1702}
1703
1704impl Default for PerformanceOptimizationConfig {
1705    fn default() -> Self {
1706        Self {
1707            objectives: vec![OptimizationObjective::Balanced],
1708            caching_config: CachingConfig::default(),
1709            prefetching_config: PrefetchingConfig::default(),
1710            batch_config: BatchProcessingConfig::default(),
1711            adaptive_config: AdaptiveOptimizationConfig::default(),
1712        }
1713    }
1714}
1715
1716impl Default for CachingConfig {
1717    fn default() -> Self {
1718        Self {
1719            enable_result_caching: true,
1720            enable_compilation_caching: true,
1721            size_limits: CacheSizeLimits::default(),
1722            eviction_policy: CacheEvictionPolicy::LRU,
1723            warming_strategies: vec![CacheWarmingStrategy::PreloadCommon],
1724        }
1725    }
1726}
1727
1728impl Default for CacheSizeLimits {
1729    fn default() -> Self {
1730        Self {
1731            max_entries: 10000,
1732            max_memory_mb: 1024.0,
1733            max_disk_mb: 5120.0,
1734            per_user_limits: None,
1735        }
1736    }
1737}
1738
1739impl Default for PrefetchingConfig {
1740    fn default() -> Self {
1741        Self {
1742            enabled: true,
1743            strategy: PrefetchingStrategy::Adaptive,
1744            prefetch_distance: 3,
1745            confidence_threshold: 0.7,
1746        }
1747    }
1748}
1749
1750impl Default for BatchProcessingConfig {
1751    fn default() -> Self {
1752        Self {
1753            enabled: true,
1754            size_limits: BatchSizeLimits::default(),
1755            strategy: BatchingStrategy::Adaptive,
1756            timeout: Duration::from_secs(30),
1757        }
1758    }
1759}
1760
1761impl Default for BatchSizeLimits {
1762    fn default() -> Self {
1763        Self {
1764            min_size: 1,
1765            max_size: 100,
1766            optimal_size: 10,
1767            dynamic_sizing: true,
1768        }
1769    }
1770}
1771
1772impl Default for AdaptiveOptimizationConfig {
1773    fn default() -> Self {
1774        Self {
1775            enabled: true,
1776            adaptation_frequency: Duration::from_secs(300),
1777            monitoring_window: Duration::from_secs(900),
1778            sensitivity: 0.1,
1779            ml_config: AdaptiveMLConfig::default(),
1780        }
1781    }
1782}
1783
1784impl Default for AdaptiveMLConfig {
1785    fn default() -> Self {
1786        Self {
1787            enabled: true,
1788            model_type: MLModelType::RandomForest,
1789            training_frequency: Duration::from_secs(3600),
1790            feature_config: FeatureEngineeringConfig::default(),
1791        }
1792    }
1793}
1794
1795impl Default for FeatureEngineeringConfig {
1796    fn default() -> Self {
1797        Self {
1798            circuit_features: vec![
1799                CircuitFeature::QubitCount,
1800                CircuitFeature::Depth,
1801                CircuitFeature::GateCount,
1802            ],
1803            hardware_features: vec![
1804                HardwareFeature::AvailableQubits,
1805                HardwareFeature::ErrorRates,
1806                HardwareFeature::QueueStatus,
1807            ],
1808            performance_features: vec![
1809                PerformanceFeature::ExecutionTime,
1810                PerformanceFeature::Throughput,
1811                PerformanceFeature::ResourceEfficiency,
1812            ],
1813            normalization: FeatureNormalization::ZScore,
1814        }
1815    }
1816}
1817
1818impl Default for LoadBalancingConfig {
1819    fn default() -> Self {
1820        Self {
1821            algorithm: LoadBalancingAlgorithm::ResourceBased,
1822            monitoring: LoadMonitoringConfig::default(),
1823            rebalancing_triggers: RebalancingTriggers::default(),
1824            migration_policies: MigrationPolicies::default(),
1825        }
1826    }
1827}
1828
1829impl Default for LoadMonitoringConfig {
1830    fn default() -> Self {
1831        Self {
1832            frequency: Duration::from_secs(30),
1833            metrics: vec![
1834                LoadMetric::CpuUtilization,
1835                LoadMetric::MemoryUtilization,
1836                LoadMetric::QpuUtilization,
1837                LoadMetric::QueueLength,
1838            ],
1839            thresholds: LoadThresholds::default(),
1840            retention_period: Duration::from_secs(3600 * 24),
1841        }
1842    }
1843}
1844
1845impl Default for LoadThresholds {
1846    fn default() -> Self {
1847        Self {
1848            cpu_threshold: 0.8,
1849            memory_threshold: 0.85,
1850            qpu_threshold: 0.9,
1851            network_threshold: 0.8,
1852            queue_threshold: 100,
1853            response_time_threshold: Duration::from_secs(30),
1854        }
1855    }
1856}
1857
1858impl Default for RebalancingTriggers {
1859    fn default() -> Self {
1860        Self {
1861            cpu_imbalance_threshold: 0.3,
1862            memory_imbalance_threshold: 0.3,
1863            queue_imbalance_threshold: 0.4,
1864            time_interval: Some(Duration::from_secs(300)),
1865            event_triggers: vec![
1866                RebalancingEvent::NodeFailure,
1867                RebalancingEvent::LoadSpike,
1868                RebalancingEvent::PerformanceDegradation,
1869            ],
1870        }
1871    }
1872}
1873
1874impl Default for MigrationPolicies {
1875    fn default() -> Self {
1876        Self {
1877            cost_threshold: 0.1,
1878            max_migrations_per_period: 10,
1879            migration_period: Duration::from_secs(3600),
1880            circuit_migration_strategy: CircuitMigrationStrategy::CheckpointRestart,
1881            data_migration_strategy: DataMigrationStrategy::Copy,
1882        }
1883    }
1884}
1885
1886impl Default for ResourceMonitoringConfig {
1887    fn default() -> Self {
1888        Self {
1889            real_time_monitoring: true,
1890            granularity: MonitoringGranularity::Circuit,
1891            metrics_collection: MetricsCollectionConfig::default(),
1892            alerting: AlertingConfig::default(),
1893            reporting: ReportingConfig::default(),
1894        }
1895    }
1896}
1897
1898impl Default for MetricsCollectionConfig {
1899    fn default() -> Self {
1900        Self {
1901            frequency: Duration::from_secs(60),
1902            metrics: vec![
1903                MonitoringMetric::ResourceUtilization,
1904                MonitoringMetric::Performance,
1905                MonitoringMetric::Quality,
1906            ],
1907            retention_policy: RetentionPolicy::default(),
1908            storage_config: StorageConfig::default(),
1909        }
1910    }
1911}
1912
1913impl Default for RetentionPolicy {
1914    fn default() -> Self {
1915        Self {
1916            raw_data_retention: Duration::from_secs(3600 * 24 * 7), // 1 week
1917            aggregated_data_retention: Duration::from_secs(3600 * 24 * 30), // 1 month
1918            archive_policy: ArchivePolicy::TimeBased(Duration::from_secs(3600 * 24 * 365)), // 1 year
1919            compression: CompressionConfig::default(),
1920        }
1921    }
1922}
1923
1924impl Default for StorageConfig {
1925    fn default() -> Self {
1926        Self {
1927            backend: StorageBackend::LocalFilesystem,
1928            location: "/tmp/quantrs_metrics".to_string(),
1929            encryption: EncryptionConfig::default(),
1930            replication: ReplicationConfig::default(),
1931        }
1932    }
1933}
1934
1935impl Default for EncryptionConfig {
1936    fn default() -> Self {
1937        Self {
1938            enabled: true,
1939            algorithm: EncryptionAlgorithm::AES256,
1940            key_management: KeyManagementConfig::default(),
1941        }
1942    }
1943}
1944
1945impl Default for KeyManagementConfig {
1946    fn default() -> Self {
1947        Self {
1948            rotation_frequency: Duration::from_secs(3600 * 24 * 30), // 1 month
1949            key_derivation: KeyDerivationFunction::Argon2,
1950            storage_backend: KeyStorageBackend::Local,
1951        }
1952    }
1953}
1954
1955impl Default for ReplicationConfig {
1956    fn default() -> Self {
1957        Self {
1958            replication_factor: 1,
1959            strategy: ReplicationStrategy::Synchronous,
1960            consistency_level: ConsistencyLevel::Strong,
1961        }
1962    }
1963}
1964
1965impl Default for AlertingConfig {
1966    fn default() -> Self {
1967        Self {
1968            enabled: true,
1969            rules: vec![],
1970            channels: vec![],
1971            aggregation: AlertAggregationConfig::default(),
1972        }
1973    }
1974}
1975
1976impl Default for AlertAggregationConfig {
1977    fn default() -> Self {
1978        Self {
1979            enabled: true,
1980            window: Duration::from_secs(300),
1981            strategy: AlertAggregationStrategy::SeverityBased,
1982            max_alerts_per_window: 10,
1983        }
1984    }
1985}
1986
1987impl Default for ReportingConfig {
1988    fn default() -> Self {
1989        Self {
1990            enabled: true,
1991            report_types: vec![ReportType::Performance, ReportType::ResourceUtilization],
1992            frequency: Duration::from_secs(3600 * 24), // Daily reports
1993            format: ReportFormat::JSON,
1994            distribution: ReportDistribution::default(),
1995        }
1996    }
1997}
1998
1999impl Default for ReportDistribution {
2000    fn default() -> Self {
2001        Self {
2002            email_recipients: vec![],
2003            file_location: Some("/tmp/quantrs_reports".to_string()),
2004            cloud_location: None,
2005            api_endpoints: vec![],
2006        }
2007    }
2008}
2009
2010/// Main hardware-aware parallelization engine
2011pub struct HardwareParallelizationEngine {
2012    config: ParallelizationConfig,
2013    device_manager: Arc<RwLock<IntegratedQuantumDeviceManager>>,
2014    calibration_manager: Arc<RwLock<CalibrationManager>>,
2015    router: Arc<RwLock<AdvancedQubitRouter>>,
2016    // Execution pools
2017    circuit_pool: Arc<AsyncMutex<VecDeque<ParallelCircuitTask>>>,
2018    gate_pool: Arc<AsyncMutex<VecDeque<ParallelGateTask>>>,
2019    // Resource tracking
2020    resource_monitor: Arc<RwLock<ResourceMonitor>>,
2021    // Performance tracking
2022    performance_tracker: Arc<RwLock<PerformanceTracker>>,
2023    // Load balancer
2024    load_balancer: Arc<RwLock<LoadBalancer>>,
2025    // Semaphores for resource control
2026    circuit_semaphore: Arc<Semaphore>,
2027    gate_semaphore: Arc<Semaphore>,
2028    memory_semaphore: Arc<Semaphore>,
2029}
2030
2031/// Parallel circuit execution task
2032#[derive(Debug)]
2033pub struct ParallelCircuitTask {
2034    pub id: String,
2035    pub circuit: Box<dyn std::any::Any + Send + Sync>,
2036    pub target_backend: HardwareBackend,
2037    pub priority: TaskPriority,
2038    pub resource_requirements: ParallelResourceRequirements,
2039    pub constraints: ExecutionConstraints,
2040    pub submitted_at: SystemTime,
2041    pub deadline: Option<SystemTime>,
2042}
2043
2044/// Parallel gate execution task
2045#[derive(Debug, Clone)]
2046pub struct ParallelGateTask {
2047    pub id: String,
2048    pub gate_operations: Vec<ParallelGateOperation>,
2049    pub target_qubits: Vec<QubitId>,
2050    pub dependency_graph: HashMap<String, Vec<String>>,
2051    pub priority: TaskPriority,
2052    pub submitted_at: SystemTime,
2053}
2054
2055/// Task priorities
2056#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
2057pub enum TaskPriority {
2058    /// Low priority (best effort)
2059    Low,
2060    /// Normal priority
2061    Normal,
2062    /// High priority
2063    High,
2064    /// Critical priority (real-time)
2065    Critical,
2066    /// System priority (internal operations)
2067    System,
2068}
2069
2070/// Parallel resource requirements
2071#[derive(Debug, Clone, Serialize, Deserialize)]
2072pub struct ParallelResourceRequirements {
2073    /// Required CPU cores
2074    pub required_cpu_cores: usize,
2075    /// Required memory (MB)
2076    pub required_memory_mb: f64,
2077    /// Required QPU time
2078    pub required_qpu_time: Duration,
2079    /// Required network bandwidth (Mbps)
2080    pub required_bandwidth_mbps: f64,
2081    /// Required storage (MB)
2082    pub required_storage_mb: f64,
2083}
2084
2085/// Execution constraints
2086#[derive(Debug, Clone, Serialize, Deserialize)]
2087pub struct ExecutionConstraints {
2088    /// Allowed backends
2089    pub allowed_backends: Vec<HardwareBackend>,
2090    /// Forbidden backends
2091    pub forbidden_backends: Vec<HardwareBackend>,
2092    /// Quality requirements
2093    pub quality_requirements: QualityRequirements,
2094    /// Timing constraints
2095    pub timing_constraints: TimingConstraints,
2096    /// Resource constraints
2097    pub resource_constraints: ResourceConstraints,
2098}
2099
2100/// Quality requirements
2101#[derive(Debug, Clone, Serialize, Deserialize)]
2102pub struct QualityRequirements {
2103    /// Minimum fidelity
2104    pub min_fidelity: Option<f64>,
2105    /// Maximum error rate
2106    pub max_error_rate: Option<f64>,
2107    /// Required calibration recency
2108    pub calibration_recency: Option<Duration>,
2109    /// Quality assessment method
2110    pub assessment_method: QualityAssessmentMethod,
2111}
2112
2113/// Quality assessment methods
2114#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2115pub enum QualityAssessmentMethod {
2116    /// Static quality metrics
2117    Static,
2118    /// Dynamic quality monitoring
2119    Dynamic,
2120    /// Predictive quality modeling
2121    Predictive,
2122    /// Benchmarking-based assessment
2123    BenchmarkBased,
2124}
2125
2126/// Timing constraints
2127#[derive(Debug, Clone, Serialize, Deserialize)]
2128pub struct TimingConstraints {
2129    /// Maximum execution time
2130    pub max_execution_time: Option<Duration>,
2131    /// Maximum queue wait time
2132    pub max_queue_time: Option<Duration>,
2133    /// Preferred execution window
2134    pub preferred_window: Option<(SystemTime, SystemTime)>,
2135    /// Scheduling flexibility
2136    pub scheduling_flexibility: SchedulingFlexibility,
2137}
2138
2139/// Scheduling flexibility levels
2140#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2141pub enum SchedulingFlexibility {
2142    /// Rigid scheduling (exact timing required)
2143    Rigid,
2144    /// Flexible scheduling (best effort)
2145    Flexible,
2146    /// Adaptive scheduling (can adjust based on conditions)
2147    Adaptive,
2148}
2149
2150/// Resource constraints
2151#[derive(Debug, Clone, Serialize, Deserialize)]
2152pub struct ResourceConstraints {
2153    /// Maximum cost
2154    pub max_cost: Option<f64>,
2155    /// Maximum energy consumption
2156    pub max_energy: Option<f64>,
2157    /// Resource usage limits
2158    pub usage_limits: HashMap<String, f64>,
2159    /// Sharing preferences
2160    pub sharing_preferences: SharingPreferences,
2161}
2162
2163/// Sharing preferences
2164#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2165pub enum SharingPreferences {
2166    /// Exclusive resource access
2167    Exclusive,
2168    /// Shared resource access
2169    Shared,
2170    /// Best effort sharing
2171    BestEffort,
2172    /// Conditional sharing
2173    Conditional(Vec<SharingCondition>),
2174}
2175
2176/// Sharing conditions
2177#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2178pub enum SharingCondition {
2179    /// Share only with specific users
2180    UserWhitelist(Vec<String>),
2181    /// Share only with specific circuit types
2182    CircuitTypeWhitelist(Vec<String>),
2183    /// Share only during specific time windows
2184    TimeWindow(SystemTime, SystemTime),
2185    /// Share only below resource threshold
2186    ResourceThreshold(String, f64),
2187}
2188
2189/// Parallel gate operation
2190#[derive(Debug, Clone, Serialize, Deserialize)]
2191pub struct ParallelGateOperation {
2192    /// Operation ID
2193    pub id: String,
2194    /// Gate type
2195    pub gate_type: String,
2196    /// Target qubits
2197    pub qubits: Vec<QubitId>,
2198    /// Gate parameters
2199    pub parameters: Vec<f64>,
2200    /// Dependencies on other operations
2201    pub dependencies: Vec<String>,
2202    /// Parallelization hints
2203    pub parallelization_hints: ParallelizationHints,
2204}
2205
2206/// Parallelization hints
2207#[derive(Debug, Clone, Serialize, Deserialize)]
2208pub struct ParallelizationHints {
2209    /// Can be executed in parallel with others
2210    pub parallel_safe: bool,
2211    /// Preferred execution order
2212    pub execution_order: Option<usize>,
2213    /// Resource affinity
2214    pub resource_affinity: ResourceAffinity,
2215    /// Scheduling hints
2216    pub scheduling_hints: SchedulingHints,
2217}
2218
2219/// Resource affinity
2220#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2221pub enum ResourceAffinity {
2222    /// No preference
2223    None,
2224    /// Prefer specific backend
2225    Backend(HardwareBackend),
2226    /// Prefer specific qubits
2227    Qubits(Vec<QubitId>),
2228    /// Prefer co-location with other operations
2229    CoLocation(Vec<String>),
2230}
2231
2232/// Scheduling hints
2233#[derive(Debug, Clone, Serialize, Deserialize)]
2234pub struct SchedulingHints {
2235    /// Preferred execution time
2236    pub preferred_time: Option<SystemTime>,
2237    /// Execution priority
2238    pub priority: TaskPriority,
2239    /// Deadline
2240    pub deadline: Option<SystemTime>,
2241    /// Batch compatibility
2242    pub batch_compatible: bool,
2243}
2244
2245/// Resource monitor for tracking system resources
2246pub struct ResourceMonitor {
2247    cpu_usage: HashMap<usize, f64>,
2248    memory_usage: f64,
2249    qpu_usage: HashMap<HardwareBackend, f64>,
2250    network_usage: f64,
2251    storage_usage: f64,
2252    monitoring_start_time: SystemTime,
2253    last_update: SystemTime,
2254}
2255
2256/// Performance tracker for optimization
2257pub struct PerformanceTracker {
2258    execution_history: VecDeque<ExecutionRecord>,
2259    performance_metrics: PerformanceMetrics,
2260    optimization_suggestions: Vec<OptimizationSuggestion>,
2261    baseline_metrics: Option<PerformanceMetrics>,
2262}
2263
2264/// Execution record
2265#[derive(Debug, Clone, Serialize, Deserialize)]
2266pub struct ExecutionRecord {
2267    pub task_id: String,
2268    pub task_type: TaskType,
2269    pub execution_time: Duration,
2270    pub resource_usage: ResourceUsage,
2271    pub quality_metrics: ExecutionQualityMetrics,
2272    pub timestamp: SystemTime,
2273    pub backend: HardwareBackend,
2274}
2275
2276/// Task types
2277#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2278pub enum TaskType {
2279    /// Circuit-level task
2280    Circuit,
2281    /// Gate-level task
2282    Gate,
2283    /// Batch task
2284    Batch,
2285    /// System task
2286    System,
2287}
2288
2289/// Resource usage metrics
2290#[derive(Debug, Clone, Serialize, Deserialize)]
2291pub struct ResourceUsage {
2292    pub cpu_usage: f64,
2293    pub memory_usage: f64,
2294    pub qpu_usage: f64,
2295    pub network_usage: f64,
2296    pub storage_usage: f64,
2297    pub energy_consumption: f64,
2298}
2299
2300/// Execution quality metrics
2301#[derive(Debug, Clone, Serialize, Deserialize)]
2302pub struct ExecutionQualityMetrics {
2303    pub fidelity: Option<f64>,
2304    pub error_rate: Option<f64>,
2305    pub success_rate: f64,
2306    pub calibration_quality: Option<f64>,
2307    pub result_consistency: Option<f64>,
2308}
2309
2310/// Performance metrics
2311#[derive(Debug, Clone, Serialize, Deserialize)]
2312pub struct PerformanceMetrics {
2313    pub throughput: f64,          // circuits per second
2314    pub latency: Duration,        // average execution time
2315    pub resource_efficiency: f64, // 0.0 to 1.0
2316    pub quality_score: f64,       // 0.0 to 1.0
2317    pub cost_efficiency: f64,     // performance per cost unit
2318    pub energy_efficiency: f64,   // performance per energy unit
2319}
2320
2321/// Optimization suggestion
2322#[derive(Debug, Clone, Serialize, Deserialize)]
2323pub struct OptimizationSuggestion {
2324    pub category: OptimizationCategory,
2325    pub description: String,
2326    pub expected_improvement: f64,
2327    pub implementation_cost: f64,
2328    pub priority: SuggestionPriority,
2329    pub applicable_conditions: Vec<String>,
2330}
2331
2332/// Optimization categories
2333#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2334pub enum OptimizationCategory {
2335    /// Resource allocation optimization
2336    ResourceAllocation,
2337    /// Scheduling optimization
2338    Scheduling,
2339    /// Load balancing optimization
2340    LoadBalancing,
2341    /// Caching optimization
2342    Caching,
2343    /// Network optimization
2344    Network,
2345    /// Hardware utilization optimization
2346    HardwareUtilization,
2347}
2348
2349/// Suggestion priorities
2350#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
2351pub enum SuggestionPriority {
2352    /// Low priority suggestion
2353    Low,
2354    /// Medium priority suggestion
2355    Medium,
2356    /// High priority suggestion
2357    High,
2358    /// Critical priority suggestion
2359    Critical,
2360}
2361
2362/// Load balancer for distributing work
2363pub struct LoadBalancer {
2364    algorithm: LoadBalancingAlgorithm,
2365    backend_loads: HashMap<HardwareBackend, LoadMetrics>,
2366    load_history: VecDeque<LoadSnapshot>,
2367    rebalancing_strategy: RebalancingStrategy,
2368    migration_tracker: MigrationTracker,
2369}
2370
2371/// Load metrics for a backend
2372#[derive(Debug, Clone, Serialize, Deserialize)]
2373pub struct LoadMetrics {
2374    pub cpu_load: f64,
2375    pub memory_load: f64,
2376    pub qpu_load: f64,
2377    pub network_load: f64,
2378    pub queue_length: usize,
2379    pub response_time: Duration,
2380    pub throughput: f64,
2381    pub error_rate: f64,
2382    pub last_updated: SystemTime,
2383}
2384
2385/// Load snapshot for historical tracking
2386#[derive(Debug, Clone, Serialize, Deserialize)]
2387pub struct LoadSnapshot {
2388    pub timestamp: SystemTime,
2389    pub backend_loads: HashMap<HardwareBackend, LoadMetrics>,
2390    pub system_metrics: SystemMetrics,
2391    pub predictions: LoadPredictions,
2392}
2393
2394/// System-wide metrics
2395#[derive(Debug, Clone, Serialize, Deserialize)]
2396pub struct SystemMetrics {
2397    pub total_throughput: f64,
2398    pub average_latency: Duration,
2399    pub total_resource_utilization: f64,
2400    pub overall_quality_score: f64,
2401    pub cost_per_operation: f64,
2402    pub energy_per_operation: f64,
2403}
2404
2405/// Load predictions
2406#[derive(Debug, Clone, Serialize, Deserialize)]
2407pub struct LoadPredictions {
2408    pub predicted_loads: HashMap<HardwareBackend, f64>,
2409    pub confidence_levels: HashMap<HardwareBackend, f64>,
2410    pub prediction_horizon: Duration,
2411    pub model_accuracy: f64,
2412}
2413
2414/// Rebalancing strategy
2415#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2416pub enum RebalancingStrategy {
2417    /// Reactive rebalancing
2418    Reactive,
2419    /// Proactive rebalancing
2420    Proactive,
2421    /// Predictive rebalancing
2422    Predictive,
2423    /// Hybrid approach
2424    Hybrid,
2425}
2426
2427/// Migration tracker
2428pub struct MigrationTracker {
2429    active_migrations: HashMap<String, MigrationStatus>,
2430    migration_history: VecDeque<MigrationRecord>,
2431    migration_costs: HashMap<(HardwareBackend, HardwareBackend), f64>,
2432}
2433
2434/// Migration status
2435#[derive(Debug, Clone, Serialize, Deserialize)]
2436pub struct MigrationStatus {
2437    pub task_id: String,
2438    pub source_backend: HardwareBackend,
2439    pub target_backend: HardwareBackend,
2440    pub progress: f64, // 0.0 to 1.0
2441    pub started_at: SystemTime,
2442    pub estimated_completion: SystemTime,
2443    pub migration_type: MigrationType,
2444}
2445
2446/// Migration types
2447#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2448pub enum MigrationType {
2449    /// Circuit migration
2450    Circuit,
2451    /// Data migration
2452    Data,
2453    /// State migration
2454    State,
2455    /// Full migration
2456    Full,
2457}
2458
2459/// Migration record for tracking history
2460#[derive(Debug, Clone, Serialize, Deserialize)]
2461pub struct MigrationRecord {
2462    pub task_id: String,
2463    pub source_backend: HardwareBackend,
2464    pub target_backend: HardwareBackend,
2465    pub migration_time: Duration,
2466    pub success: bool,
2467    pub cost: f64,
2468    pub quality_impact: f64,
2469    pub timestamp: SystemTime,
2470}
2471
2472impl HardwareParallelizationEngine {
2473    /// Create a new hardware parallelization engine
2474    pub fn new(
2475        config: ParallelizationConfig,
2476        device_manager: Arc<RwLock<IntegratedQuantumDeviceManager>>,
2477        calibration_manager: Arc<RwLock<CalibrationManager>>,
2478        router: Arc<RwLock<AdvancedQubitRouter>>,
2479    ) -> Self {
2480        let circuit_semaphore = Arc::new(Semaphore::new(
2481            config.resource_allocation.max_concurrent_circuits,
2482        ));
2483        let gate_semaphore = Arc::new(Semaphore::new(
2484            config.resource_allocation.max_concurrent_gates,
2485        ));
2486        let memory_semaphore = Arc::new(Semaphore::new(
2487            (config.resource_allocation.memory_limits.max_total_memory_mb
2488                / config.resource_allocation.memory_limits.max_per_circuit_mb) as usize,
2489        ));
2490
2491        Self {
2492            config: config.clone(),
2493            device_manager,
2494            calibration_manager,
2495            router,
2496            circuit_pool: Arc::new(AsyncMutex::new(VecDeque::new())),
2497            gate_pool: Arc::new(AsyncMutex::new(VecDeque::new())),
2498            resource_monitor: Arc::new(RwLock::new(ResourceMonitor::new())),
2499            performance_tracker: Arc::new(RwLock::new(PerformanceTracker::new())),
2500            load_balancer: Arc::new(RwLock::new(LoadBalancer::new(
2501                config.load_balancing.algorithm.clone(),
2502            ))),
2503            circuit_semaphore,
2504            gate_semaphore,
2505            memory_semaphore,
2506        }
2507    }
2508
2509    /// Submit a circuit for parallel execution
2510    pub async fn submit_parallel_circuit<const N: usize>(
2511        &self,
2512        circuit: Circuit<N>,
2513        target_backend: HardwareBackend,
2514        priority: TaskPriority,
2515        constraints: ExecutionConstraints,
2516    ) -> DeviceResult<String> {
2517        let task_id = uuid::Uuid::new_v4().to_string();
2518
2519        // Calculate resource requirements
2520        let resource_requirements =
2521            self.calculate_resource_requirements(&circuit, &target_backend)?;
2522
2523        // Create parallel task
2524        let task = ParallelCircuitTask {
2525            id: task_id.clone(),
2526            circuit: Box::new(circuit),
2527            target_backend,
2528            priority,
2529            resource_requirements,
2530            constraints,
2531            submitted_at: SystemTime::now(),
2532            deadline: None, // Will be set based on constraints
2533        };
2534
2535        // Add to circuit pool
2536        {
2537            let mut pool = self.circuit_pool.lock().await;
2538            pool.push_back(task);
2539        }
2540
2541        // Trigger scheduling
2542        self.schedule_circuits().await?;
2543
2544        Ok(task_id)
2545    }
2546
2547    /// Submit gates for parallel execution
2548    pub async fn submit_parallel_gates(
2549        &self,
2550        gate_operations: Vec<ParallelGateOperation>,
2551        target_qubits: Vec<QubitId>,
2552        priority: TaskPriority,
2553    ) -> DeviceResult<String> {
2554        let task_id = uuid::Uuid::new_v4().to_string();
2555
2556        // Build dependency graph
2557        let dependency_graph = self.build_dependency_graph(&gate_operations)?;
2558
2559        // Create parallel gate task
2560        let task = ParallelGateTask {
2561            id: task_id.clone(),
2562            gate_operations,
2563            target_qubits,
2564            dependency_graph,
2565            priority,
2566            submitted_at: SystemTime::now(),
2567        };
2568
2569        // Add to gate pool
2570        {
2571            let mut pool = self.gate_pool.lock().await;
2572            pool.push_back(task);
2573        }
2574
2575        // Trigger gate scheduling
2576        self.schedule_gates().await?;
2577
2578        Ok(task_id)
2579    }
2580
2581    /// Execute parallel circuits using the configured strategy
2582    pub async fn execute_parallel_circuits(&self) -> DeviceResult<Vec<ParallelExecutionResult>> {
2583        match self.config.strategy {
2584            ParallelizationStrategy::CircuitLevel => {
2585                self.execute_circuit_level_parallelization().await
2586            }
2587            ParallelizationStrategy::GateLevel => self.execute_gate_level_parallelization().await,
2588            ParallelizationStrategy::Hybrid => self.execute_hybrid_parallelization().await,
2589            ParallelizationStrategy::TopologyAware => {
2590                self.execute_topology_aware_parallelization().await
2591            }
2592            ParallelizationStrategy::ResourceConstrained => {
2593                self.execute_resource_constrained_parallelization().await
2594            }
2595            ParallelizationStrategy::SciRS2Optimized => {
2596                self.execute_scirs2_optimized_parallelization().await
2597            }
2598            ParallelizationStrategy::Custom { .. } => self.execute_custom_parallelization().await,
2599        }
2600    }
2601
2602    /// Get current performance metrics
2603    pub async fn get_performance_metrics(&self) -> DeviceResult<PerformanceMetrics> {
2604        let tracker = self.performance_tracker.read().unwrap();
2605        Ok(tracker.performance_metrics.clone())
2606    }
2607
2608    /// Get optimization suggestions
2609    pub async fn get_optimization_suggestions(&self) -> DeviceResult<Vec<OptimizationSuggestion>> {
2610        let tracker = self.performance_tracker.read().unwrap();
2611        Ok(tracker.optimization_suggestions.clone())
2612    }
2613
2614    /// Apply dynamic load balancing
2615    pub async fn apply_load_balancing(&self) -> DeviceResult<LoadBalancingResult> {
2616        let mut balancer = self.load_balancer.write().unwrap();
2617        balancer.rebalance_loads().await
2618    }
2619
2620    // Private implementation methods...
2621
2622    async fn schedule_circuits(&self) -> DeviceResult<()> {
2623        // Implementation for circuit scheduling
2624        Ok(())
2625    }
2626
2627    async fn schedule_gates(&self) -> DeviceResult<()> {
2628        // Implementation for gate scheduling
2629        Ok(())
2630    }
2631
2632    fn calculate_resource_requirements<const N: usize>(
2633        &self,
2634        circuit: &Circuit<N>,
2635        backend: &HardwareBackend,
2636    ) -> DeviceResult<ParallelResourceRequirements> {
2637        // Implementation for resource requirement calculation
2638        Ok(ParallelResourceRequirements {
2639            required_cpu_cores: 1,
2640            required_memory_mb: 512.0,
2641            required_qpu_time: Duration::from_secs(60),
2642            required_bandwidth_mbps: 10.0,
2643            required_storage_mb: 100.0,
2644        })
2645    }
2646
2647    fn build_dependency_graph(
2648        &self,
2649        operations: &[ParallelGateOperation],
2650    ) -> DeviceResult<HashMap<String, Vec<String>>> {
2651        // Implementation for dependency graph building
2652        Ok(HashMap::new())
2653    }
2654
2655    async fn execute_circuit_level_parallelization(
2656        &self,
2657    ) -> DeviceResult<Vec<ParallelExecutionResult>> {
2658        // Implementation for circuit-level parallelization
2659        Ok(vec![])
2660    }
2661
2662    async fn execute_gate_level_parallelization(
2663        &self,
2664    ) -> DeviceResult<Vec<ParallelExecutionResult>> {
2665        // Implementation for gate-level parallelization
2666        Ok(vec![])
2667    }
2668
2669    async fn execute_hybrid_parallelization(&self) -> DeviceResult<Vec<ParallelExecutionResult>> {
2670        // Implementation for hybrid parallelization
2671        Ok(vec![])
2672    }
2673
2674    async fn execute_topology_aware_parallelization(
2675        &self,
2676    ) -> DeviceResult<Vec<ParallelExecutionResult>> {
2677        // Implementation for topology-aware parallelization
2678        Ok(vec![])
2679    }
2680
2681    async fn execute_resource_constrained_parallelization(
2682        &self,
2683    ) -> DeviceResult<Vec<ParallelExecutionResult>> {
2684        // Implementation for resource-constrained parallelization
2685        Ok(vec![])
2686    }
2687
2688    async fn execute_scirs2_optimized_parallelization(
2689        &self,
2690    ) -> DeviceResult<Vec<ParallelExecutionResult>> {
2691        // Implementation for SciRS2-optimized parallelization
2692        Ok(vec![])
2693    }
2694
2695    async fn execute_custom_parallelization(&self) -> DeviceResult<Vec<ParallelExecutionResult>> {
2696        // Implementation for custom parallelization
2697        Ok(vec![])
2698    }
2699}
2700
2701/// Parallel execution result
2702#[derive(Debug, Clone, Serialize, Deserialize)]
2703pub struct ParallelExecutionResult {
2704    pub task_id: String,
2705    pub success: bool,
2706    pub execution_time: Duration,
2707    pub resource_usage: ResourceUsage,
2708    pub quality_metrics: ExecutionQualityMetrics,
2709    pub results: Option<Vec<u8>>, // Serialized results
2710    pub error_message: Option<String>,
2711}
2712
2713/// Load balancing result
2714#[derive(Debug, Clone, Serialize, Deserialize)]
2715pub struct LoadBalancingResult {
2716    pub rebalancing_performed: bool,
2717    pub migrations_performed: usize,
2718    pub load_improvement: f64,
2719    pub estimated_performance_gain: f64,
2720    pub rebalancing_cost: f64,
2721}
2722
2723impl ResourceMonitor {
2724    fn new() -> Self {
2725        Self {
2726            cpu_usage: HashMap::new(),
2727            memory_usage: 0.0,
2728            qpu_usage: HashMap::new(),
2729            network_usage: 0.0,
2730            storage_usage: 0.0,
2731            monitoring_start_time: SystemTime::now(),
2732            last_update: SystemTime::now(),
2733        }
2734    }
2735}
2736
2737impl PerformanceTracker {
2738    fn new() -> Self {
2739        Self {
2740            execution_history: VecDeque::new(),
2741            performance_metrics: PerformanceMetrics {
2742                throughput: 0.0,
2743                latency: Duration::from_secs(0),
2744                resource_efficiency: 0.0,
2745                quality_score: 0.0,
2746                cost_efficiency: 0.0,
2747                energy_efficiency: 0.0,
2748            },
2749            optimization_suggestions: Vec::new(),
2750            baseline_metrics: None,
2751        }
2752    }
2753}
2754
2755impl LoadBalancer {
2756    fn new(algorithm: LoadBalancingAlgorithm) -> Self {
2757        Self {
2758            algorithm,
2759            backend_loads: HashMap::new(),
2760            load_history: VecDeque::new(),
2761            rebalancing_strategy: RebalancingStrategy::Hybrid,
2762            migration_tracker: MigrationTracker::new(),
2763        }
2764    }
2765
2766    async fn rebalance_loads(&mut self) -> DeviceResult<LoadBalancingResult> {
2767        // Implementation for load rebalancing
2768        Ok(LoadBalancingResult {
2769            rebalancing_performed: false,
2770            migrations_performed: 0,
2771            load_improvement: 0.0,
2772            estimated_performance_gain: 0.0,
2773            rebalancing_cost: 0.0,
2774        })
2775    }
2776}
2777
2778impl MigrationTracker {
2779    fn new() -> Self {
2780        Self {
2781            active_migrations: HashMap::new(),
2782            migration_history: VecDeque::new(),
2783            migration_costs: HashMap::new(),
2784        }
2785    }
2786}
2787
2788#[cfg(test)]
2789mod tests {
2790    use super::*;
2791
2792    #[test]
2793    fn test_parallelization_config_default() {
2794        let config = ParallelizationConfig::default();
2795        assert_eq!(config.strategy, ParallelizationStrategy::Hybrid);
2796        assert!(config.resource_allocation.max_concurrent_circuits > 0);
2797    }
2798
2799    #[test]
2800    fn test_task_priority_ordering() {
2801        assert!(TaskPriority::Low < TaskPriority::Normal);
2802        assert!(TaskPriority::Normal < TaskPriority::High);
2803        assert!(TaskPriority::High < TaskPriority::Critical);
2804        assert!(TaskPriority::Critical < TaskPriority::System);
2805    }
2806
2807    #[test]
2808    fn test_resource_requirements_creation() {
2809        let requirements = ParallelResourceRequirements {
2810            required_cpu_cores: 4,
2811            required_memory_mb: 1024.0,
2812            required_qpu_time: Duration::from_secs(300),
2813            required_bandwidth_mbps: 100.0,
2814            required_storage_mb: 500.0,
2815        };
2816
2817        assert_eq!(requirements.required_cpu_cores, 4);
2818        assert_eq!(requirements.required_memory_mb, 1024.0);
2819    }
2820
2821    #[tokio::test]
2822    async fn test_parallelization_engine_creation() {
2823        let config = ParallelizationConfig::default();
2824        let devices = HashMap::new();
2825        let cal_mgr = CalibrationManager::new();
2826        let device_manager = Arc::new(RwLock::new(
2827            IntegratedQuantumDeviceManager::new(Default::default(), devices, cal_mgr.clone())
2828                .unwrap(),
2829        ));
2830        let calibration_manager = Arc::new(RwLock::new(cal_mgr));
2831        let router = Arc::new(RwLock::new(AdvancedQubitRouter::new(
2832            Default::default(),
2833            crate::routing_advanced::AdvancedRoutingStrategy::Hybrid,
2834            42,
2835        )));
2836
2837        let _engine =
2838            HardwareParallelizationEngine::new(config, device_manager, calibration_manager, router);
2839
2840        // Should create without error
2841        assert!(true);
2842    }
2843}