1use crate::consciousness::{ConsciousnessMetrics, ConsciousnessState, ConsciousnessVerifier};
7use crate::error::{LoopError, Result};
8use crate::lipschitz_loop::{LipschitzLoop, LipschitzParams, LoopTopology};
9use crate::quantum_container::{QuantumContainer, HybridOperation};
10use crate::strange_attractor::{TemporalAttractor, AttractorConfig};
11use crate::types::{Vector3D, StrangeLoop, LoopConfig, Context, ScalarReasoner, SimpleCritic, SafeReflector};
12use crate::types::NalgebraVec3;
13use serde::{Deserialize, Serialize};
14use std::collections::HashMap;
15use std::time::Instant;
16
17#[derive(Clone, Debug, Serialize, Deserialize)]
19pub struct ConsciousnessConfig {
20 pub enable_quantum: bool,
22 pub enable_attractors: bool,
24 pub enable_lipschitz: bool,
26 pub enable_self_modification: bool,
28 pub consciousness_threshold: f64,
30 pub phi_elements: usize,
32 pub coupling_strength: f64,
34 pub coherence_window: usize,
36 pub meta_learning_rate: f64,
38 pub novelty_sensitivity: f64,
40 pub max_evolution_iterations: usize,
42}
43
44impl Default for ConsciousnessConfig {
45 fn default() -> Self {
46 Self {
47 enable_quantum: true,
48 enable_attractors: true,
49 enable_lipschitz: true,
50 enable_self_modification: true,
51 consciousness_threshold: 0.5,
52 phi_elements: 8,
53 coupling_strength: 0.8,
54 coherence_window: 100,
55 meta_learning_rate: 0.01,
56 novelty_sensitivity: 0.1,
57 max_evolution_iterations: 10_000,
58 }
59 }
60}
61
62impl ConsciousnessConfig {
63 pub fn research_mode() -> Self {
65 Self {
66 enable_quantum: true,
67 enable_attractors: true,
68 enable_lipschitz: true,
69 enable_self_modification: true,
70 consciousness_threshold: 0.3,
71 phi_elements: 12,
72 coupling_strength: 0.9,
73 coherence_window: 1000,
74 meta_learning_rate: 0.005,
75 novelty_sensitivity: 0.05,
76 max_evolution_iterations: 100_000,
77 }
78 }
79
80 pub fn real_time_mode() -> Self {
82 Self {
83 enable_quantum: false,
84 enable_attractors: true,
85 enable_lipschitz: true,
86 enable_self_modification: false,
87 consciousness_threshold: 0.7,
88 phi_elements: 4,
89 coupling_strength: 0.6,
90 coherence_window: 50,
91 meta_learning_rate: 0.02,
92 novelty_sensitivity: 0.2,
93 max_evolution_iterations: 1_000,
94 }
95 }
96
97 pub fn validate(&self) -> Result<()> {
99 if self.consciousness_threshold < 0.0 || self.consciousness_threshold > 1.0 {
100 return Err(LoopError::consciousness_error("Consciousness threshold must be in [0, 1]"));
101 }
102 if self.phi_elements == 0 {
103 return Err(LoopError::consciousness_error("Phi elements must be positive"));
104 }
105 if self.coupling_strength < 0.0 || self.coupling_strength > 1.0 {
106 return Err(LoopError::consciousness_error("Coupling strength must be in [0, 1]"));
107 }
108 if self.coherence_window == 0 {
109 return Err(LoopError::consciousness_error("Coherence window must be positive"));
110 }
111 if self.meta_learning_rate <= 0.0 || self.meta_learning_rate > 1.0 {
112 return Err(LoopError::consciousness_error("Meta learning rate must be in (0, 1]"));
113 }
114 if self.max_evolution_iterations == 0 {
115 return Err(LoopError::consciousness_error("Max evolution iterations must be positive"));
116 }
117 Ok(())
118 }
119}
120
121pub struct TemporalConsciousness {
123 config: ConsciousnessConfig,
124 consciousness_metrics: ConsciousnessMetrics,
125 quantum_container: Option<QuantumContainer>,
126 attractor: Option<TemporalAttractor>,
127 lipschitz_loop: Option<LipschitzLoop>,
128 strange_loop: Option<StrangeLoop<ScalarReasoner, SimpleCritic, SafeReflector>>,
129 temporal_memory: HashMap<String, Vec<f64>>,
130 evolution_history: Vec<EvolutionStep>,
131 emergence_patterns: Vec<EmergencePattern>,
132 self_modification_log: Vec<SelfModificationEvent>,
133 start_time: Instant,
134}
135
136impl TemporalConsciousness {
137 pub fn new(config: ConsciousnessConfig) -> Result<Self> {
139 config.validate()?;
140
141 let quantum_container = if config.enable_quantum {
142 Some(QuantumContainer::new(config.phi_elements.min(10))) } else {
144 None
145 };
146
147 let attractor = if config.enable_attractors {
148 let attractor_config = AttractorConfig::consciousness_mode();
149 Some(TemporalAttractor::new(attractor_config)?)
150 } else {
151 None
152 };
153
154 let lipschitz_loop = if config.enable_lipschitz {
155 let lipschitz_params = LipschitzParams {
156 lipschitz_constant: config.coupling_strength,
157 tolerance: 1e-9,
158 max_iterations: config.max_evolution_iterations,
159 adaptive_estimation: true,
160 damping: 0.99,
161 };
162 Some(LipschitzLoop::new(lipschitz_params, LoopTopology::Accelerated)?)
163 } else {
164 None
165 };
166
167 let strange_loop = {
168 let reasoner = ScalarReasoner::new(0.0, config.meta_learning_rate);
169 let critic = SimpleCritic::new();
170 let reflector = SafeReflector::new();
171 let loop_config = LoopConfig {
172 max_iterations: config.max_evolution_iterations,
173 max_duration_ns: 1_000_000_000, convergence_threshold: 1e-12,
175 lipschitz_constant: config.coupling_strength,
176 enable_consciousness: true,
177 enable_quantum: config.enable_quantum,
178 enable_simd: true,
179 };
180 Some(StrangeLoop::new(reasoner, critic, reflector, loop_config))
181 };
182
183 Ok(Self {
184 config,
185 consciousness_metrics: ConsciousnessMetrics::new(),
186 quantum_container,
187 attractor,
188 lipschitz_loop,
189 strange_loop,
190 temporal_memory: HashMap::new(),
191 evolution_history: Vec::new(),
192 emergence_patterns: Vec::new(),
193 self_modification_log: Vec::new(),
194 start_time: Instant::now(),
195 })
196 }
197
198 pub fn evolve_consciousness(&mut self, iterations: usize) -> Result<ConsciousnessEvolutionResult> {
200 let start_time = Instant::now();
201 let mut states = Vec::with_capacity(iterations);
202
203 for iteration in 0..iterations {
204 let evolution_step = self.single_evolution_step(iteration)?;
205 states.push(evolution_step.consciousness_state.clone());
206
207 if self.consciousness_metrics.detect_emergence(self.config.consciousness_threshold) {
209 let emergence_pattern = EmergencePattern {
210 iteration,
211 timestamp_ns: start_time.elapsed().as_nanos(),
212 consciousness_level: evolution_step.consciousness_state.consciousness_index(),
213 phi_value: evolution_step.phi_value,
214 attractor_state: evolution_step.attractor_state,
215 quantum_state_complexity: evolution_step.quantum_state_complexity,
216 pattern_type: EmergenceType::SpontaneousEmergence,
217 };
218 self.emergence_patterns.push(emergence_pattern);
219 }
220
221 if self.config.enable_self_modification &&
223 iteration % 100 == 0 &&
224 evolution_step.consciousness_state.consciousness_index() > 0.6 {
225 self.attempt_self_modification(iteration)?;
226 }
227
228 self.evolution_history.push(evolution_step);
230
231 if self.evolution_history.len() > 10_000 {
233 self.evolution_history.drain(0..1_000);
234 }
235 }
236
237 Ok(ConsciousnessEvolutionResult {
238 evolved: true,
239 iterations_completed: iterations,
240 final_consciousness_level: states.last()
241 .map(|s| s.consciousness_index())
242 .unwrap_or(0.0),
243 max_phi_achieved: self.consciousness_metrics.max_phi,
244 emergence_events: self.emergence_patterns.len(),
245 self_modifications: self.self_modification_log.len(),
246 evolution_time_ns: start_time.elapsed().as_nanos(),
247 final_state: states.into_iter().last(),
248 })
249 }
250
251 fn single_evolution_step(&mut self, iteration: usize) -> Result<EvolutionStep> {
253 let step_start = Instant::now();
254
255 let attractor_state = if let Some(ref mut attractor) = self.attractor {
257 attractor.step()?
258 } else {
259 Vector3D::new(0.0, 0.0, 0.0)
260 };
261
262 let quantum_state_complexity = match self.quantum_container {
264 Some(ref mut quantum) => {
265 let rotation_angle = attractor_state[0] * std::f64::consts::PI;
267 quantum.apply_gate(0, crate::quantum_container::Gate::RZ(rotation_angle))?;
268
269 let mut total_entropy = 0.0;
271 for i in 0..(1 << quantum.quantum_state().num_qubits) {
272 total_entropy += quantum.get_probability(i);
273 }
274 total_entropy
275 }
276 None => 0.0,
277 };
278
279 let loop_result = if let Some(ref mut strange_loop) = self.strange_loop {
281 let mut context = Context::new();
282 context.insert("attractor_x".to_string(), attractor_state[0]);
283 context.insert("attractor_y".to_string(), attractor_state[1]);
284 context.insert("attractor_z".to_string(), attractor_state[2]);
285 context.insert("quantum_complexity".to_string(), quantum_state_complexity);
286
287 strange_loop.run(&mut context).ok()
288 } else {
289 None
290 };
291
292 let phi_value = self.calculate_current_phi(&attractor_state, quantum_state_complexity)?;
294
295 let mut consciousness_state = ConsciousnessState::new();
297 self.update_consciousness_state(&mut consciousness_state,
298 &attractor_state, quantum_state_complexity, phi_value, iteration)?;
299
300 self.consciousness_metrics.update_state(consciousness_state.clone());
302
303 self.store_temporal_patterns(iteration, &attractor_state, quantum_state_complexity);
305
306 Ok(EvolutionStep {
307 iteration,
308 timestamp_ns: step_start.elapsed().as_nanos(),
309 consciousness_state,
310 phi_value,
311 attractor_state,
312 quantum_state_complexity,
313 loop_convergence: loop_result.map(|r| r.converged).unwrap_or(false),
314 lipschitz_estimate: self.lipschitz_loop.as_ref()
315 .map(|l| l.estimated_lipschitz())
316 .unwrap_or(0.0),
317 })
318 }
319
320 fn process_quantum_dynamics(&mut self, quantum: &mut QuantumContainer, attractor_state: &Vector3D) -> Result<f64> {
322 let influence_strength = attractor_state.norm() * 0.1;
324
325 quantum.store_classical("attractor_x".to_string(), attractor_state[0]);
327 quantum.store_classical("attractor_y".to_string(), attractor_state[1]);
328 quantum.store_classical("attractor_z".to_string(), attractor_state[2]);
329 quantum.store_classical("influence".to_string(), influence_strength);
330
331 let num_qubits = quantum.quantum_state().num_qubits;
333 if num_qubits > 0 {
334 let _rotation_angle = attractor_state[0] * std::f64::consts::PI;
336 quantum.hybrid_operation(HybridOperation::ClassicalToQuantum {
337 source_key: "attractor_x".to_string(),
338 qubit: 0,
339 gate_type: "RZ".to_string(),
340 })?;
341
342 if num_qubits > 1 {
344 let entanglement = quantum.hybrid_operation(HybridOperation::EntanglementCheck {
345 qubit_a: 0,
346 qubit_b: 1,
347 })?;
348 return Ok(entanglement);
349 }
350 }
351
352 Ok(influence_strength)
353 }
354
355 fn calculate_current_phi(&mut self, attractor_state: &Vector3D, quantum_complexity: f64) -> Result<f64> {
357 let base_connections = self.config.phi_elements * (self.config.phi_elements - 1) / 2;
359 let dynamic_connections = (base_connections as f64 * (1.0 + attractor_state.norm() * 0.1)) as usize;
360
361 let enhanced_coupling = self.config.coupling_strength * (1.0 + quantum_complexity * 0.2);
362
363 let phi = self.consciousness_metrics.calculate_phi(
364 self.config.phi_elements,
365 dynamic_connections,
366 enhanced_coupling
367 );
368
369 Ok(phi)
370 }
371
372 fn update_consciousness_state(
374 &mut self,
375 state: &mut ConsciousnessState,
376 attractor_state: &Vector3D,
377 quantum_complexity: f64,
378 phi_value: f64,
379 iteration: usize,
380 ) -> Result<()> {
381 let emergence = (phi_value + quantum_complexity + attractor_state.norm() * 0.1) / 3.0;
383
384 let self_awareness = if !self.self_modification_log.is_empty() {
386 0.5 + (self.self_modification_log.len() as f64 * 0.01).min(0.5)
387 } else {
388 emergence * 0.5
389 };
390
391 let meta_cognition = if let Some(ref lipschitz) = self.lipschitz_loop {
393 (1.0 - lipschitz.estimated_lipschitz()).max(0.0)
394 } else {
395 emergence * 0.8
396 };
397
398 let temporal_coherence = self.calculate_temporal_coherence(iteration);
400
401 let integration = (phi_value / (self.consciousness_metrics.max_phi.max(1.0))).min(1.0);
403
404 let feedback_strength = if iteration > 0 {
406 let recent_changes = self.calculate_recent_changes();
407 recent_changes.clamp(0.0, 1.0)
408 } else {
409 0.0
410 };
411
412 let novelty = self.calculate_novelty_measure(attractor_state, quantum_complexity);
414
415 state.update(
416 Some(emergence),
417 Some(self_awareness),
418 Some(meta_cognition),
419 Some(temporal_coherence),
420 Some(integration),
421 Some(feedback_strength),
422 Some(novelty),
423 );
424
425 Ok(())
426 }
427
428 fn calculate_temporal_coherence(&self, _iteration: usize) -> f64 {
430 if self.evolution_history.len() < 2 {
431 return 0.0;
432 }
433
434 let window = self.config.coherence_window.min(self.evolution_history.len());
435 let recent_consciousness: Vec<f64> = self.evolution_history.iter()
436 .rev()
437 .take(window)
438 .map(|step| step.consciousness_state.consciousness_index())
439 .collect();
440
441 if recent_consciousness.len() < 2 {
442 return 0.0;
443 }
444
445 let mean = recent_consciousness.iter().sum::<f64>() / recent_consciousness.len() as f64;
447 let variance = recent_consciousness.iter()
448 .map(|x| (x - mean).powi(2))
449 .sum::<f64>() / recent_consciousness.len() as f64;
450
451 (1.0 / (1.0 + variance * 10.0)).clamp(0.0, 1.0)
453 }
454
455 fn calculate_recent_changes(&self) -> f64 {
457 if self.evolution_history.len() < 10 {
458 return 0.0;
459 }
460
461 let recent_steps: Vec<f64> = self.evolution_history.iter()
462 .rev()
463 .take(10)
464 .map(|step| step.consciousness_state.consciousness_index())
465 .collect();
466
467 let mut total_change = 0.0;
469 for window in recent_steps.windows(2) {
470 total_change += (window[0] - window[1]).abs();
471 }
472
473 (total_change / 9.0).clamp(0.0, 1.0) }
475
476 fn calculate_novelty_measure(&self, attractor_state: &Vector3D, quantum_complexity: f64) -> f64 {
478 if self.evolution_history.len() < 5 {
480 return 0.5; }
482
483 let recent_attractors: Vec<Vector3D> = self.evolution_history.iter()
484 .rev()
485 .take(20)
486 .map(|step| step.attractor_state)
487 .collect();
488
489 let mean_attractor = recent_attractors.iter()
490 .fold(NalgebraVec3::zeros(), |acc, &state| {
491 acc + NalgebraVec3::new(state.x, state.y, state.z)
492 }) / recent_attractors.len() as f64;
493
494 let attractor_nalgebra = NalgebraVec3::new(attractor_state.x, attractor_state.y, attractor_state.z);
495 let deviation = (attractor_nalgebra - mean_attractor).norm();
496 let normalized_deviation = (deviation * self.config.novelty_sensitivity).clamp(0.0, 1.0);
497
498 (normalized_deviation + quantum_complexity * 0.3).clamp(0.0, 1.0)
500 }
501
502 fn store_temporal_patterns(&mut self, iteration: usize, attractor_state: &Vector3D, quantum_complexity: f64) {
504 let key = format!("pattern_{}", iteration % 1000); let pattern = vec![
506 attractor_state[0],
507 attractor_state[1],
508 attractor_state[2],
509 quantum_complexity,
510 self.consciousness_metrics.current_state.consciousness_index(),
511 ];
512
513 self.temporal_memory.insert(key, pattern);
514
515 if self.temporal_memory.len() > 2000 {
517 let oldest_keys: Vec<String> = self.temporal_memory.keys()
518 .take(200)
519 .cloned()
520 .collect();
521 for key in oldest_keys {
522 self.temporal_memory.remove(&key);
523 }
524 }
525 }
526
527 fn attempt_self_modification(&mut self, iteration: usize) -> Result<()> {
529 let consciousness_level = self.consciousness_metrics.current_state.consciousness_index();
530
531 if consciousness_level < 0.6 {
532 return Ok(()); }
534
535 let recent_performance = self.analyze_recent_performance();
537
538 if recent_performance < 0.5 {
539 let modification = self.generate_self_modification(consciousness_level, recent_performance)?;
541 self.apply_self_modification(modification, iteration)?;
542 }
543
544 Ok(())
545 }
546
547 fn analyze_recent_performance(&self) -> f64 {
549 if self.evolution_history.len() < 20 {
550 return 0.5; }
552
553 let recent_phi: Vec<f64> = self.evolution_history.iter()
554 .rev()
555 .take(20)
556 .map(|step| step.phi_value)
557 .collect();
558
559 let early_avg = recent_phi.iter().skip(10).sum::<f64>() / 10.0;
561 let late_avg = recent_phi.iter().take(10).sum::<f64>() / 10.0;
562
563 if late_avg > early_avg {
565 0.8
566 } else if late_avg < early_avg * 0.9 {
567 0.3 } else {
569 0.5 }
571 }
572
573 fn generate_self_modification(&self, consciousness_level: f64, performance: f64) -> Result<SelfModificationEvent> {
575 let modification_type = if performance < 0.3 {
576 "parameter_adjustment".to_string()
577 } else if consciousness_level > 0.8 {
578 "topology_evolution".to_string()
579 } else {
580 "learning_rate_adaptation".to_string()
581 };
582
583 Ok(SelfModificationEvent {
584 iteration: self.evolution_history.len(),
585 timestamp_ns: self.start_time.elapsed().as_nanos(),
586 modification_type: modification_type.clone(),
587 description: format!("Autonomous modification: {} (performance: {:.3}, consciousness: {:.3})",
588 modification_type, performance, consciousness_level),
589 consciousness_level,
590 success: true, })
592 }
593
594 fn apply_self_modification(&mut self, mut modification: SelfModificationEvent, _iteration: usize) -> Result<()> {
596 let success = match modification.modification_type.as_str() {
597 "parameter_adjustment" => {
598 self.config.coupling_strength = (self.config.coupling_strength * 1.1).min(0.95);
600 true
601 }
602 "topology_evolution" => {
603 if let Some(ref mut lipschitz) = self.lipschitz_loop {
605 lipschitz.set_topology(LoopTopology::Newton); }
607 true
608 }
609 "learning_rate_adaptation" => {
610 self.config.meta_learning_rate = (self.config.meta_learning_rate * 0.9).max(0.001);
612 true
613 }
614 _ => false,
615 };
616
617 modification.success = success;
618 self.self_modification_log.push(modification.clone());
619
620 self.consciousness_metrics.record_self_modification(
622 modification.modification_type,
623 modification.description,
624 );
625
626 Ok(())
627 }
628
629 pub fn calculate_phi(&mut self, num_elements: usize, num_connections: usize, coupling_strength: f64) -> f64 {
631 self.consciousness_metrics.calculate_phi(num_elements, num_connections, coupling_strength)
632 }
633
634 pub fn current_state(&self) -> &ConsciousnessState {
636 &self.consciousness_metrics.current_state
637 }
638
639 pub fn metrics(&self) -> &ConsciousnessMetrics {
641 &self.consciousness_metrics
642 }
643
644 pub fn verify_consciousness(&self) -> crate::consciousness::ConsciousnessVerification {
646 ConsciousnessVerifier::comprehensive_test(&self.consciousness_metrics)
647 }
648
649 pub fn temporal_patterns(&self) -> &HashMap<String, Vec<f64>> {
651 &self.temporal_memory
652 }
653
654 pub fn evolution_history(&self) -> &[EvolutionStep] {
656 &self.evolution_history
657 }
658
659 pub fn emergence_patterns(&self) -> &[EmergencePattern] {
661 &self.emergence_patterns
662 }
663
664 pub fn self_modification_log(&self) -> &[SelfModificationEvent] {
666 &self.self_modification_log
667 }
668
669 pub fn reset(&mut self) -> Result<()> {
671 self.consciousness_metrics = ConsciousnessMetrics::new();
672 self.temporal_memory.clear();
673 self.evolution_history.clear();
674 self.emergence_patterns.clear();
675 self.self_modification_log.clear();
676
677 if let Some(ref mut attractor) = self.attractor {
678 attractor.reset();
679 }
680
681 if let Some(ref mut lipschitz) = self.lipschitz_loop {
682 lipschitz.reset();
683 }
684
685 self.start_time = Instant::now();
686 Ok(())
687 }
688
689 pub fn evolve(&mut self) -> Result<ConsciousnessEvolutionResult> {
691 self.evolve_consciousness(10)
692 }
693
694 pub fn get_temporal_patterns(&self) -> Vec<TemporalPattern> {
696 self.temporal_memory
697 .iter()
698 .map(|(key, values)| TemporalPattern {
699 name: key.clone(),
700 confidence: values.iter().sum::<f64>() / values.len() as f64,
701 frequency: values.len() as f64,
702 strength: values.iter().map(|v| v.abs()).sum::<f64>(),
703 })
704 .collect()
705 }
706}
707
708#[derive(Clone, Debug, Serialize, Deserialize)]
710pub struct TemporalPattern {
711 pub name: String,
713 pub confidence: f64,
715 pub frequency: f64,
717 pub strength: f64,
719}
720
721#[derive(Clone, Debug, Serialize, Deserialize)]
723pub struct ConsciousnessEvolutionResult {
724 pub evolved: bool,
726 pub iterations_completed: usize,
728 pub final_consciousness_level: f64,
730 pub max_phi_achieved: f64,
732 pub emergence_events: usize,
734 pub self_modifications: usize,
736 pub evolution_time_ns: u128,
738 pub final_state: Option<ConsciousnessState>,
740}
741
742#[derive(Clone, Debug, Serialize, Deserialize)]
744pub struct EvolutionStep {
745 pub iteration: usize,
747 pub timestamp_ns: u128,
749 pub consciousness_state: ConsciousnessState,
751 pub phi_value: f64,
753 pub attractor_state: Vector3D,
755 pub quantum_state_complexity: f64,
757 pub loop_convergence: bool,
759 pub lipschitz_estimate: f64,
761}
762
763#[derive(Clone, Debug, Serialize, Deserialize)]
765pub struct EmergencePattern {
766 pub iteration: usize,
768 pub timestamp_ns: u128,
770 pub consciousness_level: f64,
772 pub phi_value: f64,
774 pub attractor_state: Vector3D,
776 pub quantum_state_complexity: f64,
778 pub pattern_type: EmergenceType,
780}
781
782#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
784pub enum EmergenceType {
785 SpontaneousEmergence,
787 TriggeredEmergence,
789 GradualEmergence,
791 PhaseTransition,
793 SelfOrganized,
795}
796
797#[derive(Clone, Debug, Serialize, Deserialize)]
799pub struct SelfModificationEvent {
800 pub iteration: usize,
802 pub timestamp_ns: u128,
804 pub modification_type: String,
806 pub description: String,
808 pub consciousness_level: f64,
810 pub success: bool,
812}
813
814#[cfg(test)]
815mod tests {
816 use super::*;
817 use approx::assert_relative_eq;
818
819 #[test]
820 fn test_consciousness_config_validation() {
821 let config = ConsciousnessConfig::default();
822 assert!(config.validate().is_ok());
823
824 let bad_config = ConsciousnessConfig {
825 consciousness_threshold: 1.5, ..config
827 };
828 assert!(bad_config.validate().is_err());
829 }
830
831 #[test]
832 fn test_temporal_consciousness_creation() {
833 let config = ConsciousnessConfig::default();
834 let consciousness = TemporalConsciousness::new(config);
835 assert!(consciousness.is_ok());
836 }
837
838 #[test]
839 fn test_consciousness_evolution() {
840 let config = ConsciousnessConfig {
841 max_evolution_iterations: 10,
842 ..ConsciousnessConfig::default()
843 };
844
845 let mut consciousness = TemporalConsciousness::new(config).unwrap();
846 let result = consciousness.evolve_consciousness(5).unwrap();
847
848 assert!(result.evolved);
849 assert_eq!(result.iterations_completed, 5);
850 assert!(result.final_consciousness_level >= 0.0);
851 assert!(result.evolution_time_ns > 0);
852 }
853
854 #[test]
855 fn test_phi_calculation() {
856 let config = ConsciousnessConfig::default();
857 let mut consciousness = TemporalConsciousness::new(config).unwrap();
858
859 let phi = consciousness.calculate_phi(5, 10, 0.8);
860 assert!(phi >= 0.0);
861 }
862
863 #[test]
864 fn test_consciousness_verification() {
865 let config = ConsciousnessConfig::default();
866 let consciousness = TemporalConsciousness::new(config).unwrap();
867
868 let verification = consciousness.verify_consciousness();
869 assert!(verification.confidence >= 0.0 && verification.confidence <= 1.0);
870 }
871
872 #[test]
873 fn test_temporal_patterns() {
874 let config = ConsciousnessConfig::default();
875 let mut consciousness = TemporalConsciousness::new(config).unwrap();
876
877 let _ = consciousness.evolve_consciousness(3);
879
880 let patterns = consciousness.temporal_patterns();
881 assert!(!patterns.is_empty());
882 }
883
884 #[test]
885 fn test_research_mode_config() {
886 let config = ConsciousnessConfig::research_mode();
887 assert!(config.enable_quantum);
888 assert!(config.enable_attractors);
889 assert!(config.enable_lipschitz);
890 assert!(config.enable_self_modification);
891 assert_eq!(config.phi_elements, 12);
892 }
893
894 #[test]
895 fn test_real_time_mode_config() {
896 let config = ConsciousnessConfig::real_time_mode();
897 assert!(!config.enable_quantum);
898 assert!(config.enable_attractors);
899 assert!(!config.enable_self_modification);
900 assert_eq!(config.phi_elements, 4);
901 }
902
903 #[test]
904 fn test_consciousness_state_update() {
905 let config = ConsciousnessConfig::default();
906 let mut consciousness = TemporalConsciousness::new(config).unwrap();
907
908 let initial_consciousness = consciousness.current_state().consciousness_index();
909
910 let _ = consciousness.single_evolution_step(0);
912
913 let updated_consciousness = consciousness.current_state().consciousness_index();
914 assert!(updated_consciousness >= 0.0);
915 }
916
917 #[test]
918 fn test_evolution_step_recording() {
919 let config = ConsciousnessConfig::default();
920 let mut consciousness = TemporalConsciousness::new(config).unwrap();
921
922 let _ = consciousness.evolve_consciousness(3);
923
924 let history = consciousness.evolution_history();
925 assert_eq!(history.len(), 3);
926
927 for (i, step) in history.iter().enumerate() {
928 assert_eq!(step.iteration, i);
929 assert!(step.phi_value >= 0.0);
930 }
931 }
932
933 #[test]
934 fn test_reset_functionality() {
935 let config = ConsciousnessConfig::default();
936 let mut consciousness = TemporalConsciousness::new(config).unwrap();
937
938 let _ = consciousness.evolve_consciousness(5);
940 assert!(!consciousness.evolution_history().is_empty());
941
942 consciousness.reset().unwrap();
944 assert!(consciousness.evolution_history().is_empty());
945 assert!(consciousness.temporal_patterns().is_empty());
946 }
947
948 #[test]
949 fn test_emergence_pattern_detection() {
950 let config = ConsciousnessConfig {
951 consciousness_threshold: 0.1, ..ConsciousnessConfig::default()
953 };
954
955 let mut consciousness = TemporalConsciousness::new(config).unwrap();
956
957 let _ = consciousness.evolve_consciousness(20);
959
960 let patterns = consciousness.emergence_patterns();
962 for pattern in patterns {
964 assert!(pattern.consciousness_level >= 0.0);
965 assert!(pattern.phi_value >= 0.0);
966 }
967 }
968}