Skip to main content

microscope_memory/
advanced_cognition.rs

1//! Advanced Cognition — Predictive Processing, Intuition, Unconscious Problem-Solving
2
3use std::collections::HashMap;
4
5// ═══ PREDICTIVE PROCESSING ═══════════════════════════════════════════
6#[derive(Clone, Debug)]
7pub struct Prediction {
8    pub pattern: Vec<u32>,
9    pub confidence: f32,
10    pub error: f32, // prediction error
11    pub timestamp_ms: u64,
12}
13
14pub struct PredictiveProcessor {
15    pub predictions: Vec<Prediction>,
16    pub error_history: Vec<f32>,
17    pub model_accuracy: f32, // 0.0-1.0
18}
19
20impl Default for PredictiveProcessor {
21    fn default() -> Self {
22        Self::new()
23    }
24}
25
26impl PredictiveProcessor {
27    pub fn new() -> Self {
28        Self {
29            predictions: Vec::new(),
30            error_history: Vec::new(),
31            model_accuracy: 0.5,
32        }
33    }
34
35    /// Generate prediction from pattern
36    pub fn predict(&mut self, pattern: &[u32]) -> (Vec<u32>, f32) {
37        let confidence = self.model_accuracy;
38        let mut predicted = pattern.to_vec();
39
40        // Extend pattern with predicted next elements
41        if !pattern.is_empty() {
42            let last = pattern[pattern.len() - 1];
43            predicted.push(last.wrapping_add(1));
44            predicted.push(last.wrapping_add(2));
45        }
46
47        self.predictions.push(Prediction {
48            pattern: predicted.clone(),
49            confidence,
50            error: 0.0,
51            timestamp_ms: Self::now_ms(),
52        });
53
54        (predicted, confidence)
55    }
56
57    /// Update prediction error
58    pub fn update_error(&mut self, actual: &[u32]) {
59        if let Some(pred) = self.predictions.last_mut() {
60            let error = Self::calculate_error(&pred.pattern, actual);
61            pred.error = error;
62            self.error_history.push(error);
63
64            // Update model accuracy
65            if self.error_history.len() > 20 {
66                self.error_history.remove(0);
67            }
68            let avg_error: f32 =
69                self.error_history.iter().sum::<f32>() / self.error_history.len() as f32;
70            self.model_accuracy = (1.0 - avg_error).max(0.1);
71        }
72    }
73
74    fn calculate_error(predicted: &[u32], actual: &[u32]) -> f32 {
75        let len = predicted.len().min(actual.len());
76        if len == 0 {
77            return 1.0;
78        }
79
80        let mut diff = 0u32;
81        for i in 0..len {
82            diff = diff.wrapping_add(predicted[i] ^ actual[i]);
83        }
84        ((diff as f32) / (len as f32 * 256.0)).min(1.0)
85    }
86
87    fn now_ms() -> u64 {
88        std::time::SystemTime::now()
89            .duration_since(std::time::UNIX_EPOCH)
90            .unwrap_or_default()
91            .as_millis() as u64
92    }
93}
94
95// ═══ INTUITION ════════════════════════════════════════════════════════
96#[derive(Clone, Debug)]
97pub struct IntuitionPattern {
98    pub pattern_hash: u64,
99    pub confidence: f32,
100    pub decision: String,
101    pub success_rate: f32,
102    pub frequency: u32,
103}
104
105pub struct IntuitionSystem {
106    pub patterns: HashMap<u64, IntuitionPattern>,
107    pub fast_decisions: Vec<(String, f32)>, // (decision, speed_ms)
108}
109
110impl Default for IntuitionSystem {
111    fn default() -> Self {
112        Self::new()
113    }
114}
115
116impl IntuitionSystem {
117    pub fn new() -> Self {
118        Self {
119            patterns: HashMap::new(),
120            fast_decisions: Vec::new(),
121        }
122    }
123
124    /// Learn pattern for future intuitive decisions
125    pub fn learn_pattern(&mut self, pattern: &[u32], decision: &str, successful: bool) {
126        let hash = Self::pattern_hash(pattern);
127
128        let pattern_entry = self
129            .patterns
130            .entry(hash)
131            .or_insert_with(|| IntuitionPattern {
132                pattern_hash: hash,
133                confidence: 0.5,
134                decision: decision.to_string(),
135                success_rate: 0.0,
136                frequency: 0,
137            });
138
139        pattern_entry.frequency += 1;
140        if successful {
141            pattern_entry.success_rate = (pattern_entry.success_rate * 0.8 + 1.0 * 0.2).min(1.0);
142            pattern_entry.confidence = (pattern_entry.confidence + 0.1).min(1.0);
143        } else {
144            pattern_entry.success_rate = (pattern_entry.success_rate * 0.9).max(0.0);
145            pattern_entry.confidence = (pattern_entry.confidence - 0.05).max(0.0);
146        }
147    }
148
149    /// Make intuitive decision (fast, pattern-based)
150    pub fn intuitive_decision(&mut self, pattern: &[u32]) -> Option<(String, f32)> {
151        let hash = Self::pattern_hash(pattern);
152
153        if let Some(entry) = self.patterns.get(&hash) {
154            if entry.confidence > 0.6 {
155                // High confidence threshold
156                self.fast_decisions.push((entry.decision.clone(), 5.0)); // 5ms decision time
157                return Some((entry.decision.clone(), entry.confidence));
158            }
159        }
160        None
161    }
162
163    fn pattern_hash(pattern: &[u32]) -> u64 {
164        let mut hash: u64 = 0xcbf29ce484222325;
165        for &val in pattern.iter().take(10) {
166            hash = hash.wrapping_mul(0x100000001b3) ^ (val as u64);
167        }
168        hash
169    }
170}
171
172// ═══ UNCONSCIOUS PROBLEM-SOLVING ════════════════════════════════════
173#[derive(Clone, Debug)]
174pub struct IncubatedProblem {
175    pub problem_id: u64,
176    pub problem_desc: String,
177    pub incubation_start_ms: u64,
178    pub background_processing_count: u32,
179    pub solution_found: bool,
180    pub solution: Option<String>,
181    pub insight_strength: f32,
182}
183
184pub struct UnconsciousSolver {
185    pub incubating: Vec<IncubatedProblem>,
186    pub solutions: HashMap<u64, String>,
187    pub incubation_time_ms: u64, // how long to let problems simmer
188}
189
190impl Default for UnconsciousSolver {
191    fn default() -> Self {
192        Self::new()
193    }
194}
195
196impl UnconsciousSolver {
197    pub fn new() -> Self {
198        Self {
199            incubating: Vec::new(),
200            solutions: HashMap::new(),
201            incubation_time_ms: 5000, // 5 seconds default
202        }
203    }
204
205    /// Start incubating a problem (send to background)
206    pub fn incubate(&mut self, problem_desc: &str) -> u64 {
207        let problem_id = Self::problem_hash(problem_desc);
208
209        self.incubating.push(IncubatedProblem {
210            problem_id,
211            problem_desc: problem_desc.to_string(),
212            incubation_start_ms: Self::now_ms(),
213            background_processing_count: 0,
214            solution_found: false,
215            solution: None,
216            insight_strength: 0.0,
217        });
218
219        problem_id
220    }
221
222    /// Background processing (happens passively)
223    pub fn background_process(&mut self) {
224        let now = Self::now_ms();
225
226        for problem in &mut self.incubating {
227            if !problem.solution_found {
228                problem.background_processing_count += 1;
229
230                let incubation_time = now.saturating_sub(problem.incubation_start_ms);
231
232                // Solution emerges after incubation period
233                if incubation_time > self.incubation_time_ms
234                    && problem.background_processing_count > 3
235                {
236                    // Generate insight (simple heuristic)
237                    problem.solution = Some(format!(
238                        "Insight: Approach {} differently",
239                        problem.background_processing_count
240                    ));
241                    problem.solution_found = true;
242                    problem.insight_strength =
243                        0.5 + (problem.background_processing_count as f32 * 0.05).min(0.4);
244                }
245            }
246        }
247    }
248
249    /// Retrieve solution from background processing
250    pub fn retrieve_solution(&mut self, problem_id: u64) -> Option<(String, f32)> {
251        if let Some(pos) = self
252            .incubating
253            .iter()
254            .position(|p| p.problem_id == problem_id)
255        {
256            let problem = self.incubating.remove(pos);
257
258            if problem.solution_found {
259                if let Some(solution) = problem.solution {
260                    self.solutions.insert(problem_id, solution.clone());
261                    return Some((solution, problem.insight_strength));
262                }
263            }
264        }
265        None
266    }
267
268    /// Check if solution is ready
269    pub fn is_ready(&self, problem_id: u64) -> bool {
270        self.incubating
271            .iter()
272            .find(|p| p.problem_id == problem_id)
273            .map(|p| p.solution_found)
274            .unwrap_or(false)
275    }
276
277    fn problem_hash(desc: &str) -> u64 {
278        let mut hash: u64 = 0xcbf29ce484222325;
279        for &b in desc.as_bytes().iter().take(32) {
280            hash = hash.wrapping_mul(0x100000001b3) ^ (b as u64);
281        }
282        hash
283    }
284
285    fn now_ms() -> u64 {
286        std::time::SystemTime::now()
287            .duration_since(std::time::UNIX_EPOCH)
288            .unwrap_or_default()
289            .as_millis() as u64
290    }
291}
292
293// ═══ INTEGRATED SYSTEM ═════════════════════════════════════════════════
294pub struct AdvancedCognition {
295    pub predictor: PredictiveProcessor,
296    pub intuition: IntuitionSystem,
297    pub solver: UnconsciousSolver,
298}
299
300impl Default for AdvancedCognition {
301    fn default() -> Self {
302        Self::new()
303    }
304}
305
306impl AdvancedCognition {
307    pub fn new() -> Self {
308        Self {
309            predictor: PredictiveProcessor::new(),
310            intuition: IntuitionSystem::new(),
311            solver: UnconsciousSolver::new(),
312        }
313    }
314
315    /// Process in integrated way
316    pub fn process_cycle(&mut self) {
317        self.solver.background_process();
318
319        // Let intuition contribute to predictions
320        self.predictor.model_accuracy = (self.predictor.model_accuracy * 0.9
321            + self.intuition.patterns.len() as f32 * 0.001)
322            .min(1.0);
323    }
324}