Skip to main content

quantrs2_anneal/active_learning_decomposition/
knowledge_base.rs

1//! Knowledge base components for decomposition
2
3use scirs2_core::ndarray::Array2;
4use std::collections::HashMap;
5use std::time::{Duration, Instant};
6
7use super::{
8    ActionType, ConditionType, DecompositionStrategy, LogicalOperator, PerformanceRecord,
9    RequirementType, RequirementValue, ResourceConstraints, SideEffectType, TrendDirection,
10};
11
12/// Decomposition knowledge base
13#[derive(Debug, Clone)]
14pub struct DecompositionKnowledgeBase {
15    /// Strategy database
16    pub strategy_database: StrategyDatabase,
17    /// Pattern library
18    pub pattern_library: PatternLibrary,
19    /// Performance repository
20    pub performance_repository: PerformanceRepository,
21    /// Rule engine
22    pub rule_engine: RuleEngine,
23}
24
25impl DecompositionKnowledgeBase {
26    pub fn new() -> Result<Self, String> {
27        Ok(Self {
28            strategy_database: StrategyDatabase::new(),
29            pattern_library: PatternLibrary::new(),
30            performance_repository: PerformanceRepository::new(),
31            rule_engine: RuleEngine::new(),
32        })
33    }
34}
35
36/// Strategy database
37#[derive(Debug, Clone)]
38pub struct StrategyDatabase {
39    /// Available strategies
40    pub strategies: Vec<DecompositionStrategy>,
41    /// Strategy relationships
42    pub strategy_relationships: HashMap<String, Vec<String>>,
43    /// Strategy success rates
44    pub success_rates: HashMap<DecompositionStrategy, f64>,
45}
46
47impl StrategyDatabase {
48    #[must_use]
49    pub fn new() -> Self {
50        Self {
51            strategies: vec![
52                DecompositionStrategy::GraphPartitioning,
53                DecompositionStrategy::CommunityDetection,
54                DecompositionStrategy::SpectralClustering,
55                DecompositionStrategy::Hierarchical,
56                DecompositionStrategy::NoDecomposition,
57            ],
58            strategy_relationships: HashMap::new(),
59            success_rates: HashMap::new(),
60        }
61    }
62}
63
64/// Pattern library
65#[derive(Debug, Clone)]
66pub struct PatternLibrary {
67    /// Known patterns
68    pub patterns: Vec<KnownPattern>,
69    /// Pattern index
70    pub pattern_index: HashMap<String, usize>,
71    /// Pattern similarity matrix
72    pub similarity_matrix: Array2<f64>,
73}
74
75impl PatternLibrary {
76    #[must_use]
77    pub fn new() -> Self {
78        Self {
79            patterns: Vec::new(),
80            pattern_index: HashMap::new(),
81            similarity_matrix: Array2::zeros((0, 0)),
82        }
83    }
84}
85
86/// Known pattern
87#[derive(Debug, Clone)]
88pub struct KnownPattern {
89    /// Pattern identifier
90    pub pattern_id: String,
91    /// Pattern description
92    pub description: String,
93    /// Pattern features
94    pub features: scirs2_core::ndarray::Array1<f64>,
95    /// Optimal strategies for this pattern
96    pub optimal_strategies: Vec<DecompositionStrategy>,
97    /// Pattern frequency
98    pub frequency: f64,
99}
100
101/// Performance repository
102#[derive(Debug, Clone)]
103pub struct PerformanceRepository {
104    /// Historical performance data
105    pub historical_data: Vec<HistoricalPerformance>,
106    /// Performance trends
107    pub performance_trends: HashMap<String, PerformanceTrend>,
108    /// Benchmark results
109    pub benchmark_results: Vec<BenchmarkResult>,
110}
111
112impl PerformanceRepository {
113    #[must_use]
114    pub fn new() -> Self {
115        Self {
116            historical_data: Vec::new(),
117            performance_trends: HashMap::new(),
118            benchmark_results: Vec::new(),
119        }
120    }
121}
122
123/// Historical performance data
124#[derive(Debug, Clone)]
125pub struct HistoricalPerformance {
126    /// Problem characteristics
127    pub problem_characteristics: ProblemCharacteristics,
128    /// Strategy applied
129    pub strategy_applied: DecompositionStrategy,
130    /// Performance achieved
131    pub performance_achieved: PerformanceRecord,
132    /// Context information
133    pub context: PerformanceContext,
134}
135
136/// Problem characteristics
137#[derive(Debug, Clone)]
138pub struct ProblemCharacteristics {
139    /// Problem size
140    pub problem_size: usize,
141    /// Problem type
142    pub problem_type: String,
143    /// Structural features
144    pub structural_features: scirs2_core::ndarray::Array1<f64>,
145    /// Complexity indicators
146    pub complexity_indicators: HashMap<String, f64>,
147}
148
149/// Performance context
150#[derive(Debug, Clone)]
151pub struct PerformanceContext {
152    /// Hardware configuration
153    pub hardware_config: String,
154    /// Software configuration
155    pub software_config: String,
156    /// Resource constraints
157    pub resource_constraints: ResourceConstraints,
158    /// Environmental factors
159    pub environmental_factors: HashMap<String, f64>,
160}
161
162/// Performance trend
163#[derive(Debug, Clone)]
164pub struct PerformanceTrend {
165    /// Trend direction
166    pub trend_direction: TrendDirection,
167    /// Trend strength
168    pub trend_strength: f64,
169    /// Trend data points
170    pub data_points: Vec<(f64, f64)>, // (time, performance)
171    /// Trend prediction
172    pub prediction: Option<TrendPrediction>,
173}
174
175/// Trend prediction
176#[derive(Debug, Clone)]
177pub struct TrendPrediction {
178    /// Predicted value
179    pub predicted_value: f64,
180    /// Prediction confidence
181    pub confidence: f64,
182    /// Prediction horizon
183    pub horizon: Duration,
184}
185
186/// Benchmark result
187#[derive(Debug, Clone)]
188pub struct BenchmarkResult {
189    /// Benchmark name
190    pub benchmark_name: String,
191    /// Problem set
192    pub problem_set: Vec<String>,
193    /// Strategy results
194    pub strategy_results: HashMap<DecompositionStrategy, f64>,
195    /// Best performing strategy
196    pub best_strategy: DecompositionStrategy,
197}
198
199/// Rule engine for decomposition decisions
200#[derive(Debug, Clone)]
201pub struct RuleEngine {
202    /// Rule set
203    pub rules: Vec<DecompositionRule>,
204    /// Rule priorities
205    pub rule_priorities: HashMap<String, f64>,
206    /// Rule application history
207    pub application_history: Vec<RuleApplication>,
208}
209
210impl RuleEngine {
211    #[must_use]
212    pub fn new() -> Self {
213        Self {
214            rules: Vec::new(),
215            rule_priorities: HashMap::new(),
216            application_history: Vec::new(),
217        }
218    }
219}
220
221/// Decomposition rule
222#[derive(Debug, Clone)]
223pub struct DecompositionRule {
224    /// Rule identifier
225    pub rule_id: String,
226    /// Rule condition
227    pub condition: RuleCondition,
228    /// Rule action
229    pub action: RuleAction,
230    /// Rule confidence
231    pub confidence: f64,
232    /// Rule applicability
233    pub applicability: RuleApplicability,
234}
235
236/// Rule condition
237#[derive(Debug, Clone)]
238pub struct RuleCondition {
239    /// Condition type
240    pub condition_type: ConditionType,
241    /// Condition parameters
242    pub parameters: HashMap<String, f64>,
243    /// Logical operator
244    pub logical_operator: LogicalOperator,
245}
246
247/// Rule action
248#[derive(Debug, Clone)]
249pub struct RuleAction {
250    /// Action type
251    pub action_type: ActionType,
252    /// Action parameters
253    pub parameters: HashMap<String, f64>,
254    /// Expected outcome
255    pub expected_outcome: ExpectedOutcome,
256}
257
258/// Expected outcome
259#[derive(Debug, Clone)]
260pub struct ExpectedOutcome {
261    /// Performance improvement
262    pub performance_improvement: f64,
263    /// Confidence in outcome
264    pub outcome_confidence: f64,
265    /// Side effects
266    pub side_effects: Vec<SideEffect>,
267}
268
269/// Side effect
270#[derive(Debug, Clone)]
271pub struct SideEffect {
272    /// Effect type
273    pub effect_type: SideEffectType,
274    /// Effect magnitude
275    pub magnitude: f64,
276    /// Effect probability
277    pub probability: f64,
278}
279
280/// Rule applicability
281#[derive(Debug, Clone)]
282pub struct RuleApplicability {
283    /// Problem types where rule applies
284    pub applicable_problem_types: Vec<String>,
285    /// Size range where rule applies
286    pub applicable_size_range: (usize, usize),
287    /// Context requirements
288    pub context_requirements: Vec<ContextRequirement>,
289}
290
291/// Context requirement
292#[derive(Debug, Clone)]
293pub struct ContextRequirement {
294    /// Requirement type
295    pub requirement_type: RequirementType,
296    /// Required value or range
297    pub required_value: RequirementValue,
298}
299
300/// Rule application record
301#[derive(Debug, Clone)]
302pub struct RuleApplication {
303    /// Application timestamp
304    pub timestamp: Instant,
305    /// Rule applied
306    pub rule_id: String,
307    /// Problem context
308    pub problem_context: ProblemCharacteristics,
309    /// Application result
310    pub result: ApplicationResult,
311}
312
313/// Application result
314#[derive(Debug, Clone)]
315pub struct ApplicationResult {
316    /// Success status
317    pub success: bool,
318    /// Performance impact
319    pub performance_impact: f64,
320    /// User satisfaction
321    pub user_satisfaction: Option<f64>,
322    /// Lessons learned
323    pub lessons_learned: Vec<String>,
324}