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
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
//! Multi-Objective Optimization for Meta-Learning
//!
//! This module contains all Multi-Objective Optimization types and implementations
//! used by the meta-learning optimization system.

use super::config::{
    ConstraintHandling, FrontierUpdateStrategy, MultiObjectiveConfig, OptimizationConfiguration,
    OptimizationObjective, ParetoFrontierConfig, ScalarizationMethod,
};
use crate::applications::ApplicationResult;
use std::collections::{HashMap, VecDeque};
use std::time::{Duration, Instant};

/// Multi-objective optimizer
pub struct MultiObjectiveOptimizer {
    /// Configuration
    pub config: MultiObjectiveConfig,
    /// Pareto frontier
    pub pareto_frontier: ParetoFrontier,
    /// Scalarization methods
    pub scalarizers: Vec<Scalarizer>,
    /// Constraint handlers
    pub constraint_handlers: Vec<ConstraintHandler>,
    /// Decision maker
    pub decision_maker: DecisionMaker,
}

/// Pareto frontier representation
#[derive(Debug)]
pub struct ParetoFrontier {
    /// Non-dominated solutions
    pub solutions: Vec<MultiObjectiveSolution>,
    /// Frontier statistics
    pub statistics: FrontierStatistics,
    /// Update history
    pub update_history: VecDeque<FrontierUpdate>,
}

/// Multi-objective solution
#[derive(Debug, Clone)]
pub struct MultiObjectiveSolution {
    /// Solution identifier
    pub id: String,
    /// Objective values
    pub objective_values: Vec<f64>,
    /// Decision variables
    pub decision_variables: OptimizationConfiguration,
    /// Dominance rank
    pub dominance_rank: usize,
    /// Crowding distance
    pub crowding_distance: f64,
}

/// Frontier statistics
#[derive(Debug, Clone)]
pub struct FrontierStatistics {
    /// Frontier size
    pub size: usize,
    /// Hypervolume
    pub hypervolume: f64,
    /// Spread
    pub spread: f64,
    /// Convergence metric
    pub convergence: f64,
    /// Coverage
    pub coverage: f64,
}

/// Frontier update
#[derive(Debug, Clone)]
pub struct FrontierUpdate {
    /// Update timestamp
    pub timestamp: Instant,
    /// Solutions added
    pub solutions_added: Vec<String>,
    /// Solutions removed
    pub solutions_removed: Vec<String>,
    /// Update reason
    pub reason: UpdateReason,
}

/// Update reasons
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum UpdateReason {
    /// New non-dominated solution
    NewNonDominated,
    /// Dominated solution removal
    DominatedRemoval,
    /// Capacity limit reached
    CapacityLimit,
    /// Quality improvement
    QualityImprovement,
}

/// Scalarization function
#[derive(Debug)]
pub struct Scalarizer {
    /// Method used
    pub method: ScalarizationMethod,
    /// Weights or preferences
    pub weights: Vec<f64>,
    /// Reference point
    pub reference_point: Option<Vec<f64>>,
    /// Parameters
    pub parameters: HashMap<String, f64>,
}

/// Constraint handler
#[derive(Debug)]
pub struct ConstraintHandler {
    /// Handling method
    pub method: ConstraintHandling,
    /// Constraints
    pub constraints: Vec<Constraint>,
    /// Penalty parameters
    pub penalty_parameters: HashMap<String, f64>,
}

/// Constraint definition
#[derive(Debug, Clone)]
pub struct Constraint {
    /// Constraint type
    pub constraint_type: ConstraintType,
    /// Constraint function
    pub function: String,
    /// Bounds
    pub bounds: (f64, f64),
    /// Tolerance
    pub tolerance: f64,
}

/// Constraint types
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ConstraintType {
    /// Equality constraint
    Equality,
    /// Inequality constraint
    Inequality,
    /// Box constraint
    Box,
    /// Linear constraint
    Linear,
    /// Nonlinear constraint
    Nonlinear,
}

