Skip to main content

scirs2_ndimage/hyperdimensional_computing/
types.rs

1//! Core Types and Configuration for Hyperdimensional Computing
2//!
3//! This module defines the fundamental data structures and configuration
4//! for hyperdimensional computing operations, including hypervectors and
5//! various result types used throughout the HDC system.
6
7use std::collections::HashMap;
8
9/// Configuration for hyperdimensional computing
10#[derive(Debug, Clone)]
11pub struct HDCConfig {
12    /// Dimensionality of hypervectors (typically 10,000+)
13    pub hypervector_dim: usize,
14    /// Sparsity level (fraction of dimensions that are non-zero)
15    pub sparsity: f64,
16    /// Similarity threshold for recognition
17    pub similarity_threshold: f64,
18    /// Number of training iterations
19    pub training_iterations: usize,
20    /// Learning rate for adaptation
21    pub learning_rate: f64,
22    /// Bundling capacity (number of vectors to bundle)
23    pub bundling_capacity: usize,
24    /// Binding strength for compositional operations
25    pub binding_strength: f64,
26    /// Cleanup threshold for memory operations
27    pub cleanup_threshold: f64,
28}
29
30impl Default for HDCConfig {
31    fn default() -> Self {
32        Self {
33            hypervector_dim: 10000,
34            sparsity: 0.01, // 1% sparsity
35            similarity_threshold: 0.8,
36            training_iterations: 10,
37            learning_rate: 0.1,
38            bundling_capacity: 100,
39            binding_strength: 1.0,
40            cleanup_threshold: 0.7,
41        }
42    }
43}
44
45/// Hyperdimensional vector representation
46#[derive(Debug, Clone)]
47pub struct Hypervector {
48    /// Sparse representation: (index, value) pairs
49    pub sparse_data: Vec<(usize, f64)>,
50    /// Dimensionality
51    pub dimension: usize,
52    /// Norm for normalization
53    pub norm: f64,
54}
55
56/// Pattern match result
57#[derive(Debug, Clone)]
58pub struct PatternMatch {
59    /// Matched pattern label
60    pub label: String,
61    /// Confidence score [0, 1]
62    pub confidence: f64,
63    /// Position in the image (y, x)
64    pub position: (usize, usize),
65    /// Size of the matched region (height, width)
66    pub size: (usize, usize),
67}
68
69/// Feature detection result
70#[derive(Debug, Clone)]
71pub struct FeatureDetection {
72    /// Type of detected feature
73    pub feature_type: String,
74    /// Position of the feature (y, x)
75    pub position: (usize, usize),
76    /// Strength/confidence of the detection
77    pub strength: f64,
78    /// Encoded hypervector representation
79    pub hypervector: Hypervector,
80    /// Size of the feature patch (height, width)
81    pub patch_size: (usize, usize),
82}
83
84/// Sequence encoding result
85#[derive(Debug, Clone)]
86pub struct SequenceEncoding {
87    /// Encoded sequence as hypervector
88    pub encoding: Hypervector,
89    /// Temporal position mappings
90    pub temporal_positions: Vec<usize>,
91    /// Sequence confidence score
92    pub confidence: f64,
93}
94
95/// Experience for continual learning
96#[derive(Debug, Clone)]
97pub struct Experience {
98    /// Encoded representation
99    pub encoding: Hypervector,
100    /// Associated label
101    pub label: String,
102    /// Timestamp of experience
103    pub timestamp: usize,
104    /// Importance score
105    pub importance: f64,
106}
107
108/// Consolidation result for memory operations
109#[derive(Debug, Clone)]
110pub struct ConsolidationResult {
111    /// Number of interference cases prevented
112    pub interference_prevented: usize,
113    /// Effectiveness score of consolidation
114    pub effectiveness_score: f64,
115    /// Number of replay cycles used
116    pub replay_cycles_used: usize,
117}
118
119/// Prediction result
120#[derive(Debug, Clone)]
121pub struct PredictionResult {
122    /// Predicted label
123    pub predicted_label: String,
124    /// Confidence in prediction
125    pub confidence: f64,
126    /// Alternative predictions with scores
127    pub alternatives: Vec<(String, f64)>,
128}
129
130/// Update result for online learning
131#[derive(Debug, Clone)]
132pub struct UpdateResult {
133    /// Whether memory was updated
134    pub memory_updated: bool,
135    /// Learning rate used for update
136    pub learning_rate_used: f64,
137    /// Change in performance metrics
138    pub performance_change: f64,
139}
140
141/// Performance metrics
142#[derive(Debug, Clone)]
143pub struct PerformanceMetrics {
144    /// Overall accuracy
145    pub accuracy: f64,
146    /// Learning speed
147    pub learning_speed: f64,
148    /// Memory efficiency
149    pub memory_efficiency: f64,
150    /// Adaptation effectiveness
151    pub adaptation_effectiveness: f64,
152}
153
154/// Result of online learning step
155#[derive(Debug, Clone)]
156pub struct OnlineLearningResult {
157    /// Prediction made
158    pub prediction: PredictionResult,
159    /// Learning update information
160    pub learning_update: UpdateResult,
161    /// Current system performance
162    pub system_performance: PerformanceMetrics,
163    /// Current adaptation rate
164    pub adaptation_rate: f64,
165}
166
167/// Result of compositional reasoning
168#[derive(Debug, Clone)]
169pub struct CompositionResult {
170    /// Similarity between query and image
171    pub query_similarity: f64,
172    /// Presence strength of individual concepts
173    pub concept_presence: HashMap<String, f64>,
174    /// Composed query representation
175    pub composed_representation: Hypervector,
176    /// Image representation
177    pub image_representation: Hypervector,
178}
179
180/// Abstraction level for hierarchical reasoning
181#[derive(Debug, Clone)]
182pub struct AbstractionLevel {
183    /// Level identifier
184    pub level: usize,
185    /// Concepts at this level
186    pub concepts: HashMap<String, Hypervector>,
187    /// Resolution/granularity
188    pub resolution: f64,
189    /// Complexity score
190    pub complexity: f64,
191}
192
193/// Reasoning chain for logical inference
194#[derive(Debug, Clone)]
195pub struct ReasoningChain {
196    /// Chain identifier
197    pub chain_id: String,
198    /// Sequence of concepts
199    pub concepts: Vec<String>,
200    /// Overall confidence
201    pub confidence: f64,
202    /// Supporting evidence strength
203    pub support_evidence: f64,
204}
205
206/// Meta-cognitive assessment
207#[derive(Debug, Clone)]
208pub struct MetaCognitiveAssessment {
209    /// Confidence in reasoning
210    pub confidence_score: f64,
211    /// Depth of reasoning
212    pub reasoning_depth: usize,
213    /// Uncertainty estimate
214    pub uncertainty_estimate: f64,
215}
216
217/// Multi-modal fusion configuration
218#[derive(Debug, Clone)]
219pub struct MultiModalFusionConfig {
220    /// Weight for visual modality
221    pub visual_weight: f64,
222    /// Weight for temporal modality
223    pub temporal_weight: f64,
224    /// Weight for semantic modality
225    pub semantic_weight: f64,
226    /// Attention mechanism strength
227    pub attention_strength: f64,
228    /// Fusion method to use
229    pub fusion_method: FusionMethod,
230}
231
232impl Default for MultiModalFusionConfig {
233    fn default() -> Self {
234        Self {
235            visual_weight: 0.4,
236            temporal_weight: 0.3,
237            semantic_weight: 0.3,
238            attention_strength: 0.8,
239            fusion_method: FusionMethod::WeightedBundle,
240        }
241    }
242}
243
244/// Fusion method enumeration
245#[derive(Debug, Clone)]
246pub enum FusionMethod {
247    /// Simple weighted bundling
248    WeightedBundle,
249    /// Attention-based fusion
250    AttentionFusion,
251    /// Hierarchical fusion
252    HierarchicalFusion,
253}
254
255/// Adaptation parameters for online learning
256#[derive(Debug, Clone)]
257pub struct AdaptationParameters {
258    /// Base learning rate
259    pub base_rate: f64,
260    /// Current learning rate
261    pub current_rate: f64,
262    /// Minimum learning rate
263    pub min_rate: f64,
264    /// Maximum learning rate
265    pub max_rate: f64,
266    /// Adaptation speed
267    pub adaptation_speed: f64,
268    /// Performance threshold for adaptation
269    pub performance_threshold: f64,
270}
271
272impl Default for AdaptationParameters {
273    fn default() -> Self {
274        Self {
275            base_rate: 0.1,
276            current_rate: 0.1,
277            min_rate: 0.001,
278            max_rate: 0.5,
279            adaptation_speed: 0.05,
280            performance_threshold: 0.8,
281        }
282    }
283}
284
285impl AdaptationParameters {
286    /// Adjust learning rate based on performance
287    pub fn adjust_based_on_performance(
288        &mut self,
289        tracker: &crate::hyperdimensional_computing::memory::PerformanceTracker,
290    ) {
291        let recent_change = tracker.get_recent_performance_change();
292
293        if recent_change > 0.05 {
294            // Performance improving - increase rate
295            self.current_rate =
296                (self.current_rate * (1.0 + self.adaptation_speed)).min(self.max_rate);
297        } else if recent_change < -0.05 {
298            // Performance degrading - decrease rate
299            self.current_rate =
300                (self.current_rate * (1.0 - self.adaptation_speed)).max(self.min_rate);
301        }
302        // Otherwise maintain current rate
303    }
304
305    /// Reset to base rate
306    pub fn reset(&mut self) {
307        self.current_rate = self.base_rate;
308    }
309}
310
311#[cfg(test)]
312mod tests {
313    use super::*;
314
315    #[test]
316    fn test_hdc_config_default() {
317        let config = HDCConfig::default();
318        assert_eq!(config.hypervector_dim, 10000);
319        assert_eq!(config.sparsity, 0.01);
320        assert_eq!(config.similarity_threshold, 0.8);
321        assert_eq!(config.training_iterations, 10);
322        assert_eq!(config.learning_rate, 0.1);
323        assert_eq!(config.bundling_capacity, 100);
324        assert_eq!(config.binding_strength, 1.0);
325        assert_eq!(config.cleanup_threshold, 0.7);
326    }
327
328    #[test]
329    fn test_hypervector_creation() {
330        let hv = Hypervector {
331            sparse_data: vec![(0, 1.0), (100, -1.0), (200, 1.0)],
332            dimension: 1000,
333            norm: 1.732, // sqrt(3)
334        };
335
336        assert_eq!(hv.dimension, 1000);
337        assert_eq!(hv.sparse_data.len(), 3);
338        assert!((hv.norm - 1.732).abs() < 0.01);
339    }
340
341    #[test]
342    fn test_pattern_match() {
343        let pattern_match = PatternMatch {
344            label: "test_pattern".to_string(),
345            confidence: 0.95,
346            position: (10, 20),
347            size: (32, 32),
348        };
349
350        assert_eq!(pattern_match.label, "test_pattern");
351        assert_eq!(pattern_match.confidence, 0.95);
352        assert_eq!(pattern_match.position, (10, 20));
353        assert_eq!(pattern_match.size, (32, 32));
354    }
355
356    #[test]
357    fn test_multimodal_fusion_config_default() {
358        let config = MultiModalFusionConfig::default();
359
360        // Weights should sum approximately to 1.0
361        let sum = config.visual_weight + config.temporal_weight + config.semantic_weight;
362        assert!((sum - 1.0).abs() < 0.1);
363
364        assert!(config.attention_strength > 0.0);
365        assert!(config.attention_strength <= 1.0);
366
367        matches!(config.fusion_method, FusionMethod::WeightedBundle);
368    }
369
370    #[test]
371    fn test_adaptation_parameters() {
372        let mut params = AdaptationParameters::default();
373        let original_rate = params.current_rate;
374
375        // Test reset functionality
376        params.current_rate = 0.3;
377        params.reset();
378        assert_eq!(params.current_rate, params.base_rate);
379
380        // Test bounds
381        assert!(params.min_rate < params.max_rate);
382        assert!(params.current_rate >= params.min_rate);
383        assert!(params.current_rate <= params.max_rate);
384    }
385
386    #[test]
387    fn test_prediction_result() {
388        let prediction = PredictionResult {
389            predicted_label: "cat".to_string(),
390            confidence: 0.9,
391            alternatives: vec![("dog".to_string(), 0.1), ("bird".to_string(), 0.05)],
392        };
393
394        assert_eq!(prediction.predicted_label, "cat");
395        assert_eq!(prediction.confidence, 0.9);
396        assert_eq!(prediction.alternatives.len(), 2);
397        assert_eq!(prediction.alternatives[0].0, "dog");
398        assert_eq!(prediction.alternatives[0].1, 0.1);
399    }
400
401    #[test]
402    fn test_reasoning_chain() {
403        let chain = ReasoningChain {
404            chain_id: "chain_1".to_string(),
405            concepts: vec!["A".to_string(), "B".to_string(), "C".to_string()],
406            confidence: 0.8,
407            support_evidence: 0.75,
408        };
409
410        assert_eq!(chain.chain_id, "chain_1");
411        assert_eq!(chain.concepts.len(), 3);
412        assert_eq!(chain.concepts[0], "A");
413        assert_eq!(chain.confidence, 0.8);
414        assert_eq!(chain.support_evidence, 0.75);
415    }
416}