#![cfg_attr(not(feature = "std"), no_std)]
#![deny(missing_docs)]
#![warn(clippy::all)]
#![allow(clippy::module_inception)]
extern crate alloc;
pub mod scheduler;
pub mod neural;
pub mod temporal;
pub mod plasticity;
pub mod benchmark;
pub use scheduler::{
NanosecondScheduler, SchedulerConfig, SchedulableTask, TaskResult, TimePoint
};
pub use neural::{
TemporalNetwork, NetworkAdapter, InferenceTask, PlasticityTask
};
pub use temporal::{
TemporalWindow, WindowManager, TemporalConfig, OverlapStrategy
};
pub use plasticity::{
STDPConfig, PhaseConfig, PlasticityEngine
};
#[cfg(feature = "std")]
use std::{
collections::HashMap,
sync::{Arc, Mutex},
time::{Duration, Instant},
};
#[cfg(not(feature = "std"))]
use alloc::{
collections::BTreeMap as HashMap,
sync::Arc,
vec::Vec,
};
#[cfg(all(target_arch = "wasm32", feature = "wasm"))]
use wasm_bindgen::prelude::*;
use thiserror::Error;
#[derive(Error, Debug)]
pub enum NanoConsciousnessError {
#[error("Scheduler error: {0}")]
Scheduler(#[from] scheduler::SchedulerError),
#[error("Neural network error: {0}")]
Neural(String),
#[error("Temporal error: {0}")]
Temporal(#[from] temporal::TemporalError),
#[error("Plasticity error: {0}")]
Plasticity(#[from] plasticity::PlasticityError),
#[error("Configuration error: {0}")]
Config(String),
#[error("System state error: {0}")]
SystemState(String),
}
pub type Result<T> = std::result::Result<T, NanoConsciousnessError>;
#[derive(Debug, Clone)]
pub struct NanoConsciousnessConfig {
pub scheduler: SchedulerConfig,
pub temporal: TemporalConfig,
pub stdp: Option<STDPConfig>,
pub phase: Option<PhaseConfig>,
pub enable_emergence: bool,
pub log_level: log::LevelFilter,
}
impl Default for NanoConsciousnessConfig {
fn default() -> Self {
Self {
scheduler: SchedulerConfig::default(),
temporal: TemporalConfig::default(),
stdp: Some(STDPConfig::default()),
phase: Some(PhaseConfig::default()),
enable_emergence: true,
log_level: log::LevelFilter::Info,
}
}
}
pub struct NanoConsciousnessSystem {
scheduler: NanosecondScheduler,
window_manager: WindowManager,
plasticity_engine: Option<PlasticityEngine>,
config: NanoConsciousnessConfig,
networks: HashMap<String, Arc<Mutex<NetworkAdapter>>>,
metrics: ConsciousnessMetrics,
is_running: bool,
}
#[derive(Debug, Default, Clone)]
pub struct ConsciousnessMetrics {
pub phi: f64,
pub emergence: f64,
pub coherence: f64,
pub efficiency: f64,
pub tasks_executed: u64,
pub avg_execution_time_ns: f64,
pub timing_jitter_ns: f64,
}
impl NanoConsciousnessSystem {
pub fn new(config: NanoConsciousnessConfig) -> Result<Self> {
#[cfg(feature = "std")]
{
env_logger::Builder::from_default_env()
.filter_level(config.log_level)
.init();
}
#[cfg(all(target_arch = "wasm32", feature = "wasm"))]
{
console_log::init_with_level(config.log_level).map_err(|e| {
NanoConsciousnessError::Config(format!("Failed to initialize WASM logging: {}", e))
})?;
}
log::info!("Initializing nano-consciousness system");
let scheduler = NanosecondScheduler::new(config.scheduler.clone())?;
let window_manager = WindowManager::new(config.temporal.clone())?;
let plasticity_engine = if config.stdp.is_some() || config.phase.is_some() {
Some(PlasticityEngine::new(
config.stdp.clone(),
config.phase.clone()
)?)
} else {
None
};
Ok(Self {
scheduler,
window_manager,
plasticity_engine,
config,
networks: HashMap::new(),
metrics: ConsciousnessMetrics::default(),
is_running: false,
})
}
pub fn add_network(&mut self, name: String, network: NetworkAdapter) -> Result<()> {
log::info!("Adding network: {}", name);
self.networks.insert(name, Arc::new(Mutex::new(network)));
Ok(())
}
pub fn remove_network(&mut self, name: &str) -> Result<()> {
log::info!("Removing network: {}", name);
self.networks.remove(name);
Ok(())
}
#[cfg(feature = "async")]
pub async fn start_consciousness_loop(&mut self) -> Result<()> {
if self.is_running {
return Err(NanoConsciousnessError::SystemState(
"System is already running".to_string()
));
}
log::info!("Starting consciousness processing loop");
self.is_running = true;
while self.is_running {
self.process_temporal_window().await?;
self.update_consciousness_metrics()?;
#[cfg(target_arch = "wasm32")]
gloo_timers::future::sleep(Duration::from_nanos(1)).await;
#[cfg(not(target_arch = "wasm32"))]
tokio::task::yield_now().await;
}
log::info!("Consciousness processing loop stopped");
Ok(())
}
#[cfg(not(feature = "async"))]
pub fn start_consciousness_loop(&mut self) -> Result<()> {
if self.is_running {
return Err(NanoConsciousnessError::SystemState(
"System is already running".to_string()
));
}
log::info!("Starting consciousness processing loop (sync)");
self.is_running = true;
while self.is_running {
self.process_temporal_window_sync()?;
self.update_consciousness_metrics()?;
#[cfg(feature = "std")]
std::thread::sleep(Duration::from_nanos(100));
}
log::info!("Consciousness processing loop stopped");
Ok(())
}
pub fn stop(&mut self) {
log::info!("Stopping consciousness system");
self.is_running = false;
}
pub fn get_metrics(&self) -> &ConsciousnessMetrics {
&self.metrics
}
#[cfg(feature = "async")]
async fn process_temporal_window(&mut self) -> Result<()> {
let window = self.window_manager.get_current_window()?;
let tasks = self.scheduler.get_ready_tasks(window.start_time, window.end_time)?;
for task in tasks {
let start_time = self.get_current_time();
let result = task.execute();
let execution_time = self.get_current_time().duration_since(start_time);
self.metrics.tasks_executed += 1;
self.metrics.avg_execution_time_ns =
(self.metrics.avg_execution_time_ns * (self.metrics.tasks_executed - 1) as f64 +
execution_time.as_nanos() as f64) / self.metrics.tasks_executed as f64;
log::debug!("Task executed in {}ns", execution_time.as_nanos());
}
self.window_manager.advance_window()?;
Ok(())
}
#[cfg(not(feature = "async"))]
fn process_temporal_window_sync(&mut self) -> Result<()> {
let window = self.window_manager.get_current_window()?;
let tasks = self.scheduler.get_ready_tasks(window.start_time, window.end_time)?;
for task in tasks {
let start_time = self.get_current_time();
let result = task.execute();
let execution_time = self.get_current_time().duration_since(start_time);
self.metrics.tasks_executed += 1;
self.metrics.avg_execution_time_ns =
(self.metrics.avg_execution_time_ns * (self.metrics.tasks_executed - 1) as f64 +
execution_time.as_nanos() as f64) / self.metrics.tasks_executed as f64;
log::debug!("Task executed in {}ns", execution_time.as_nanos());
}
self.window_manager.advance_window()?;
Ok(())
}
fn update_consciousness_metrics(&mut self) -> Result<()> {
if !self.config.enable_emergence {
return Ok(());
}
self.metrics.phi = self.calculate_integrated_information();
self.metrics.emergence = self.calculate_emergence_level();
self.metrics.coherence = self.calculate_temporal_coherence();
self.metrics.efficiency = self.calculate_processing_efficiency();
Ok(())
}
fn calculate_integrated_information(&self) -> f64 {
let mut total_phi = 0.0;
for network in self.networks.values() {
total_phi += 0.1; }
total_phi.min(1.0)
}
fn calculate_emergence_level(&self) -> f64 {
let coherence_factor = self.metrics.coherence;
let efficiency_factor = self.metrics.efficiency;
let phi_factor = self.metrics.phi;
(coherence_factor * 0.4 + efficiency_factor * 0.3 + phi_factor * 0.3).min(1.0)
}
fn calculate_temporal_coherence(&self) -> f64 {
let jitter_factor = 1.0 - (self.metrics.timing_jitter_ns / 1000.0).min(1.0);
let window_quality = self.window_manager.get_coherence_metric();
(jitter_factor * 0.6 + window_quality * 0.4).max(0.0).min(1.0)
}
fn calculate_processing_efficiency(&self) -> f64 {
if self.metrics.tasks_executed == 0 {
return 0.0;
}
let target_execution_time = 1000.0; let efficiency = target_execution_time / self.metrics.avg_execution_time_ns.max(1.0);
efficiency.min(1.0)
}
fn get_current_time(&self) -> TimePoint {
#[cfg(target_arch = "wasm32")]
{
TimePoint::from_nanos((js_sys::Date::now() * 1_000_000.0) as u64)
}
#[cfg(not(target_arch = "wasm32"))]
{
use std::time::{SystemTime, UNIX_EPOCH};
let duration = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
TimePoint::from_nanos(
duration.as_secs() * 1_000_000_000 + duration.subsec_nanos() as u64
)
}
}
}
pub mod emergence {
use super::*;
pub fn detect_emergence(metrics: &ConsciousnessMetrics) -> EmergencePattern {
if metrics.emergence > 0.8 && metrics.coherence > 0.7 {
EmergencePattern::HighConsciousness
} else if metrics.emergence > 0.5 && metrics.coherence > 0.5 {
EmergencePattern::MediumConsciousness
} else if metrics.emergence > 0.2 {
EmergencePattern::BasicAwareness
} else {
EmergencePattern::NoEmergence
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum EmergencePattern {
NoEmergence,
BasicAwareness,
MediumConsciousness,
HighConsciousness,
}
}
#[cfg(all(target_arch = "wasm32", feature = "wasm"))]
pub mod wasm {
use super::*;
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub struct WasmNanoConsciousness {
system: NanoConsciousnessSystem,
}
#[wasm_bindgen]
impl WasmNanoConsciousness {
#[wasm_bindgen(constructor)]
pub fn new() -> Result<WasmNanoConsciousness, JsValue> {
let config = NanoConsciousnessConfig::default();
let system = NanoConsciousnessSystem::new(config)
.map_err(|e| JsValue::from_str(&e.to_string()))?;
Ok(WasmNanoConsciousness { system })
}
#[wasm_bindgen]
pub fn get_metrics_json(&self) -> String {
serde_json::to_string(&self.system.get_metrics()).unwrap_or_default()
}
#[wasm_bindgen]
pub fn stop(&mut self) {
self.system.stop();
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_system_creation() {
let config = NanoConsciousnessConfig::default();
let system = NanoConsciousnessSystem::new(config);
assert!(system.is_ok());
}
#[test]
fn test_emergence_detection() {
let metrics = ConsciousnessMetrics {
phi: 0.8,
emergence: 0.9,
coherence: 0.8,
efficiency: 0.7,
..Default::default()
};
let pattern = emergence::detect_emergence(&metrics);
assert_eq!(pattern, emergence::EmergencePattern::HighConsciousness);
}
}