Skip to main content

quantrs2_anneal/universal_annealing_compiler/
scheduling.rs

1//! Scheduling and resource allocation types.
2//!
3//! This module contains types for job scheduling, resource allocation,
4//! and performance tracking.
5
6use std::collections::{HashMap, VecDeque};
7use std::time::{Duration, Instant};
8
9use super::config::{ResourceAllocationStrategy, SchedulingPriority};
10use super::platform::QuantumPlatform;
11
12/// Universal resource scheduler
13pub struct UniversalResourceScheduler {
14    /// Scheduler configuration
15    pub config: SchedulerConfig,
16    /// Scheduling queue
17    pub queue: SchedulingQueue,
18    /// Resource allocator
19    pub allocator: ResourceAllocator,
20    /// Performance tracker
21    pub performance_tracker: PerformanceTracker,
22}
23
24impl UniversalResourceScheduler {
25    /// Create a new scheduler
26    pub fn new() -> Self {
27        Self {
28            config: SchedulerConfig {
29                algorithm: SchedulingAlgorithm::Priority,
30                allocation_strategy: ResourceAllocationStrategy::CostEffective,
31                fairness_policy: FairnessPolicy::ProportionalShare,
32                load_balancing: LoadBalancingConfig {
33                    enabled: true,
34                    threshold: 0.8,
35                    frequency: Duration::from_secs(60),
36                    strategy: LoadBalancingStrategy::PerformanceBased,
37                },
38            },
39            queue: SchedulingQueue {
40                pending_jobs: VecDeque::new(),
41                running_jobs: HashMap::new(),
42                completed_jobs: VecDeque::new(),
43                statistics: QueueStatistics {
44                    total_jobs: 0,
45                    average_wait_time: Duration::from_secs(0),
46                    average_execution_time: Duration::from_secs(0),
47                    throughput: 0.0,
48                    utilization: 0.0,
49                },
50            },
51            allocator: ResourceAllocator {
52                config: AllocatorConfig {
53                    strategy: AllocationStrategy::Optimized,
54                    constraints: AllocationConstraints {
55                        max_utilization: 0.9,
56                        reservations: vec![],
57                        affinity_constraints: vec![],
58                    },
59                    objectives: AllocationObjectives {
60                        primary: AllocationObjective::MaximizePerformance,
61                        secondary: vec![(AllocationObjective::MinimizeCost, 0.3)],
62                    },
63                },
64                available_resources: HashMap::new(),
65                allocation_history: VecDeque::new(),
66            },
67            performance_tracker: PerformanceTracker {
68                config: TrackerConfig {
69                    collection_interval: Duration::from_secs(10),
70                    retention_period: Duration::from_secs(86_400),
71                    alerting: AlertingConfig {
72                        enabled: true,
73                        thresholds: HashMap::new(),
74                        channels: vec![],
75                    },
76                },
77                metrics: HashMap::new(),
78                historical_data: VecDeque::new(),
79            },
80        }
81    }
82}
83
84impl Default for UniversalResourceScheduler {
85    fn default() -> Self {
86        Self::new()
87    }
88}
89
90/// Scheduler configuration
91#[derive(Debug, Clone)]
92pub struct SchedulerConfig {
93    /// Scheduling algorithm
94    pub algorithm: SchedulingAlgorithm,
95    /// Allocation strategy
96    pub allocation_strategy: ResourceAllocationStrategy,
97    /// Fairness policy
98    pub fairness_policy: FairnessPolicy,
99    /// Load balancing configuration
100    pub load_balancing: LoadBalancingConfig,
101}
102
103/// Scheduling algorithms
104#[derive(Debug, Clone, PartialEq)]
105pub enum SchedulingAlgorithm {
106    /// First-come-first-served
107    FCFS,
108    /// Shortest job first
109    ShortestJobFirst,
110    /// Priority-based
111    Priority,
112    /// Round-robin
113    RoundRobin,
114    /// Multi-level feedback queue
115    MultilevelFeedback,
116}
117
118/// Fairness policies
119#[derive(Debug, Clone, PartialEq)]
120pub enum FairnessPolicy {
121    /// Equal share
122    EqualShare,
123    /// Proportional share
124    ProportionalShare,
125    /// Weighted fair sharing
126    WeightedFairSharing,
127    /// Priority-based
128    PriorityBased,
129}
130
131/// Load balancing configuration
132#[derive(Debug, Clone)]
133pub struct LoadBalancingConfig {
134    /// Enable load balancing
135    pub enabled: bool,
136    /// Threshold for rebalancing
137    pub threshold: f64,
138    /// Rebalancing frequency
139    pub frequency: Duration,
140    /// Load balancing strategy
141    pub strategy: LoadBalancingStrategy,
142}
143
144/// Load balancing strategies
145#[derive(Debug, Clone, PartialEq)]
146pub enum LoadBalancingStrategy {
147    /// Round-robin
148    RoundRobin,
149    /// Least loaded
150    LeastLoaded,
151    /// Performance-based
152    PerformanceBased,
153    /// Cost-based
154    CostBased,
155}
156
157/// Scheduling queue
158#[derive(Debug)]
159pub struct SchedulingQueue {
160    /// Pending jobs
161    pub pending_jobs: VecDeque<ScheduledJob>,
162    /// Running jobs
163    pub running_jobs: HashMap<String, RunningJob>,
164    /// Completed jobs
165    pub completed_jobs: VecDeque<CompletedJob>,
166    /// Queue statistics
167    pub statistics: QueueStatistics,
168}
169
170/// Scheduled job
171#[derive(Debug, Clone)]
172pub struct ScheduledJob {
173    /// Job identifier
174    pub job_id: String,
175    /// Priority
176    pub priority: SchedulingPriority,
177    /// Estimated execution time
178    pub estimated_execution_time: Duration,
179    /// Resource requirements
180    pub resource_requirements: JobResourceRequirements,
181    /// Submission timestamp
182    pub submitted_at: Instant,
183}
184
185/// Running job
186#[derive(Debug, Clone)]
187pub struct RunningJob {
188    /// Job identifier
189    pub job_id: String,
190    /// Start time
191    pub started_at: Instant,
192    /// Allocated resources
193    pub allocated_resources: AllocatedResources,
194    /// Platform
195    pub platform: QuantumPlatform,
196}
197
198/// Completed job
199#[derive(Debug, Clone)]
200pub struct CompletedJob {
201    /// Job identifier
202    pub job_id: String,
203    /// Completion timestamp
204    pub completed_at: Instant,
205    /// Status
206    pub status: JobStatus,
207    /// Execution time
208    pub execution_time: Duration,
209    /// Wait time
210    pub wait_time: Duration,
211}
212
213/// Job resource requirements
214#[derive(Debug, Clone)]
215pub struct JobResourceRequirements {
216    /// Minimum qubits
217    pub min_qubits: usize,
218    /// Preferred qubits
219    pub preferred_qubits: Option<usize>,
220    /// Memory requirements
221    pub memory_mb: usize,
222    /// Expected duration
223    pub expected_duration: Duration,
224}
225
226/// Allocated resources
227#[derive(Debug, Clone)]
228pub struct AllocatedResources {
229    /// Allocated qubits
230    pub qubits: Vec<usize>,
231    /// Memory allocated
232    pub memory_mb: usize,
233    /// Time slot
234    pub time_slot: TimeSlot,
235}
236
237/// Job status
238#[derive(Debug, Clone, PartialEq)]
239pub enum JobStatus {
240    /// Pending
241    Pending,
242    /// Queued
243    Queued,
244    /// Running
245    Running,
246    /// Completed successfully
247    Completed,
248    /// Failed
249    Failed,
250    /// Cancelled
251    Cancelled,
252    /// Timed out
253    TimedOut,
254}
255
256/// Queue statistics
257#[derive(Debug, Clone)]
258pub struct QueueStatistics {
259    /// Total jobs
260    pub total_jobs: u64,
261    /// Average wait time
262    pub average_wait_time: Duration,
263    /// Average execution time
264    pub average_execution_time: Duration,
265    /// Throughput (jobs per hour)
266    pub throughput: f64,
267    /// Utilization
268    pub utilization: f64,
269}
270
271/// Resource allocator
272#[derive(Debug)]
273pub struct ResourceAllocator {
274    /// Allocator configuration
275    pub config: AllocatorConfig,
276    /// Available resources per platform
277    pub available_resources: HashMap<QuantumPlatform, AvailableResources>,
278    /// Allocation history
279    pub allocation_history: VecDeque<AllocationRecord>,
280}
281
282/// Allocator configuration
283#[derive(Debug, Clone)]
284pub struct AllocatorConfig {
285    /// Allocation strategy
286    pub strategy: AllocationStrategy,
287    /// Constraints
288    pub constraints: AllocationConstraints,
289    /// Allocation objectives
290    pub objectives: AllocationObjectives,
291}
292
293/// Allocation strategies
294#[derive(Debug, Clone, PartialEq)]
295pub enum AllocationStrategy {
296    /// First fit
297    FirstFit,
298    /// Best fit
299    BestFit,
300    /// Worst fit
301    WorstFit,
302    /// Optimized
303    Optimized,
304}
305
306/// Allocation constraints
307#[derive(Debug, Clone)]
308pub struct AllocationConstraints {
309    /// Maximum utilization
310    pub max_utilization: f64,
311    /// Reservations
312    pub reservations: Vec<ResourceReservation>,
313    /// Affinity constraints
314    pub affinity_constraints: Vec<AffinityConstraint>,
315}
316
317/// Resource reservation
318#[derive(Debug, Clone)]
319pub struct ResourceReservation {
320    /// Reservation identifier
321    pub reservation_id: String,
322    /// Reserved resources
323    pub resources: ReservedResources,
324    /// Start time
325    pub start_time: Instant,
326    /// Duration
327    pub duration: Duration,
328}
329
330/// Reserved resources
331#[derive(Debug, Clone)]
332pub struct ReservedResources {
333    /// Reserved qubits
334    pub qubits: Vec<usize>,
335    /// Reserved memory
336    pub memory_mb: usize,
337}
338
339/// Time slot
340#[derive(Debug, Clone)]
341pub struct TimeSlot {
342    /// Start time
343    pub start_time: Instant,
344    /// End time
345    pub end_time: Instant,
346}
347
348/// Affinity constraint
349#[derive(Debug, Clone)]
350pub struct AffinityConstraint {
351    /// Target platform
352    pub target: QuantumPlatform,
353    /// Affinity type
354    pub affinity_type: AffinityType,
355    /// Strength
356    pub strength: AffinityStrength,
357}
358
359/// Affinity types
360#[derive(Debug, Clone, PartialEq)]
361pub enum AffinityType {
362    /// Must use this platform
363    Required,
364    /// Prefer this platform
365    Preferred,
366    /// Avoid this platform
367    Avoid,
368}
369
370/// Affinity strength
371#[derive(Debug, Clone, PartialEq)]
372pub enum AffinityStrength {
373    /// Weak
374    Weak,
375    /// Medium
376    Medium,
377    /// Strong
378    Strong,
379}
380
381/// Allocation objectives
382#[derive(Debug, Clone)]
383pub struct AllocationObjectives {
384    /// Primary objective
385    pub primary: AllocationObjective,
386    /// Secondary objectives with weights
387    pub secondary: Vec<(AllocationObjective, f64)>,
388}
389
390/// Allocation objectives
391#[derive(Debug, Clone, PartialEq)]
392pub enum AllocationObjective {
393    /// Maximize performance
394    MaximizePerformance,
395    /// Minimize cost
396    MinimizeCost,
397    /// Minimize wait time
398    MinimizeWaitTime,
399    /// Maximize utilization
400    MaximizeUtilization,
401    /// Balance load
402    BalanceLoad,
403}
404
405/// Available resources
406#[derive(Debug, Clone)]
407pub struct AvailableResources {
408    /// Platform
409    pub platform: QuantumPlatform,
410    /// Capacity
411    pub capacity: ResourceCapacity,
412    /// Current load
413    pub current_load: ResourceLoad,
414}
415
416/// Resource capacity
417#[derive(Debug, Clone)]
418pub struct ResourceCapacity {
419    /// Total qubits
420    pub total_qubits: usize,
421    /// Total memory
422    pub total_memory_mb: usize,
423    /// Maximum concurrent jobs
424    pub max_concurrent_jobs: usize,
425}
426
427/// Resource load
428#[derive(Debug, Clone)]
429pub struct ResourceLoad {
430    /// Used qubits
431    pub used_qubits: usize,
432    /// Used memory
433    pub used_memory_mb: usize,
434    /// Active jobs
435    pub active_jobs: usize,
436}
437
438/// Allocation record
439#[derive(Debug, Clone)]
440pub struct AllocationRecord {
441    /// Job identifier
442    pub job_id: String,
443    /// Allocated platform
444    pub platform: QuantumPlatform,
445    /// Allocated resources
446    pub resources: AllocatedResources,
447    /// Allocation timestamp
448    pub allocated_at: Instant,
449}
450
451/// Performance tracker
452#[derive(Debug)]
453pub struct PerformanceTracker {
454    /// Tracker configuration
455    pub config: TrackerConfig,
456    /// Current metrics
457    pub metrics: HashMap<String, MetricValue>,
458    /// Historical data
459    pub historical_data: VecDeque<PerformanceSnapshot>,
460}
461
462/// Tracker configuration
463#[derive(Debug, Clone)]
464pub struct TrackerConfig {
465    /// Collection interval
466    pub collection_interval: Duration,
467    /// Retention period
468    pub retention_period: Duration,
469    /// Alerting configuration
470    pub alerting: AlertingConfig,
471}
472
473/// Alerting configuration
474#[derive(Debug, Clone)]
475pub struct AlertingConfig {
476    /// Alerting enabled
477    pub enabled: bool,
478    /// Thresholds
479    pub thresholds: HashMap<String, f64>,
480    /// Alert channels
481    pub channels: Vec<AlertChannel>,
482}
483
484/// Alert channel
485#[derive(Debug, Clone)]
486pub struct AlertChannel {
487    /// Channel name
488    pub name: String,
489    /// Channel type
490    pub channel_type: AlertChannelType,
491}
492
493/// Alert channel types
494#[derive(Debug, Clone, PartialEq)]
495pub enum AlertChannelType {
496    /// Email
497    Email,
498    /// Slack
499    Slack,
500    /// PagerDuty
501    PagerDuty,
502    /// Webhook
503    Webhook,
504    /// Log
505    Log,
506}
507
508/// Metric value
509#[derive(Debug, Clone)]
510pub enum MetricValue {
511    /// Counter
512    Counter(u64),
513    /// Gauge
514    Gauge(f64),
515    /// Histogram
516    Histogram(Vec<f64>),
517    /// Summary
518    Summary { count: u64, sum: f64 },
519}
520
521/// Performance snapshot
522#[derive(Debug, Clone)]
523pub struct PerformanceSnapshot {
524    /// Timestamp
525    pub timestamp: Instant,
526    /// Platform metrics
527    pub platform_metrics: HashMap<QuantumPlatform, PlatformMetrics>,
528}
529
530/// Platform metrics
531#[derive(Debug, Clone)]
532pub struct PlatformMetrics {
533    /// Success rate
534    pub success_rate: f64,
535    /// Average execution time
536    pub avg_execution_time: Duration,
537    /// Queue length
538    pub queue_length: usize,
539    /// Utilization
540    pub utilization: f64,
541}
542
543/// System state
544#[derive(Debug, Clone)]
545pub struct SystemState {
546    /// Queue lengths
547    pub queue_lengths: HashMap<QuantumPlatform, usize>,
548    /// Resource utilization
549    pub resource_utilization: HashMap<QuantumPlatform, f64>,
550}