quantrs2-tytan 0.1.3

High-level quantum annealing interface inspired by Tytan 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
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
//! Sampler framework extensions for advanced optimization strategies.
//!
//! This module provides plugin architecture, hyperparameter optimization,
//! ensemble methods, and adaptive sampling strategies.

#![allow(dead_code)]

#[cfg(feature = "dwave")]
use crate::compile::CompiledModel;
use crate::sampler::{SampleResult, Sampler, SamplerError, SamplerResult};
use scirs2_core::ndarray::{Array, Array2, IxDyn};
use scirs2_core::random::prelude::*;
use scirs2_core::random::prelude::*;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

#[cfg(feature = "scirs")]
use crate::scirs_stub::{
    scirs2_ml::{CrossValidation, RandomForest},
    scirs2_optimization::bayesian::{AcquisitionFunction, BayesianOptimizer, KernelType},
};

/// Plugin trait for custom samplers
pub trait SamplerPlugin: Send + Sync {
    /// Plugin name
    fn name(&self) -> &str;

    /// Plugin version
    fn version(&self) -> &str;

    /// Initialize plugin
    fn initialize(&mut self, config: &HashMap<String, String>) -> Result<(), String>;

    /// Create sampler instance
    fn create_sampler(&self) -> Box<dyn Sampler>;

    /// Get default configuration
    fn default_config(&self) -> HashMap<String, String>;

    /// Validate configuration
    fn validate_config(&self, config: &HashMap<String, String>) -> Result<(), String>;
}

/// Plugin manager for dynamic sampler loading
pub struct PluginManager {
    /// Registered plugins
    plugins: HashMap<String, Box<dyn SamplerPlugin>>,
    /// Plugin configurations
    configs: HashMap<String, HashMap<String, String>>,
}

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

impl PluginManager {
    /// Create new plugin manager
    pub fn new() -> Self {
        Self {
            plugins: HashMap::new(),
            configs: HashMap::new(),
        }
    }

    /// Register a plugin
    pub fn register_plugin(&mut self, plugin: Box<dyn SamplerPlugin>) -> Result<(), String> {
        let name = plugin.name().to_string();

        if self.plugins.contains_key(&name) {
            return Err(format!("Plugin {name} already registered"));
        }

        let default_config = plugin.default_config();
        self.configs.insert(name.clone(), default_config);
        self.plugins.insert(name, plugin);

        Ok(())
    }

    /// Configure plugin
    pub fn configure_plugin(
        &mut self,
        name: &str,
        config: HashMap<String, String>,
    ) -> Result<(), String> {
        let plugin = self
            .plugins
            .get(name)
            .ok_or_else(|| format!("Plugin {name} not found"))?;

        plugin.validate_config(&config)?;
        self.configs.insert(name.to_string(), config);

        Ok(())
    }

    /// Create sampler from plugin
    pub fn create_sampler(&mut self, name: &str) -> Result<Box<dyn Sampler>, String> {
        let plugin = self
            .plugins
            .get_mut(name)
            .ok_or_else(|| format!("Plugin {name} not found"))?;

        let config = self.configs.get(name).cloned().unwrap_or_default();
        plugin.initialize(&config)?;

        Ok(plugin.create_sampler())
    }

    /// List available plugins
    pub fn list_plugins(&self) -> Vec<PluginInfo> {
        self.plugins
            .values()
            .map(|p| PluginInfo {
                name: p.name().to_string(),
                version: p.version().to_string(),
            })
            .collect()
    }
}

#[derive(Debug, Clone)]
pub struct PluginInfo {
    pub name: String,
    pub version: String,
}

/// Hyperparameter optimization for samplers
pub struct HyperparameterOptimizer {
    /// Parameter search space
    search_space: HashMap<String, ParameterSpace>,
    /// Optimization method
    method: OptimizationMethod,
    /// Number of trials
    num_trials: usize,
    /// Cross-validation folds
    cv_folds: usize,
}

#[derive(Debug, Clone)]
pub enum ParameterSpace {
    /// Continuous parameter
    Continuous { min: f64, max: f64, log_scale: bool },
    /// Discrete parameter
    Discrete { values: Vec<f64> },
    /// Categorical parameter
    Categorical { options: Vec<String> },
}

