Skip to main content

scirs2_ndimage/ai_driven_adaptive_processing/
state.rs

1//! State Management for AI-Driven Adaptive Processing
2//!
3//! This module handles the main processing state, experience buffers,
4//! and state transitions for the AI-driven adaptive processing system.
5
6use scirs2_core::ndarray::{Array1, Array2, Array3};
7use std::collections::{HashMap, VecDeque};
8
9use super::config::ImagePattern;
10use super::knowledge::{MultiModalKnowledgeBase, ProcessingContext};
11use super::learning::{
12    ContinualLearningState, ExplanationTracker, FewShotLearningEntry, NeuralModel,
13    ProcessingExperience, TransferLearningModel,
14};
15use super::strategies::ProcessingStrategy;
16
17/// AI-Driven Processing State
18#[derive(Debug, Clone)]
19pub struct AIProcessingState {
20    /// Neural network weights for decision making
21    pub decision_network: Array3<f64>,
22    /// Experience replay buffer
23    pub experience_buffer: VecDeque<ProcessingExperience>,
24    /// Learned processing strategies
25    pub processing_strategies: HashMap<ImagePattern, ProcessingStrategy>,
26    /// Performance history
27    pub performancehistory: VecDeque<f64>,
28    /// Multi-modal knowledge base
29    pub knowledge_base: MultiModalKnowledgeBase,
30    /// Current processing context
31    pub currentcontext: ProcessingContext,
32    /// Continual learning state
33    pub continual_learningstate: ContinualLearningState,
34    /// Explainability tracking
35    pub explanation_tracker: ExplanationTracker,
36    /// Transfer learning models
37    pub transfer_models: Vec<TransferLearningModel>,
38    /// Few-shot learning cache
39    pub few_shot_cache: HashMap<String, FewShotLearningEntry>,
40    /// Algorithm confidence levels
41    pub algorithm_confidence: HashMap<String, f64>,
42    /// Neural network for pattern classification
43    pub neural_network: NeuralModel,
44    /// Pattern to strategy mapping
45    pub pattern_strategy_mapping: HashMap<String, String>,
46    /// Algorithm usage count tracking
47    pub algorithm_usage_count: HashMap<String, usize>,
48    /// Strategy performance tracking
49    pub strategy_performance: HashMap<String, f64>,
50    /// Pattern processing history
51    pub patternhistory: VecDeque<ImagePattern>,
52    /// Learned feature representations
53    pub learnedfeatures: HashMap<String, Array1<f64>>,
54}
55
56impl AIProcessingState {
57    /// Create a new AI processing state
58    pub fn new() -> Self {
59        Self {
60            decision_network: Array3::zeros((10, 10, 5)), // Default small network
61            experience_buffer: VecDeque::new(),
62            processing_strategies: HashMap::new(),
63            performancehistory: VecDeque::new(),
64            knowledge_base: MultiModalKnowledgeBase::new(),
65            currentcontext: ProcessingContext::default(),
66            continual_learningstate: ContinualLearningState {
67                task_knowledge: Vec::new(),
68                forgetting_prevention: super::learning::ForgettingPreventionState {
69                    ewc_params: Array1::zeros(100),
70                    fisher_information: Array2::zeros((100, 100)),
71                    importance_mask: Array1::from_elem(100, false),
72                    memory_strength: 1.0,
73                },
74                meta_learning_params: Array1::zeros(50),
75                adaptationhistory: Vec::new(),
76            },
77            explanation_tracker: ExplanationTracker {
78                decision_explanations: VecDeque::new(),
79                feature_importance: HashMap::new(),
80                justifications: HashMap::new(),
81                confidence_scores: HashMap::new(),
82            },
83            transfer_models: Vec::new(),
84            few_shot_cache: HashMap::new(),
85            algorithm_confidence: HashMap::new(),
86            neural_network: NeuralModel {
87                weights: Array2::zeros((100, 50)),
88                biases: Array1::zeros(50),
89                architecture: "feedforward".to_string(),
90            },
91            pattern_strategy_mapping: HashMap::new(),
92            algorithm_usage_count: HashMap::new(),
93            strategy_performance: HashMap::new(),
94            patternhistory: VecDeque::new(),
95            learnedfeatures: HashMap::new(),
96        }
97    }
98
99    /// Add experience to the replay buffer
100    pub fn add_experience(&mut self, experience: ProcessingExperience) {
101        self.experience_buffer.push_back(experience);
102
103        // Limit buffer size to prevent excessive memory usage
104        if self.experience_buffer.len() > 10000 {
105            self.experience_buffer.pop_front();
106        }
107    }
108
109    /// Get a batch of experiences for learning
110    pub fn get_experience_batch(&self, batch_size: usize) -> Vec<ProcessingExperience> {
111        if self.experience_buffer.is_empty() {
112            return Vec::new();
113        }
114
115        let buffer_size = self.experience_buffer.len();
116        let actual_batch_size = batch_size.min(buffer_size);
117        let mut batch = Vec::new();
118
119        // Simple random sampling (in production, use proper randomization)
120        let step = buffer_size / actual_batch_size;
121        for i in 0..actual_batch_size {
122            let index = (i * step) % buffer_size;
123            if let Some(experience) = self.experience_buffer.get(index) {
124                batch.push(experience.clone());
125            }
126        }
127
128        batch
129    }
130
131    /// Update strategy for a given pattern
132    pub fn update_strategy(&mut self, pattern: ImagePattern, strategy: ProcessingStrategy) {
133        self.processing_strategies.insert(pattern, strategy);
134    }
135
136    /// Get best strategy for a given pattern
137    pub fn get_best_strategy(&self, pattern: &ImagePattern) -> Option<&ProcessingStrategy> {
138        self.processing_strategies.get(pattern)
139    }
140
141    /// Add performance record
142    pub fn add_performance_record(&mut self, performance: f64) {
143        self.performancehistory.push_back(performance);
144
145        // Limit history size
146        if self.performancehistory.len() > 1000 {
147            self.performancehistory.pop_front();
148        }
149    }
150
151    /// Get average performance over recent history
152    pub fn get_average_performance(&self, recent_count: usize) -> f64 {
153        if self.performancehistory.is_empty() {
154            return 0.0;
155        }
156
157        let count = recent_count.min(self.performancehistory.len());
158        let start_index = self.performancehistory.len() - count;
159
160        let sum: f64 = self.performancehistory.iter().skip(start_index).sum();
161
162        sum / count as f64
163    }
164
165    /// Update algorithm confidence
166    pub fn update_algorithm_confidence(&mut self, algorithm: &str, confidence: f64) {
167        self.algorithm_confidence
168            .insert(algorithm.to_string(), confidence);
169    }
170
171    /// Get algorithm confidence
172    pub fn get_algorithm_confidence(&self, algorithm: &str) -> f64 {
173        self.algorithm_confidence
174            .get(algorithm)
175            .copied()
176            .unwrap_or(0.5)
177    }
178
179    /// Add pattern to history
180    pub fn add_pattern_to_history(&mut self, pattern: ImagePattern) {
181        self.patternhistory.push_back(pattern);
182
183        // Limit pattern history size
184        if self.patternhistory.len() > 500 {
185            self.patternhistory.pop_front();
186        }
187    }
188
189    /// Check if pattern has been seen recently
190    pub fn has_seen_pattern_recently(&self, pattern: &ImagePattern, within_last: usize) -> bool {
191        let check_count = within_last.min(self.patternhistory.len());
192        let start_index = self.patternhistory.len() - check_count;
193
194        self.patternhistory
195            .iter()
196            .skip(start_index)
197            .any(|p| p == pattern)
198    }
199
200    /// Get state summary for monitoring
201    pub fn get_state_summary(&self) -> StateSummary {
202        StateSummary {
203            experience_count: self.experience_buffer.len(),
204            strategy_count: self.processing_strategies.len(),
205            average_performance: self.get_average_performance(100),
206            patterns_learned: self.patternhistory.len(),
207            algorithms_used: self.algorithm_usage_count.len(),
208        }
209    }
210}
211
212/// Summary of AI processing state for monitoring
213#[derive(Debug, Clone)]
214pub struct StateSummary {
215    /// Number of experiences in buffer
216    pub experience_count: usize,
217    /// Number of learned strategies
218    pub strategy_count: usize,
219    /// Average performance over recent history
220    pub average_performance: f64,
221    /// Number of patterns processed
222    pub patterns_learned: usize,
223    /// Number of different algorithms used
224    pub algorithms_used: usize,
225}