/// Decision maker for multi-objective problems
#[derive(Debug)]
pub struct DecisionMaker {
    /// Decision strategy
    pub strategy: DecisionStrategy,
    /// Preference information
    pub preferences: UserPreferences,
    /// Decision history
    pub decision_history: VecDeque<Decision>,
}

/// Decision strategies
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DecisionStrategy {
    /// Interactive decision making
    Interactive,
    /// A priori preferences
    APriori,
    /// A posteriori analysis
    APosteriori,
    /// Progressive articulation
    Progressive,
    /// Automated decision
    Automated,
}

/// User preferences
#[derive(Debug, Clone)]
pub struct UserPreferences {
    /// Objective weights
    pub objective_weights: Vec<f64>,
    /// Acceptable trade-offs
    pub trade_offs: HashMap<String, f64>,
    /// Constraints
    pub user_constraints: Vec<Constraint>,
    /// Preference functions
    pub preference_functions: Vec<PreferenceFunction>,
}

/// Preference function
#[derive(Debug, Clone)]
pub struct PreferenceFunction {
    /// Function type
    pub function_type: PreferenceFunctionType,
    /// Parameters
    pub parameters: Vec<f64>,
    /// Applicable objectives
    pub objectives: Vec<usize>,
}

/// Types of preference functions
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PreferenceFunctionType {
    /// Linear preference
    Linear,
    /// Exponential preference
    Exponential,
    /// Logarithmic preference
    Logarithmic,
    /// Threshold-based
    Threshold,
    /// Custom function
    Custom(String),
}

/// Decision record
#[derive(Debug, Clone)]
pub struct Decision {
    /// Decision timestamp
    pub timestamp: Instant,
    /// Selected solution
    pub selected_solution: String,
    /// Decision rationale
    pub rationale: String,
    /// Confidence level
    pub confidence: f64,
    /// User feedback
    pub user_feedback: Option<f64>,
}

impl MultiObjectiveOptimizer {
    #[must_use]
    pub fn new(config: MultiObjectiveConfig) -> Self {
        Self {
            config,
            pareto_frontier: ParetoFrontier {
                solutions: Vec::new(),
                statistics: FrontierStatistics {
                    size: 0,
                    hypervolume: 0.0,
                    spread: 0.0,
                    convergence: 0.0,
                    coverage: 0.0,
                },
                update_history: VecDeque::new(),
            },
            scalarizers: Vec::new(),
            constraint_handlers: Vec::new(),
            decision_maker: DecisionMaker {
                strategy: DecisionStrategy::Automated,
                preferences: UserPreferences {
                    objective_weights: vec![0.5, 0.3, 0.2],
                    trade_offs: HashMap::new(),
                    user_constraints: Vec::new(),
                    preference_functions: Vec::new(),
                },
                decision_history: VecDeque::new(),
            },
        }
    }

    /// Add solution to Pareto frontier
    pub fn add_solution(&mut self, solution: MultiObjectiveSolution) -> ApplicationResult<bool> {
        // Check if solution is non-dominated
        let is_non_dominated = self.is_non_dominated(&solution);

        if is_non_dominated {
            // Remove dominated solutions
            let solutions_to_keep: Vec<_> = self
                .pareto_frontier
                .solutions
                .iter()
                .filter(|existing| !self.dominates(&solution, existing))
                .cloned()
                .collect();
            self.pareto_frontier.solutions = solutions_to_keep;

            // Add new solution
            self.pareto_frontier.solutions.push(solution.clone());

            // Update statistics
            self.update_frontier_statistics();

            // Record update
            let update = FrontierUpdate {
                timestamp: Instant::now(),
                solutions_added: vec![solution.id],
                solutions_removed: Vec::new(),
                reason: UpdateReason::NewNonDominated,
            };
            self.pareto_frontier.update_history.push_back(update);

            // Limit history size
            if self.pareto_frontier.update_history.len() > 1000 {
                self.pareto_frontier.update_history.pop_front();
            }

            Ok(true)
        } else {
            Ok(false)
        }
    }

