quantrs2-anneal 0.1.3

Quantum annealing support for the QuantRS2 framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
//! Scheduling and resource allocation types.
//!
//! This module contains types for job scheduling, resource allocation,
//! and performance tracking.

use std::collections::{HashMap, VecDeque};
use std::time::{Duration, Instant};

use super::config::{ResourceAllocationStrategy, SchedulingPriority};
use super::platform::QuantumPlatform;

/// Universal resource scheduler
pub struct UniversalResourceScheduler {
    /// Scheduler configuration
    pub config: SchedulerConfig,
    /// Scheduling queue
    pub queue: SchedulingQueue,
    /// Resource allocator
    pub allocator: ResourceAllocator,
    /// Performance tracker
    pub performance_tracker: PerformanceTracker,
}

impl UniversalResourceScheduler {
    /// Create a new scheduler
    pub fn new() -> Self {
        Self {
            config: SchedulerConfig {
                algorithm: SchedulingAlgorithm::Priority,
                allocation_strategy: ResourceAllocationStrategy::CostEffective,
                fairness_policy: FairnessPolicy::ProportionalShare,
                load_balancing: LoadBalancingConfig {
                    enabled: true,
                    threshold: 0.8,
                    frequency: Duration::from_secs(60),
                    strategy: LoadBalancingStrategy::PerformanceBased,
                },
            },
            queue: SchedulingQueue {
                pending_jobs: VecDeque::new(),
                running_jobs: HashMap::new(),
                completed_jobs: VecDeque::new(),
                statistics: QueueStatistics {
                    total_jobs: 0,
                    average_wait_time: Duration::from_secs(0),
                    average_execution_time: Duration::from_secs(0),
                    throughput: 0.0,
                    utilization: 0.0,
                },
            },
            allocator: ResourceAllocator {
                config: AllocatorConfig {
                    strategy: AllocationStrategy::Optimized,
                    constraints: AllocationConstraints {
                        max_utilization: 0.9,
                        reservations: vec![],
                        affinity_constraints: vec![],
                    },
                    objectives: AllocationObjectives {
                        primary: AllocationObjective::MaximizePerformance,
                        secondary: vec![(AllocationObjective::MinimizeCost, 0.3)],
                    },
                },
                available_resources: HashMap::new(),
                allocation_history: VecDeque::new(),
            },
            performance_tracker: PerformanceTracker {
                config: TrackerConfig {
                    collection_interval: Duration::from_secs(10),
                    retention_period: Duration::from_secs(86_400),
                    alerting: AlertingConfig {
                        enabled: true,
                        thresholds: HashMap::new(),
                        channels: vec![],
                    },
                },
                metrics: HashMap::new(),
                historical_data: VecDeque::new(),
            },
        }
    }
}

impl Default for UniversalResourceScheduler {
    fn default() -> Self {
        Self::new()
    }
}

/// Scheduler configuration
#[derive(Debug, Clone)]
pub struct SchedulerConfig {
    /// Scheduling algorithm
    pub algorithm: SchedulingAlgorithm,
    /// Allocation strategy
    pub allocation_strategy: ResourceAllocationStrategy,
    /// Fairness policy
    pub fairness_policy: FairnessPolicy,
    /// Load balancing configuration
    pub load_balancing: LoadBalancingConfig,
}

/// Scheduling algorithms
#[derive(Debug, Clone, PartialEq)]
pub enum SchedulingAlgorithm {
    /// First-come-first-served
    FCFS,
    /// Shortest job first
    ShortestJobFirst,
    /// Priority-based
    Priority,
    /// Round-robin
    RoundRobin,
    /// Multi-level feedback queue
    MultilevelFeedback,
}

/// Fairness policies
#[derive(Debug, Clone, PartialEq)]
pub enum FairnessPolicy {
    /// Equal share
    EqualShare,
    /// Proportional share
    ProportionalShare,
    /// Weighted fair sharing
    WeightedFairSharing,
    /// Priority-based
    PriorityBased,
}

/// Load balancing configuration
#[derive(Debug, Clone)]
pub struct LoadBalancingConfig {
    /// Enable load balancing
    pub enabled: bool,
    /// Threshold for rebalancing
    pub threshold: f64,
    /// Rebalancing frequency
    pub frequency: Duration,
    /// Load balancing strategy
    pub strategy: LoadBalancingStrategy,
}

/// Load balancing strategies
#[derive(Debug, Clone, PartialEq)]
pub enum LoadBalancingStrategy {
    /// Round-robin
    RoundRobin,
    /// Least loaded
    LeastLoaded,
    /// Performance-based
    PerformanceBased,
    /// Cost-based
    CostBased,
}