#[derive(Debug, Clone)]
pub enum OptimizationMethod {
    /// Random search
    RandomSearch,
    /// Grid search
    GridSearch { resolution: usize },
    /// Bayesian optimization
    #[cfg(feature = "scirs")]
    Bayesian {
        kernel: KernelType,
        acquisition: AcquisitionFunction,
        exploration: f64,
    },
    /// Evolutionary optimization
    Evolutionary {
        population_size: usize,
        mutation_rate: f64,
    },
}

impl HyperparameterOptimizer {
    /// Create new optimizer
    pub fn new(method: OptimizationMethod, num_trials: usize) -> Self {
        Self {
            search_space: HashMap::new(),
            method,
            num_trials,
            cv_folds: 5,
        }
    }

    /// Add parameter to search space
    pub fn add_parameter(&mut self, name: &str, space: ParameterSpace) {
        self.search_space.insert(name.to_string(), space);
    }

    /// Optimize hyperparameters
    #[cfg(feature = "dwave")]
    pub fn optimize<F>(
        &self,
        objective: F,
        validation_problems: &[CompiledModel],
    ) -> Result<OptimizationResult, String>
    where
        F: Fn(&HashMap<String, f64>) -> Box<dyn Sampler>,
    {
        match &self.method {
            OptimizationMethod::RandomSearch => self.random_search(objective, validation_problems),
            OptimizationMethod::GridSearch { resolution } => {
                self.grid_search(objective, validation_problems, *resolution)
            }
            #[cfg(feature = "scirs")]
            OptimizationMethod::Bayesian {
                kernel,
                acquisition,
                exploration,
            } => self.bayesian_optimization(
                objective,
                validation_problems,
                *kernel,
                *acquisition,
                *exploration,
            ),
            OptimizationMethod::Evolutionary {
                population_size,
                mutation_rate,
            } => self.evolutionary_optimization(
                objective,
                validation_problems,
                *population_size,
                *mutation_rate,
            ),
        }
    }

    /// Random search implementation
    #[cfg(feature = "dwave")]
    fn random_search<F>(
        &self,
        objective: F,
        validation_problems: &[CompiledModel],
    ) -> Result<OptimizationResult, String>
    where
        F: Fn(&HashMap<String, f64>) -> Box<dyn Sampler>,
    {
        let mut rng = thread_rng();
        let mut best_params = HashMap::new();
        let mut best_score = f64::INFINITY;
        let mut history = Vec::new();

        for trial in 0..self.num_trials {
            // Sample random parameters
            let mut params = self.sample_parameters(&mut rng)?;

            // Evaluate
            let sampler = objective(&params);
            let mut score = self.evaluate_sampler(sampler, validation_problems)?;

            history.push(TrialResult {
                parameters: params.clone(),
                score,
                iteration: trial,
            });

            if score < best_score {
                best_score = score;
                best_params = params;
            }
        }

        let convergence_curve = self.compute_convergence_curve(&history);
        Ok(OptimizationResult {
            best_parameters: best_params,
            best_score,
            history,
            convergence_curve,
        })
    }

    /// Grid search implementation
    #[cfg(feature = "dwave")]
    fn grid_search<F>(
        &self,
        objective: F,
        validation_problems: &[CompiledModel],
        resolution: usize,
    ) -> Result<OptimizationResult, String>
    where
        F: Fn(&HashMap<String, f64>) -> Box<dyn Sampler>,
    {
        // Generate grid points
        let grid_points = self.generate_grid(resolution)?;

        let mut best_params = HashMap::new();
        let mut best_score = f64::INFINITY;
        let mut history = Vec::new();

        for (i, params) in grid_points.iter().enumerate() {
            let sampler = objective(params);
            let mut score = self.evaluate_sampler(sampler, validation_problems)?;

            history.push(TrialResult {
                parameters: params.clone(),
                score,
                iteration: i,
            });

            if score < best_score {
                best_score = score;
                best_params = params.clone();
            }
        }

        let convergence_curve = self.compute_convergence_curve(&history);
        Ok(OptimizationResult {
            best_parameters: best_params,
            best_score,
            history,
            convergence_curve,
        })
    }