    /// Check if solution is non-dominated
    fn is_non_dominated(&self, solution: &MultiObjectiveSolution) -> bool {
        for existing in &self.pareto_frontier.solutions {
            if self.dominates(existing, solution) {
                return false;
            }
        }
        true
    }

    /// Check if solution1 dominates solution2
    fn dominates(
        &self,
        solution1: &MultiObjectiveSolution,
        solution2: &MultiObjectiveSolution,
    ) -> bool {
        let mut at_least_one_better = false;

        for (val1, val2) in solution1
            .objective_values
            .iter()
            .zip(&solution2.objective_values)
        {
            if val1 < val2 {
                return false; // Assuming minimization
            }
            if val1 > val2 {
                at_least_one_better = true;
            }
        }

        at_least_one_better
    }

    /// Update frontier statistics
    fn update_frontier_statistics(&mut self) {
        self.pareto_frontier.statistics.size = self.pareto_frontier.solutions.len();

        // Calculate hypervolume (simplified)
        self.pareto_frontier.statistics.hypervolume = self.calculate_hypervolume();

        // Calculate spread
        self.pareto_frontier.statistics.spread = self.calculate_spread();

        // Update convergence metric
        self.pareto_frontier.statistics.convergence = 0.8; // Simplified

        // Update coverage
        self.pareto_frontier.statistics.coverage = 0.9; // Simplified
    }

    /// Calculate hypervolume (simplified implementation)
    fn calculate_hypervolume(&self) -> f64 {
        if self.pareto_frontier.solutions.is_empty() {
            return 0.0;
        }

        // Simple hypervolume calculation
        let mut volume = 0.0;
        for solution in &self.pareto_frontier.solutions {
            let mut point_volume = 1.0;
            for &value in &solution.objective_values {
                point_volume *= value.max(0.0);
            }
            volume += point_volume;
        }

        volume
    }

    /// Calculate spread metric
    fn calculate_spread(&self) -> f64 {
        if self.pareto_frontier.solutions.len() < 2 {
            return 0.0;
        }

        // Simple spread calculation based on distance between solutions
        let mut total_distance = 0.0;
        let num_objectives = self.pareto_frontier.solutions[0].objective_values.len();

        for i in 0..num_objectives {
            let mut values: Vec<f64> = self
                .pareto_frontier
                .solutions
                .iter()
                .map(|s| s.objective_values[i])
                .collect();
            values.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));