/// Scheduling queue
#[derive(Debug)]
pub struct SchedulingQueue {
    /// Pending jobs
    pub pending_jobs: VecDeque<ScheduledJob>,
    /// Running jobs
    pub running_jobs: HashMap<String, RunningJob>,
    /// Completed jobs
    pub completed_jobs: VecDeque<CompletedJob>,
    /// Queue statistics
    pub statistics: QueueStatistics,
}

/// Scheduled job
#[derive(Debug, Clone)]
pub struct ScheduledJob {
    /// Job identifier
    pub job_id: String,
    /// Priority
    pub priority: SchedulingPriority,
    /// Estimated execution time
    pub estimated_execution_time: Duration,
    /// Resource requirements
    pub resource_requirements: JobResourceRequirements,
    /// Submission timestamp
    pub submitted_at: Instant,
}

/// Running job
#[derive(Debug, Clone)]
pub struct RunningJob {
    /// Job identifier
    pub job_id: String,
    /// Start time
    pub started_at: Instant,
    /// Allocated resources
    pub allocated_resources: AllocatedResources,
    /// Platform
    pub platform: QuantumPlatform,
}

/// Completed job
#[derive(Debug, Clone)]
pub struct CompletedJob {
    /// Job identifier
    pub job_id: String,
    /// Completion timestamp
    pub completed_at: Instant,
    /// Status
    pub status: JobStatus,
    /// Execution time
    pub execution_time: Duration,
    /// Wait time
    pub wait_time: Duration,
}

/// Job resource requirements
#[derive(Debug, Clone)]
pub struct JobResourceRequirements {
    /// Minimum qubits
    pub min_qubits: usize,
    /// Preferred qubits
    pub preferred_qubits: Option<usize>,
    /// Memory requirements
    pub memory_mb: usize,
    /// Expected duration
    pub expected_duration: Duration,
}

/// Allocated resources
#[derive(Debug, Clone)]
pub struct AllocatedResources {
    /// Allocated qubits
    pub qubits: Vec<usize>,
    /// Memory allocated
    pub memory_mb: usize,
    /// Time slot
    pub time_slot: TimeSlot,
}

/// Job status
#[derive(Debug, Clone, PartialEq)]
pub enum JobStatus {
    /// Pending
    Pending,
    /// Queued
    Queued,
    /// Running
    Running,
    /// Completed successfully
    Completed,
    /// Failed
    Failed,
    /// Cancelled
    Cancelled,
    /// Timed out
    TimedOut,
}

/// Queue statistics
#[derive(Debug, Clone)]
pub struct QueueStatistics {
    /// Total jobs
    pub total_jobs: u64,
    /// Average wait time
    pub average_wait_time: Duration,
    /// Average execution time
    pub average_execution_time: Duration,
    /// Throughput (jobs per hour)
    pub throughput: f64,
    /// Utilization
    pub utilization: f64,
}

/// Resource allocator
#[derive(Debug)]
pub struct ResourceAllocator {
    /// Allocator configuration
    pub config: AllocatorConfig,
    /// Available resources per platform
    pub available_resources: HashMap<QuantumPlatform, AvailableResources>,
    /// Allocation history
    pub allocation_history: VecDeque<AllocationRecord>,
}

/// Allocator configuration
#[derive(Debug, Clone)]
pub struct AllocatorConfig {
    /// Allocation strategy
    pub strategy: AllocationStrategy,
    /// Constraints
    pub constraints: AllocationConstraints,
    /// Allocation objectives
    pub objectives: AllocationObjectives,
}

/// Allocation strategies
#[derive(Debug, Clone, PartialEq)]
pub enum AllocationStrategy {
    /// First fit
    FirstFit,
    /// Best fit
    BestFit,
    /// Worst fit
    WorstFit,
    /// Optimized
    Optimized,
}

/// Allocation constraints
#[derive(Debug, Clone)]
pub struct AllocationConstraints {
    /// Maximum utilization
    pub max_utilization: f64,
    /// Reservations
    pub reservations: Vec<ResourceReservation>,
    /// Affinity constraints
    pub affinity_constraints: Vec<AffinityConstraint>,
}

/// Resource reservation
#[derive(Debug, Clone)]
pub struct ResourceReservation {
    /// Reservation identifier
    pub reservation_id: String,
    /// Reserved resources
    pub resources: ReservedResources,
    /// Start time
    pub start_time: Instant,
    /// Duration
    pub duration: Duration,
}

/// Reserved resources
#[derive(Debug, Clone)]
pub struct ReservedResources {
    /// Reserved qubits
    pub qubits: Vec<usize>,
    /// Reserved memory
    pub memory_mb: usize,
}

/// Time slot
#[derive(Debug, Clone)]
pub struct TimeSlot {
    /// Start time
    pub start_time: Instant,
    /// End time
    pub end_time: Instant,
}

/// Affinity constraint
#[derive(Debug, Clone)]
pub struct AffinityConstraint {
    /// Target platform
    pub target: QuantumPlatform,
    /// Affinity type
    pub affinity_type: AffinityType,
    /// Strength
    pub strength: AffinityStrength,
}