    /// Bayesian optimization implementation
    #[cfg(all(feature = "scirs", feature = "dwave"))]
    fn bayesian_optimization<F>(
        &self,
        objective: F,
        validation_problems: &[CompiledModel],
        kernel: KernelType,
        acquisition: AcquisitionFunction,
        exploration: f64,
    ) -> Result<OptimizationResult, String>
    where
        F: Fn(&HashMap<String, f64>) -> Box<dyn Sampler>,
    {
        use scirs2_core::ndarray::Array1;

        let dim = self.search_space.len();
        let mut optimizer = BayesianOptimizer::new(dim, kernel, acquisition, exploration)
            .map_err(|e| e.to_string())?;

        let mut history = Vec::new();
        let mut x_data = Vec::new();
        let mut y_data = Vec::new();

        // Initial random samples
        let mut rng = thread_rng();
        for _ in 0..std::cmp::min(10, self.num_trials / 4) {
            let mut params = self.sample_parameters(&mut rng)?;
            let sampler = objective(&params);
            let mut score = self.evaluate_sampler(sampler, validation_problems)?;

            let mut x = self.params_to_array(&params)?;
            x_data.push(x);
            y_data.push(score);

            history.push(TrialResult {
                parameters: params,
                score,
                iteration: history.len(),
            });
        }

        // Bayesian optimization loop
        let y_array = Array1::from_vec(y_data.clone());
        optimizer
            .update(&x_data, &y_array)
            .map_err(|e| e.to_string())?;

        for _ in history.len()..self.num_trials {
            // Suggest next point
            let x_next = optimizer.suggest_next().map_err(|e| e.to_string())?;
            let mut params = self.array_to_params(&x_next)?;

            // Evaluate
            let sampler = objective(&params);
            let mut score = self.evaluate_sampler(sampler, validation_problems)?;

            // Update model
            x_data.push(x_next);
            y_data.push(score);
            let y_array = Array1::from_vec(y_data.clone());
            optimizer
                .update(&x_data, &y_array)
                .map_err(|e| e.to_string())?;

            history.push(TrialResult {
                parameters: params,
                score,
                iteration: history.len(),
            });
        }

        // Find best
        let (best_idx, &best_score) = y_data
            .iter()
            .enumerate()
            .min_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
            .ok_or_else(|| "No optimization trials completed".to_string())?;

        let best_params = self.array_to_params(&x_data[best_idx])?;

        let convergence_curve = self.compute_convergence_curve(&history);
        Ok(OptimizationResult {
            best_parameters: best_params,
            best_score,
            history,
            convergence_curve,
        })
    }

    /// Evolutionary optimization (placeholder)
    #[cfg(feature = "dwave")]
    fn evolutionary_optimization<F>(
        &self,
        _objective: F,
        _validation_problems: &[CompiledModel],
        _population_size: usize,
        _mutation_rate: f64,
    ) -> Result<OptimizationResult, String>
    where
        F: Fn(&HashMap<String, f64>) -> Box<dyn Sampler>,
    {
        Err("Evolutionary optimization not yet implemented".to_string())
    }

    /// Sample parameters from search space
    fn sample_parameters(&self, rng: &mut impl Rng) -> Result<HashMap<String, f64>, String> {
        let mut params = HashMap::new();

        for (name, space) in &self.search_space {
            let value = match space {
                ParameterSpace::Continuous {
                    min,
                    max,
                    log_scale,
                } => {
                    if *log_scale {
                        let log_min = min.ln();
                        let log_max = max.ln();
                        let log_val = rng.random_range(log_min..log_max);
                        log_val.exp()
                    } else {
                        rng.random_range(*min..*max)
                    }
                }
                ParameterSpace::Discrete { values } => values[rng.random_range(0..values.len())],
                ParameterSpace::Categorical { options } => {
                    // Return index for categorical
                    rng.random_range(0..options.len()) as f64
                }
            };

            params.insert(name.clone(), value);
        }

        Ok(params)
    }

