-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
288 lines (232 loc) · 10.4 KB
/
main.py
File metadata and controls
288 lines (232 loc) · 10.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
"""
RCCA Main Application Entry Point
================================
Main application for running the Real Cortical Cognitive Architecture
with command-line interface and system monitoring.
"""
import sys
import os
import argparse
import signal
import time
from pathlib import Path
# Add src to path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src'))
try:
# Import core components directly to avoid relative import issues
from rcca.domain.entities import LIFNeuron, AmodalManifold, NeurochemicalState
from rcca.domain.aggregates import CognitiveAgent, GlobalLatentWorkspace, AutobiographicalMemory
from rcca.service_layer.services import CognitiveOrchestrator, InMemoryUnitOfWork, IITComputationService
print("[OK] RCCA core modules imported successfully")
except ImportError as e:
print(f"Error importing RCCA modules: {e}")
print("Please ensure the RCCA package is properly installed.")
sys.exit(1)
class RCCAApplication:
"""
Main RCCA application with CLI and monitoring
"""
def __init__(self, config_path: str = None):
self.config_path = config_path
self.uow = None
self.orchestrator = None
self.agents = {}
self.running = False
def initialize(self):
"""Initialize RCCA system"""
print("Initializing Real Cortical Cognitive Architecture...")
print("-" * 50)
try:
# Create Unit of Work
self.uow = InMemoryUnitOfWork()
# Create IIT computation service
iit_service = IITComputationService()
# Create cognitive orchestrator
self.orchestrator = CognitiveOrchestrator(
uow=self.uow,
iit_service=iit_service
)
print("[OK] Core services initialized")
print("[OK] Unit of Work created")
print("[OK] IIT computation service ready")
print("[OK] Cognitive orchestrator ready")
print("\nRCCA System Status:")
print(f" Configuration: {self.config_path or 'Default'}")
print(f" Unit of Work: Active")
print(f" IIT Service: Active")
print(f" Orchestrator: Active")
self.running = True
return True
except Exception as e:
print(f"Failed to initialize RCCA system: {e}")
import traceback
traceback.print_exc()
return False
def run_cli(self):
"""Run interactive CLI"""
if not self.running:
print("RCCA system not initialized. Please run initialize() first.")
return
print("\nSimple RCCA Interactive Interface...")
print("Commands: demo, status, exit")
try:
while self.running:
command = input("\nRCCA> ").strip().lower()
if command == "demo":
self.run_demo_cycle()
elif command == "status":
print("\nRCCA System Status:")
print(f" Running: {self.running}")
print(f" Agents: {len(self.agents)}")
if self.orchestrator:
print(" Orchestrator: Active")
else:
print(" Orchestrator: None")
elif command == "exit":
print("Goodbye!")
break
elif command == "help":
print("Available commands:")
print(" demo - Run demonstration cognitive cycle")
print(" status - Show system status")
print(" exit - Exit RCCA")
else:
print(f"Unknown command: {command}. Type 'help' for commands.")
except KeyboardInterrupt:
print("\nCLI session interrupted by user")
except Exception as e:
print(f"Error in CLI session: {e}")
def run_demo_cycle(self):
"""Run demonstration thinking cycle"""
if not self.running:
print("RCCA system not initialized.")
return
print("\nRunning RCCA Demonstration Cognitive Cycle...")
print("-" * 40)
try:
# Create demo perceptual input
import torch
demo_input = {
'visual': torch.randn(64) * 1.5, # Visual cortex input
'auditory': torch.randn(64) * 1.2, # Auditory cortex input
'language': torch.randn(64) * 2.0, # Language areas input
'tactile': torch.randn(64) * 0.8 # Somatosensory input
}
print("Demo perceptual input created:")
for modality, data in demo_input.items():
print(f" {modality}: {data.shape} (norm: {torch.norm(data):.2f})")
# Create a demo agent
agent_id = "demo_agent"
agent = CognitiveAgent(agent_id)
print(f"\nCreated cognitive agent: {agent_id}")
print(f" Agent global workspace dim: {agent.global_workspace.workspace_dim}")
print(f" Agent state: {type(agent.get_agent_state())}")
# Process through orchestrator
print("\nProcessing through cognitive orchestrator...")
start_time = time.time()
# Create mock SLM context
slm_context = torch.randn(1536) # Match workspace dimension
print(f"SLM context: {slm_context.shape} (norm: {torch.norm(slm_context):.2f})")
cycle_results = self.orchestrator.process_cognitive_cycle(
agent_id=agent_id,
perceptual_data=demo_input,
slm_context=slm_context
)
orchestrator_time = (time.time() - start_time) * 1000
print(f"Orchestrator processing: {orchestrator_time:.2f}ms")
print("Results:")
for key, value in cycle_results.items():
if isinstance(value, torch.Tensor):
print(f" {key}: {value.shape} (norm: {torch.norm(value):.3f})")
elif isinstance(value, (int, float)):
print(f" {key}: {value:.4f}")
else:
print(f" {key}: {type(value).__name__}")
# Test domain entities directly
print("\nTesting core domain entities...")
# Test LIF Neuron
neuron = LIFNeuron(neuron_id="demo_neuron")
# Test integration (this needs different approach for the LIFNeuron)
spike_output = neuron.integrate_inputs()
print(f"LIF Neuron: demo integration -> spike output {spike_output:.3f}")
# Test Amodal Manifold
manifold = AmodalManifold(manifold_dim=1536, n_modalities=4)
bound_representation = manifold.bind_modalities(demo_input)
print(f"Amodal Manifold: bound representation {bound_representation.shape} (norm: {torch.norm(bound_representation):.3f})")
# Test Neurochemical State
neurochemical = NeurochemicalState(
dopamine=0.5, serotonin=0.7, norepinephrine=0.6, acetylcholine=0.8
)
homeostasis = neurochemical.homeostasis_score()
print(f"Neurochemical State: homeostasis score {homeostasis:.3f}")
print("\n[OK] Demo cognitive cycle completed successfully")
except Exception as e:
print(f"Error in demo cycle: {e}")
import traceback
traceback.print_exc()
def shutdown(self):
"""Shutdown RCCA system"""
print("\nShutting down RCCA system...")
self.running = False
print("[OK] RCCA system shutdown complete")
def signal_handler(signum, frame, app: RCCAApplication):
"""Handle shutdown signals"""
print(f"\nReceived signal {signum}, shutting down...")
app.shutdown()
sys.exit(0)
def main():
"""Main entry point"""
parser = argparse.ArgumentParser(description='Real Cortical Cognitive Architecture')
parser.add_argument('--config', type=str, default='hp_elitebook',
choices=['hp_elitebook', 'development', 'default'],
help='Configuration profile to use')
parser.add_argument('--mode', type=str, default='cli',
choices=['cli', 'demo', 'batch'],
help='Run mode (cli=interactive, demo=demonstration, batch=batch processing)')
parser.add_argument('--config-path', type=str,
help='Custom configuration file path')
parser.add_argument('--verbose', '-v', action='store_true',
help='Enable verbose logging')
args = parser.parse_args()
# Set up logging
if args.verbose:
print("Verbose mode enabled")
# Create application
config_path = args.config_path or f"configs/{args.config}.yaml"
app = RCCAApplication(config_path=config_path)
# Set up signal handlers
signal.signal(signal.SIGINT, lambda s, f: signal_handler(s, f, app))
signal.signal(signal.SIGTERM, lambda s, f: signal_handler(s, f, app))
print("Real Cortical Cognitive Architecture")
print("=" * 50)
print(f"Configuration: {args.config}")
print(f"Mode: {args.mode}")
print(f"Config path: {config_path}")
# Initialize system
if not app.initialize():
print("Failed to initialize RCCA system")
sys.exit(1)
# Run based on mode
try:
if args.mode == 'cli':
app.run_cli()
elif args.mode == 'demo':
app.run_demo_cycle()
# Keep alive for monitoring
print("\nDemo completed. Press Ctrl+C to exit.")
while app.running:
time.sleep(1)
elif args.mode == 'batch':
print("Batch processing mode not yet implemented")
sys.exit(1)
except KeyboardInterrupt:
print("\nInterrupted by user")
except Exception as e:
print(f"Application error: {e}")
import traceback
traceback.print_exc()
sys.exit(1)
finally:
app.shutdown()
if __name__ == "__main__":
main()