/// Affinity types
#[derive(Debug, Clone, PartialEq)]
pub enum AffinityType {
    /// Must use this platform
    Required,
    /// Prefer this platform
    Preferred,
    /// Avoid this platform
    Avoid,
}

/// Affinity strength
#[derive(Debug, Clone, PartialEq)]
pub enum AffinityStrength {
    /// Weak
    Weak,
    /// Medium
    Medium,
    /// Strong
    Strong,
}

/// Allocation objectives
#[derive(Debug, Clone)]
pub struct AllocationObjectives {
    /// Primary objective
    pub primary: AllocationObjective,
    /// Secondary objectives with weights
    pub secondary: Vec<(AllocationObjective, f64)>,
}

/// Allocation objectives
#[derive(Debug, Clone, PartialEq)]
pub enum AllocationObjective {
    /// Maximize performance
    MaximizePerformance,
    /// Minimize cost
    MinimizeCost,
    /// Minimize wait time
    MinimizeWaitTime,
    /// Maximize utilization
    MaximizeUtilization,
    /// Balance load
    BalanceLoad,
}

/// Available resources
#[derive(Debug, Clone)]
pub struct AvailableResources {
    /// Platform
    pub platform: QuantumPlatform,
    /// Capacity
    pub capacity: ResourceCapacity,
    /// Current load
    pub current_load: ResourceLoad,
}

/// Resource capacity
#[derive(Debug, Clone)]
pub struct ResourceCapacity {
    /// Total qubits
    pub total_qubits: usize,
    /// Total memory
    pub total_memory_mb: usize,
    /// Maximum concurrent jobs
    pub max_concurrent_jobs: usize,
}

/// Resource load
#[derive(Debug, Clone)]
pub struct ResourceLoad {
    /// Used qubits
    pub used_qubits: usize,
    /// Used memory
    pub used_memory_mb: usize,
    /// Active jobs
    pub active_jobs: usize,
}

/// Allocation record
#[derive(Debug, Clone)]
pub struct AllocationRecord {
    /// Job identifier
    pub job_id: String,
    /// Allocated platform
    pub platform: QuantumPlatform,
    /// Allocated resources
    pub resources: AllocatedResources,
    /// Allocation timestamp
    pub allocated_at: Instant,
}

/// Performance tracker
#[derive(Debug)]
pub struct PerformanceTracker {
    /// Tracker configuration
    pub config: TrackerConfig,
    /// Current metrics
    pub metrics: HashMap<String, MetricValue>,
    /// Historical data
    pub historical_data: VecDeque<PerformanceSnapshot>,
}

/// Tracker configuration
#[derive(Debug, Clone)]
pub struct TrackerConfig {
    /// Collection interval
    pub collection_interval: Duration,
    /// Retention period
    pub retention_period: Duration,
    /// Alerting configuration
    pub alerting: AlertingConfig,
}

/// Alerting configuration
#[derive(Debug, Clone)]
pub struct AlertingConfig {
    /// Alerting enabled
    pub enabled: bool,
    /// Thresholds
    pub thresholds: HashMap<String, f64>,
    /// Alert channels
    pub channels: Vec<AlertChannel>,
}

/// Alert channel
#[derive(Debug, Clone)]
pub struct AlertChannel {
    /// Channel name
    pub name: String,
    /// Channel type
    pub channel_type: AlertChannelType,
}

/// Alert channel types
#[derive(Debug, Clone, PartialEq)]
pub enum AlertChannelType {
    /// Email
    Email,
    /// Slack
    Slack,
    /// PagerDuty
    PagerDuty,
    /// Webhook
    Webhook,
    /// Log
    Log,
}

/// Metric value
#[derive(Debug, Clone)]
pub enum MetricValue {
    /// Counter
    Counter(u64),
    /// Gauge
    Gauge(f64),
    /// Histogram
    Histogram(Vec<f64>),
    /// Summary
    Summary { count: u64, sum: f64 },
}

/// Performance snapshot
#[derive(Debug, Clone)]
pub struct PerformanceSnapshot {
    /// Timestamp
    pub timestamp: Instant,
    /// Platform metrics
    pub platform_metrics: HashMap<QuantumPlatform, PlatformMetrics>,
}

/// Platform metrics
#[derive(Debug, Clone)]
pub struct PlatformMetrics {
    /// Success rate
    pub success_rate: f64,
    /// Average execution time
    pub avg_execution_time: Duration,
    /// Queue length
    pub queue_length: usize,
    /// Utilization
    pub utilization: f64,
}

/// System state
#[derive(Debug, Clone)]
pub struct SystemState {
    /// Queue lengths
    pub queue_lengths: HashMap<QuantumPlatform, usize>,
    /// Resource utilization
    pub resource_utilization: HashMap<QuantumPlatform, f64>,
}