    /// Generate grid points
    fn generate_grid(&self, resolution: usize) -> Result<Vec<HashMap<String, f64>>, String> {
        // Simplified: generate regular grid
        let mut grid_points = Vec::new();

        // This would need proper multi-dimensional grid generation
        // For now, just sample uniformly
        let total_points = resolution.pow(self.search_space.len() as u32);
        let mut rng = thread_rng();

        for _ in 0..total_points.min(self.num_trials) {
            grid_points.push(self.sample_parameters(&mut rng)?);
        }

        Ok(grid_points)
    }

    /// Convert parameters to array
    #[cfg(feature = "scirs")]
    fn params_to_array(
        &self,
        params: &HashMap<String, f64>,
    ) -> Result<scirs2_core::ndarray::Array1<f64>, String> {
        let mut values = Vec::new();

        // Ensure consistent ordering
        let mut names: Vec<_> = self.search_space.keys().collect();
        names.sort();

        for name in names {
            values.push(params.get(name).copied().unwrap_or(0.0));
        }

        Ok(scirs2_core::ndarray::Array1::from_vec(values))
    }

    /// Convert array to parameters
    #[cfg(feature = "scirs")]
    fn array_to_params(
        &self,
        array: &scirs2_core::ndarray::Array1<f64>,
    ) -> Result<HashMap<String, f64>, String> {
        let mut params = HashMap::new();

        let mut names: Vec<_> = self.search_space.keys().collect();
        names.sort();

        for (i, name) in names.iter().enumerate() {
            params.insert((*name).clone(), array[i]);
        }

        Ok(params)
    }

    /// Evaluate sampler performance
    #[cfg(feature = "dwave")]
    fn evaluate_sampler(
        &self,
        mut sampler: Box<dyn Sampler>,
        problems: &[CompiledModel],
    ) -> Result<f64, String> {
        let mut scores = Vec::new();

        for problem in problems {
            let mut qubo = problem.to_qubo();
            let start = Instant::now();

            let qubo_tuple = (qubo.to_dense_matrix(), qubo.variable_map());
            let mut results = sampler
                .run_qubo(&qubo_tuple, 100)
                .map_err(|e| format!("Sampler error: {e:?}"))?;

            let elapsed = start.elapsed();

            // Score based on solution quality and time
            let mut best_energy = results.first().map_or(f64::INFINITY, |r| r.energy);

            let time_penalty = elapsed.as_secs_f64();
            let mut score = 0.1f64.mul_add(time_penalty, best_energy);

            scores.push(score);
        }

        // Return average score
        Ok(scores.iter().sum::<f64>() / scores.len() as f64)
    }

    /// Compute convergence curve
    fn compute_convergence_curve(&self, history: &[TrialResult]) -> Vec<f64> {
        let mut curve = Vec::new();
        let mut best_so_far = f64::INFINITY;

        for trial in history {
            best_so_far = best_so_far.min(trial.score);
            curve.push(best_so_far);
        }

        curve
    }
}

#[derive(Debug, Clone)]
pub struct OptimizationResult {
    pub best_parameters: HashMap<String, f64>,
    pub best_score: f64,
    pub history: Vec<TrialResult>,
    pub convergence_curve: Vec<f64>,
}

#[derive(Debug, Clone)]
pub struct TrialResult {
    pub parameters: HashMap<String, f64>,
    pub score: f64,
    pub iteration: usize,
}

/// Ensemble sampler that combines multiple sampling strategies
pub struct EnsembleSampler {
    /// Base samplers
    samplers: Vec<Box<dyn Sampler>>,
    /// Combination method
    method: EnsembleMethod,
    /// Weights for weighted combination
    weights: Option<Vec<f64>>,
}

#[derive(Debug, Clone)]
pub enum EnsembleMethod {
    /// Simple voting
    Voting,
    /// Weighted voting
    WeightedVoting,
    /// Best of all
    BestOf,
    /// Sequential refinement
    Sequential,
    /// Parallel with aggregation
    Parallel,
}

impl EnsembleSampler {
    /// Create new ensemble sampler
    pub fn new(samplers: Vec<Box<dyn Sampler>>, method: EnsembleMethod) -> Self {
        Self {
            samplers,
            method,
            weights: None,
        }
    }

    /// Set weights for weighted voting
    pub fn with_weights(mut self, weights: Vec<f64>) -> Self {
        self.weights = Some(weights);
        self
    }
}