            if let (Some(&min), Some(&max)) = (values.first(), values.last()) {
                total_distance += max - min;
            }
        }

        total_distance / num_objectives as f64
    }

    /// Scalarize objectives using weighted sum
    #[must_use]
    pub fn scalarize_weighted_sum(
        &self,
        solution: &MultiObjectiveSolution,
        weights: &[f64],
    ) -> f64 {
        solution
            .objective_values
            .iter()
            .zip(weights)
            .map(|(value, weight)| value * weight)
            .sum()
    }

    /// Select best solution using decision maker preferences
    pub fn select_solution(&mut self) -> ApplicationResult<Option<String>> {
        if self.pareto_frontier.solutions.is_empty() {
            return Ok(None);
        }

        match self.decision_maker.strategy {
            DecisionStrategy::Automated => {
                // Use weighted sum with user preferences
                let weights = &self.decision_maker.preferences.objective_weights;

                let mut best_solution = None;
                let mut best_score = f64::NEG_INFINITY;

                for solution in &self.pareto_frontier.solutions {
                    let score = self.scalarize_weighted_sum(solution, weights);
                    if score > best_score {
                        best_score = score;
                        best_solution = Some(solution.id.clone());
                    }
                }

                if let Some(ref solution_id) = best_solution {
                    // Record decision
                    let decision = Decision {
                        timestamp: Instant::now(),
                        selected_solution: solution_id.clone(),
                        rationale: "Automated selection using weighted sum".to_string(),
                        confidence: 0.8,
                        user_feedback: None,
                    };
                    self.decision_maker.decision_history.push_back(decision);

                    // Limit history size
                    if self.decision_maker.decision_history.len() > 100 {
                        self.decision_maker.decision_history.pop_front();
                    }
                }

                Ok(best_solution)
            }
            _ => {
                // For other strategies, just return the first solution for now
                Ok(self.pareto_frontier.solutions.first().map(|s| s.id.clone()))
            }
        }
    }

    /// Get frontier statistics
    #[must_use]
    pub const fn get_statistics(&self) -> &FrontierStatistics {
        &self.pareto_frontier.statistics
    }

    /// Get all solutions in Pareto frontier
    #[must_use]
    pub const fn get_pareto_solutions(&self) -> &Vec<MultiObjectiveSolution> {
        &self.pareto_frontier.solutions
    }

    /// Clear Pareto frontier
    pub fn clear_frontier(&mut self) {
        self.pareto_frontier.solutions.clear();
        self.update_frontier_statistics();

        let update = FrontierUpdate {
            timestamp: Instant::now(),
            solutions_added: Vec::new(),
            solutions_removed: Vec::new(),
            reason: UpdateReason::QualityImprovement,
        };
        self.pareto_frontier.update_history.push_back(update);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::meta_learning::config::*;
    use crate::meta_learning::config::{AlgorithmType, ResourceAllocation};

    #[test]
    fn test_multi_objective_optimizer_creation() {
        let config = MultiObjectiveConfig::default();
        let optimizer = MultiObjectiveOptimizer::new(config);

        assert_eq!(optimizer.pareto_frontier.solutions.len(), 0);
        assert_eq!(optimizer.pareto_frontier.statistics.size, 0);
    }

    #[test]
    fn test_solution_addition() {
        let config = MultiObjectiveConfig::default();
        let mut optimizer = MultiObjectiveOptimizer::new(config);

        let solution = MultiObjectiveSolution {
            id: "test_solution".to_string(),
            objective_values: vec![1.0, 2.0, 3.0],
            decision_variables: OptimizationConfiguration {
                algorithm: AlgorithmType::SimulatedAnnealing,
                hyperparameters: HashMap::new(),
                architecture: None,
                resources: ResourceAllocation {
                    cpu: 1.0,
                    memory: 512,
                    gpu: 0.0,
                    time: Duration::from_secs(60),
                },
            },
            dominance_rank: 0,
            crowding_distance: 0.0,
        };

        let result = optimizer.add_solution(solution);
        assert!(result.is_ok());
        assert!(result.expect("add_solution should succeed"));
        assert_eq!(optimizer.pareto_frontier.solutions.len(), 1);
    }

    #[test]
    fn test_dominance_check() {
        let config = MultiObjectiveConfig::default();
        let optimizer = MultiObjectiveOptimizer::new(config);

        let solution1 = MultiObjectiveSolution {
            id: "solution1".to_string(),
            objective_values: vec![1.0, 2.0],
            decision_variables: OptimizationConfiguration {
                algorithm: AlgorithmType::QuantumAnnealing,
                hyperparameters: HashMap::new(),
                architecture: None,
                resources: ResourceAllocation {
                    cpu: 1.0,
                    memory: 512,
                    gpu: 0.0,
                    time: Duration::from_secs(60),
                },
            },
            dominance_rank: 0,
            crowding_distance: 0.0,
        };

        let solution2 = MultiObjectiveSolution {
            id: "solution2".to_string(),
            objective_values: vec![2.0, 1.0],
            decision_variables: OptimizationConfiguration {
                algorithm: AlgorithmType::TabuSearch,
                hyperparameters: HashMap::new(),
                architecture: None,
                resources: ResourceAllocation {
                    cpu: 1.0,
                    memory: 512,
                    gpu: 0.0,
                    time: Duration::from_secs(60),
                },
            },
            dominance_rank: 0,
            crowding_distance: 0.0,
        };

        // Neither solution should dominate the other (trade-off)
        assert!(!optimizer.dominates(&solution1, &solution2));
        assert!(!optimizer.dominates(&solution2, &solution1));
    }

    #[test]
    fn test_weighted_sum_scalarization() {
        let config = MultiObjectiveConfig::default();
        let optimizer = MultiObjectiveOptimizer::new(config);

        let solution = MultiObjectiveSolution {
            id: "test_solution".to_string(),
            objective_values: vec![2.0, 3.0, 1.0],
            decision_variables: OptimizationConfiguration {
                algorithm: AlgorithmType::GeneticAlgorithm,
                hyperparameters: HashMap::new(),
                architecture: None,
                resources: ResourceAllocation {
                    cpu: 1.0,
                    memory: 512,
                    gpu: 0.0,
                    time: Duration::from_secs(60),
                },
            },
            dominance_rank: 0,
            crowding_distance: 0.0,
        };

        let weights = vec![0.5, 0.3, 0.2];
        let score = optimizer.scalarize_weighted_sum(&solution, &weights);

        // Expected: 2.0*0.5 + 3.0*0.3 + 1.0*0.2 = 1.0 + 0.9 + 0.2 = 2.1
        assert!((score - 2.1).abs() < 1e-10);
    }

    #[test]
    fn test_frontier_statistics() {
        let config = MultiObjectiveConfig::default();
        let mut optimizer = MultiObjectiveOptimizer::new(config);

        // Add a solution
        let solution = MultiObjectiveSolution {
            id: "test_solution".to_string(),
            objective_values: vec![1.0, 2.0],
            decision_variables: OptimizationConfiguration {
                algorithm: AlgorithmType::ParticleSwarm,
                hyperparameters: HashMap::new(),
                architecture: None,
                resources: ResourceAllocation {
                    cpu: 1.0,
                    memory: 512,
                    gpu: 0.0,
                    time: Duration::from_secs(60),
                },
            },
            dominance_rank: 0,
            crowding_distance: 0.0,
        };

        optimizer
            .add_solution(solution)
            .expect("add_solution should succeed");

        let stats = optimizer.get_statistics();
        assert_eq!(stats.size, 1);
        assert!(stats.hypervolume > 0.0);
    }

    #[test]
    fn test_solution_selection() {
        let config = MultiObjectiveConfig::default();
        let mut optimizer = MultiObjectiveOptimizer::new(config);

        // Add solutions
        let solution1 = MultiObjectiveSolution {
            id: "solution1".to_string(),
            objective_values: vec![1.0, 2.0],
            decision_variables: OptimizationConfiguration {
                algorithm: AlgorithmType::AntColony,
                hyperparameters: HashMap::new(),
                architecture: None,
                resources: ResourceAllocation {
                    cpu: 1.0,
                    memory: 512,
                    gpu: 0.0,
                    time: Duration::from_secs(60),
                },
            },
            dominance_rank: 0,
            crowding_distance: 0.0,
        };

        let solution2 = MultiObjectiveSolution {
            id: "solution2".to_string(),
            objective_values: vec![2.0, 1.0],
            decision_variables: OptimizationConfiguration {
                algorithm: AlgorithmType::VariableNeighborhood,
                hyperparameters: HashMap::new(),
                architecture: None,
                resources: ResourceAllocation {
                    cpu: 1.0,
                    memory: 512,
                    gpu: 0.0,
                    time: Duration::from_secs(60),
                },
            },
            dominance_rank: 0,
            crowding_distance: 0.0,
        };

        optimizer
            .add_solution(solution1)
            .expect("add_solution for solution1 should succeed");
        optimizer
            .add_solution(solution2)
            .expect("add_solution for solution2 should succeed");

        let selected = optimizer.select_solution();
        assert!(selected.is_ok());
        assert!(selected.expect("select_solution should succeed").is_some());
    }
}