impl Sampler for EnsembleSampler {
    fn run_qubo(
        &self,
        qubo: &(Array2<f64>, HashMap<String, usize>),
        shots: usize,
    ) -> SamplerResult<Vec<SampleResult>> {
        match &self.method {
            EnsembleMethod::Voting => self.voting_ensemble(qubo, shots),
            EnsembleMethod::WeightedVoting => self.weighted_voting_ensemble(qubo, shots),
            EnsembleMethod::BestOf => self.best_of_ensemble(qubo, shots),
            EnsembleMethod::Sequential => self.sequential_ensemble(qubo, shots),
            EnsembleMethod::Parallel => self.parallel_ensemble(qubo, shots),
        }
    }

    fn run_hobo(
        &self,
        hobo: &(Array<f64, IxDyn>, HashMap<String, usize>),
        shots: usize,
    ) -> SamplerResult<Vec<SampleResult>> {
        // Similar implementation for HOBO
        match &self.method {
            EnsembleMethod::Voting => self.voting_ensemble_hobo(hobo, shots),
            _ => Err(SamplerError::InvalidParameter(
                "HOBO ensemble not fully implemented".to_string(),
            )),
        }
    }
}

impl EnsembleSampler {
    /// Simple voting ensemble
    fn voting_ensemble(
        &self,
        qubo: &(Array2<f64>, HashMap<String, usize>),
        shots: usize,
    ) -> SamplerResult<Vec<SampleResult>> {
        let shots_per_sampler = shots / self.samplers.len();
        let mut all_results = Vec::new();

        // Run each sampler
        for sampler in &self.samplers {
            let results = sampler.run_qubo(qubo, shots_per_sampler)?;
            all_results.extend(results);
        }

        // Aggregate by voting
        let mut vote_counts: HashMap<Vec<bool>, (f64, usize)> = HashMap::new();

        for result in all_results {
            let state: Vec<bool> = qubo.1.keys().map(|var| result.assignments[var]).collect();

            let entry = vote_counts.entry(state).or_insert((result.energy, 0));
            entry.1 += result.occurrences;
        }

        // Convert back to results
        let mut final_results: Vec<SampleResult> = vote_counts
            .into_iter()
            .map(|(state, (energy, count))| {
                let assignments: HashMap<String, bool> = qubo
                    .1
                    .iter()
                    .zip(state.iter())
                    .map(|((var, _), &val)| (var.clone(), val))
                    .collect();

                SampleResult {
                    assignments,
                    energy,
                    occurrences: count,
                }
            })
            .collect();

        final_results.sort_by(|a, b| {
            a.energy
                .partial_cmp(&b.energy)
                .unwrap_or(std::cmp::Ordering::Equal)
        });

        Ok(final_results)
    }

    /// Weighted voting ensemble
    fn weighted_voting_ensemble(
        &self,
        qubo: &(Array2<f64>, HashMap<String, usize>),
        shots: usize,
    ) -> SamplerResult<Vec<SampleResult>> {
        let weights = self.weights.as_ref().ok_or_else(|| {
            SamplerError::InvalidParameter("Weights not set for weighted voting".to_string())
        })?;

        if weights.len() != self.samplers.len() {
            return Err(SamplerError::InvalidParameter(
                "Number of weights must match number of samplers".to_string(),
            ));
        }

        // Normalize weights
        let total_weight: f64 = weights.iter().sum();
        let normalized: Vec<f64> = weights.iter().map(|&w| w / total_weight).collect();

        let mut all_results = Vec::new();

        // Run each sampler with weighted shots
        for (sampler, &weight) in self.samplers.iter().zip(normalized.iter()) {
            let sampler_shots = (shots as f64 * weight).round() as usize;
            if sampler_shots > 0 {
                let results = sampler.run_qubo(qubo, sampler_shots)?;
                all_results.extend(results);
            }
        }

        // Aggregate results
        self.aggregate_results(all_results, &qubo.1)
    }

    /// Best-of ensemble
    fn best_of_ensemble(
        &self,
        qubo: &(Array2<f64>, HashMap<String, usize>),
        shots: usize,
    ) -> SamplerResult<Vec<SampleResult>> {
        let shots_per_sampler = shots / self.samplers.len();
        let mut best_results = Vec::new();
        let mut best_energy = f64::INFINITY;

        // Run each sampler and keep best
        for sampler in &self.samplers {
            let results = sampler.run_qubo(qubo, shots_per_sampler)?;

            if let Some(best) = results.first() {
                if best.energy < best_energy {
                    best_energy = best.energy;
                    best_results = results;
                }
            }
        }

        Ok(best_results)
    }

    /// Sequential refinement ensemble
    fn sequential_ensemble(
        &self,
        qubo: &(Array2<f64>, HashMap<String, usize>),
        shots: usize,
    ) -> SamplerResult<Vec<SampleResult>> {
        if self.samplers.is_empty() {
            return Ok(Vec::new());
        }

        // Start with first sampler
        let mut current_best = self.samplers[0].run_qubo(qubo, shots)?;

        // Refine with subsequent samplers
        for sampler in self.samplers.iter().skip(1) {
            // Use best solutions as warm start (if sampler supports it)
            // For now, just run independently
            let refined = sampler.run_qubo(qubo, shots / self.samplers.len())?;

            // Merge results
            current_best.extend(refined);
            current_best.sort_by(|a, b| {
                a.energy
                    .partial_cmp(&b.energy)
                    .unwrap_or(std::cmp::Ordering::Equal)
            });
            current_best.truncate(shots);
        }

        Ok(current_best)
    }

    /// Parallel ensemble with aggregation
    fn parallel_ensemble(
        &self,
        qubo: &(Array2<f64>, HashMap<String, usize>),
        shots: usize,
    ) -> SamplerResult<Vec<SampleResult>> {
        let shots_per_sampler = shots / self.samplers.len();
        let _handles: Vec<std::thread::JoinHandle<()>> = Vec::new();

        // Would need to make samplers thread-safe for real parallel execution
        // For now, sequential execution
        let mut all_results = Vec::new();

        for sampler in &self.samplers {
            let results = sampler.run_qubo(qubo, shots_per_sampler)?;
            all_results.extend(results);
        }

        self.aggregate_results(all_results, &qubo.1)
    }

    /// Aggregate results from multiple samplers
    fn aggregate_results(
        &self,
        results: Vec<SampleResult>,
        var_map: &HashMap<String, usize>,
    ) -> SamplerResult<Vec<SampleResult>> {
        let mut aggregated: HashMap<Vec<bool>, (f64, usize)> = HashMap::new();

        for result in results {
            let state: Vec<bool> = var_map.keys().map(|var| result.assignments[var]).collect();

            let entry = aggregated.entry(state).or_insert((result.energy, 0));

            // Keep minimum energy for duplicates
            entry.0 = entry.0.min(result.energy);
            entry.1 += result.occurrences;
        }

        let mut final_results: Vec<SampleResult> = aggregated
            .into_iter()
            .map(|(state, (energy, count))| {
                let assignments: HashMap<String, bool> = var_map
                    .iter()
                    .zip(state.iter())
                    .map(|((var, _), &val)| (var.clone(), val))
                    .collect();

                SampleResult {
                    assignments,
                    energy,
                    occurrences: count,
                }
            })
            .collect();

        final_results.sort_by(|a, b| {
            a.energy
                .partial_cmp(&b.energy)
                .unwrap_or(std::cmp::Ordering::Equal)
        });

        Ok(final_results)
    }

    /// Voting ensemble for HOBO
    fn voting_ensemble_hobo(
        &self,
        hobo: &(Array<f64, IxDyn>, HashMap<String, usize>),
        shots: usize,
    ) -> SamplerResult<Vec<SampleResult>> {
        // Similar to QUBO voting but for HOBO
        let shots_per_sampler = shots / self.samplers.len();
        let mut all_results = Vec::new();

        for sampler in &self.samplers {
            let results = sampler.run_hobo(hobo, shots_per_sampler)?;
            all_results.extend(results);
        }

        self.aggregate_results(all_results, &hobo.1)
    }
}

/// Adaptive sampling strategy
pub struct AdaptiveSampler<S: Sampler> {
    /// Base sampler
    base_sampler: S,
    /// Adaptation strategy
    strategy: AdaptationStrategy,
    /// Performance history
    history: Arc<Mutex<PerformanceHistory>>,
}

#[derive(Debug, Clone)]
pub enum AdaptationStrategy {
    /// Temperature adaptation
    TemperatureAdaptive {
        initial_range: (f64, f64),
        adaptation_rate: f64,
    },
    /// Population size adaptation
    PopulationAdaptive {
        min_size: usize,
        max_size: usize,
        growth_rate: f64,
    },
    /// Multi-armed bandit for strategy selection
    BanditAdaptive {
        strategies: Vec<String>,
        exploration_rate: f64,
    },
    /// Reinforcement learning based
    RLAdaptive {
        state_features: Vec<String>,
        action_space: Vec<String>,
    },
}

#[derive(Default)]
struct PerformanceHistory {
    energies: Vec<f64>,
    times: Vec<Duration>,
    improvements: Vec<f64>,
    parameters: Vec<HashMap<String, f64>>,
}

impl<S: Sampler> AdaptiveSampler<S> {
    /// Create new adaptive sampler
    pub fn new(base_sampler: S, strategy: AdaptationStrategy) -> Self {
        Self {
            base_sampler,
            strategy,
            history: Arc::new(Mutex::new(PerformanceHistory::default())),
        }
    }

    /// Adapt parameters based on performance
    fn adapt_parameters(&self) -> HashMap<String, f64> {
        let history = self
            .history
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());

        match &self.strategy {
            AdaptationStrategy::TemperatureAdaptive {
                initial_range,
                adaptation_rate,
            } => {
                let mut params = HashMap::new();

                // Adapt temperature based on acceptance rate
                let (min_temp, max_temp) = initial_range;
                let temp = if history.improvements.len() > 10 {
                    let recent_improvements: f64 =
                        history.improvements.iter().rev().take(10).sum::<f64>() / 10.0;

                    if recent_improvements < 0.1 {
                        // Low improvement: increase temperature
                        min_temp + (max_temp - min_temp) * (1.0 - adaptation_rate)
                    } else {
                        // Good improvement: decrease temperature
                        min_temp + (max_temp - min_temp) * adaptation_rate
                    }
                } else {
                    (min_temp + max_temp) / 2.0
                };

                params.insert("temperature".to_string(), temp);
                params
            }
            _ => HashMap::new(),
        }
    }
}

impl<S: Sampler> Sampler for AdaptiveSampler<S> {
    fn run_qubo(
        &self,
        qubo: &(Array2<f64>, HashMap<String, usize>),
        shots: usize,
    ) -> SamplerResult<Vec<SampleResult>> {
        // Adapt parameters
        let params = self.adapt_parameters();

        // Run base sampler (would need to apply params)
        let start = Instant::now();
        let results = self.base_sampler.run_qubo(qubo, shots)?;
        let elapsed = start.elapsed();

        // Update history
        if let Some(best) = results.first() {
            let mut history = self
                .history
                .lock()
                .unwrap_or_else(|poisoned| poisoned.into_inner());

            let improvement = if let Some(&last) = history.energies.last() {
                (last - best.energy) / last.abs().max(1.0)
            } else {
                1.0
            };

            history.energies.push(best.energy);
            history.times.push(elapsed);
            history.improvements.push(improvement);
            history.parameters.push(params);
        }

        Ok(results)
    }

    fn run_hobo(
        &self,
        hobo: &(Array<f64, IxDyn>, HashMap<String, usize>),
        shots: usize,
    ) -> SamplerResult<Vec<SampleResult>> {
        // Similar adaptation for HOBO
        self.base_sampler.run_hobo(hobo, shots)
    }
}

/// Cross-validation for sampler evaluation
pub struct SamplerCrossValidation {
    /// Number of folds
    n_folds: usize,
    /// Evaluation metric
    metric: EvaluationMetric,
}

#[derive(Debug, Clone)]
pub enum EvaluationMetric {
    /// Best energy found
    BestEnergy,
    /// Average of top-k energies
    TopKAverage(usize),
    /// Time to solution
    TimeToSolution(f64),
    /// Success probability
    SuccessProbability(f64),
}

impl SamplerCrossValidation {
    /// Create new cross-validation
    pub const fn new(n_folds: usize, metric: EvaluationMetric) -> Self {
        Self { n_folds, metric }
    }

    /// Evaluate sampler with cross-validation
    #[cfg(feature = "dwave")]
    pub fn evaluate<S: Sampler>(
        &self,
        sampler: &S,
        problems: &[CompiledModel],
        shots_per_problem: usize,
    ) -> Result<CrossValidationResult, String> {
        let n_problems = problems.len();
        let fold_size = n_problems / self.n_folds;

        let mut fold_scores = Vec::new();

        for fold in 0..self.n_folds {
            let test_start = fold * fold_size;
            let test_end = if fold == self.n_folds - 1 {
                n_problems
            } else {
                (fold + 1) * fold_size
            };

            let test_problems = &problems[test_start..test_end];

            // Evaluate on test fold
            let mut scores = Vec::new();
            for problem in test_problems {
                let mut score = self.evaluate_single(sampler, problem, shots_per_problem)?;
                scores.push(score);
            }

            let fold_score = scores.iter().sum::<f64>() / scores.len() as f64;
            fold_scores.push(fold_score);
        }

        let mean_score = fold_scores.iter().sum::<f64>() / fold_scores.len() as f64;
        let variance = fold_scores
            .iter()
            .map(|&s| (s - mean_score).powi(2))
            .sum::<f64>()
            / fold_scores.len() as f64;

        Ok(CrossValidationResult {
            mean_score,
            std_error: variance.sqrt(),
            fold_scores,
        })
    }

    /// Evaluate single problem
    #[cfg(feature = "dwave")]
    fn evaluate_single<S: Sampler>(
        &self,
        sampler: &S,
        problem: &CompiledModel,
        shots: usize,
    ) -> Result<f64, String> {
        let mut qubo = problem.to_qubo();
        let qubo_tuple = (qubo.to_dense_matrix(), qubo.variable_map());
        let start = Instant::now();
        let mut results = sampler
            .run_qubo(&qubo_tuple, shots)
            .map_err(|e| format!("Sampler error: {e:?}"))?;
        let elapsed = start.elapsed();

        match &self.metric {
            EvaluationMetric::BestEnergy => Ok(results.first().map_or(f64::INFINITY, |r| r.energy)),
            EvaluationMetric::TopKAverage(k) => {
                let sum: f64 = results.iter().take(*k).map(|r| r.energy).sum();
                Ok(sum / (*k).min(results.len()) as f64)
            }
            EvaluationMetric::TimeToSolution(threshold) => {
                let found = results.iter().any(|r| r.energy <= *threshold);
                Ok(if found {
                    elapsed.as_secs_f64()
                } else {
                    f64::INFINITY
                })
            }
            EvaluationMetric::SuccessProbability(threshold) => {
                let successes = results
                    .iter()
                    .filter(|r| r.energy <= *threshold)
                    .map(|r| r.occurrences)
                    .sum::<usize>();
                Ok(successes as f64 / shots as f64)
            }
        }
    }
}

#[derive(Debug, Clone)]
pub struct CrossValidationResult {
    pub mean_score: f64,
    pub std_error: f64,
    pub fold_scores: Vec<f64>,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::sampler::SASampler;

    #[test]
    fn test_plugin_manager() {
        let manager = PluginManager::new();

        // Would need actual plugin implementation to test
        assert_eq!(manager.list_plugins().len(), 0);
    }

    #[test]
    fn test_hyperparameter_space() {
        let mut optimizer = HyperparameterOptimizer::new(OptimizationMethod::RandomSearch, 10);

        optimizer.add_parameter(
            "temperature",
            ParameterSpace::Continuous {
                min: 0.1,
                max: 10.0,
                log_scale: true,
            },
        );

        optimizer.add_parameter(
            "sweeps",
            ParameterSpace::Discrete {
                values: vec![100.0, 500.0, 1000.0],
            },
        );

        // Would need actual optimization to test further
    }

    #[test]
    fn test_ensemble_sampler() {
        let samplers: Vec<Box<dyn Sampler>> = vec![
            Box::new(SASampler::new(Some(42))),
            Box::new(SASampler::new(Some(43))),
        ];

        let ensemble = EnsembleSampler::new(samplers, EnsembleMethod::Voting);

        // Would need QUBO problem to test
    }
}