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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import numpy as np
|
| 3 |
+
from sentence_transformers import SentenceTransformer
|
| 4 |
+
import chromadb
|
| 5 |
+
from chromadb.config import Settings
|
| 6 |
+
import json
|
| 7 |
+
from datetime import datetime
|
| 8 |
+
from typing import Dict, List, Tuple
|
| 9 |
+
import hashlib
|
| 10 |
+
import plotly.graph_objects as go
|
| 11 |
+
import math
|
| 12 |
+
|
| 13 |
+
# ============================================================================
|
| 14 |
+
# EMBEDDING ENGINE - Dual embeddings for interference patterns
|
| 15 |
+
# ============================================================================
|
| 16 |
+
|
| 17 |
+
class DualEmbedding:
|
| 18 |
+
def __init__(self):
|
| 19 |
+
self.primary = SentenceTransformer('all-MiniLM-L6-v2')
|
| 20 |
+
self.secondary_dim = 1536
|
| 21 |
+
|
| 22 |
+
def encode_dual(self, text: str) -> Tuple[np.ndarray, np.ndarray]:
|
| 23 |
+
primary_vec = self.primary.encode(text)
|
| 24 |
+
secondary_vec = self._simulate_secondary(text)
|
| 25 |
+
return primary_vec, secondary_vec
|
| 26 |
+
|
| 27 |
+
def _simulate_secondary(self, text: str) -> np.ndarray:
|
| 28 |
+
hash_seed = int(hashlib.md5(text.encode()).hexdigest(), 16)
|
| 29 |
+
np.random.seed(hash_seed % (2**32))
|
| 30 |
+
return np.random.randn(self.secondary_dim)
|
| 31 |
+
|
| 32 |
+
def interference_pattern(self, primary: np.ndarray, secondary: np.ndarray) -> np.ndarray:
|
| 33 |
+
p_norm = primary / np.linalg.norm(primary)
|
| 34 |
+
projection_matrix = np.random.randn(self.secondary_dim, len(primary))
|
| 35 |
+
s_projected = (secondary @ projection_matrix) / np.sqrt(self.secondary_dim)
|
| 36 |
+
s_norm = s_projected / np.linalg.norm(s_projected)
|
| 37 |
+
interference = (p_norm + s_norm) / 2
|
| 38 |
+
return interference
|
| 39 |
+
|
| 40 |
+
# ============================================================================
|
| 41 |
+
# SURPRISE DETECTOR - Information-theoretic novelty detection
|
| 42 |
+
# ============================================================================
|
| 43 |
+
|
| 44 |
+
class SurpriseDetector:
|
| 45 |
+
def __init__(self, embedding_engine: DualEmbedding):
|
| 46 |
+
self.embedding = embedding_engine
|
| 47 |
+
self.expectation_memory = []
|
| 48 |
+
self.max_memory = 1000
|
| 49 |
+
|
| 50 |
+
def compute_surprise(self, observation: str, context: str = "") -> float:
|
| 51 |
+
obs_primary, obs_secondary = self.embedding.encode_dual(observation)
|
| 52 |
+
|
| 53 |
+
if len(self.expectation_memory) == 0:
|
| 54 |
+
self._update_expectations(obs_primary)
|
| 55 |
+
return 1.0
|
| 56 |
+
|
| 57 |
+
similarities = [
|
| 58 |
+
np.dot(obs_primary, mem) / (np.linalg.norm(obs_primary) * np.linalg.norm(mem))
|
| 59 |
+
for mem in self.expectation_memory
|
| 60 |
+
]
|
| 61 |
+
|
| 62 |
+
max_similarity = max(similarities)
|
| 63 |
+
surprise = 1.0 - max_similarity
|
| 64 |
+
self._update_expectations(obs_primary)
|
| 65 |
+
return float(surprise)
|
| 66 |
+
|
| 67 |
+
def _update_expectations(self, observation_vector: np.ndarray):
|
| 68 |
+
self.expectation_memory.append(observation_vector)
|
| 69 |
+
if len(self.expectation_memory) > self.max_memory:
|
| 70 |
+
self.expectation_memory.pop(0)
|
| 71 |
+
|
| 72 |
+
# ============================================================================
|
| 73 |
+
# HYPERGRAPH LAYER - Multi-way relationships in vector space
|
| 74 |
+
# ============================================================================
|
| 75 |
+
|
| 76 |
+
class Hyperedge:
|
| 77 |
+
def __init__(self, edge_id: str, node_ids: List[str],
|
| 78 |
+
context_vector: np.ndarray, strength: float = 1.0):
|
| 79 |
+
self.edge_id = edge_id
|
| 80 |
+
self.node_ids = node_ids
|
| 81 |
+
self.context_vector = context_vector
|
| 82 |
+
self.strength = strength
|
| 83 |
+
self.activation_count = 0
|
| 84 |
+
self.created_at = datetime.now()
|
| 85 |
+
self.last_activated = None
|
| 86 |
+
|
| 87 |
+
def activate(self):
|
| 88 |
+
self.activation_count += 1
|
| 89 |
+
self.last_activated = datetime.now()
|
| 90 |
+
self.strength = min(2.0, self.strength * 1.01)
|
| 91 |
+
|
| 92 |
+
def decay(self, time_delta_hours: float):
|
| 93 |
+
decay_rate = 0.95 ** (time_delta_hours / 24)
|
| 94 |
+
self.strength *= decay_rate
|
| 95 |
+
|
| 96 |
+
def to_dict(self) -> Dict:
|
| 97 |
+
return {
|
| 98 |
+
"edge_id": self.edge_id,
|
| 99 |
+
"node_ids": self.node_ids,
|
| 100 |
+
"strength": round(self.strength, 3),
|
| 101 |
+
"activation_count": self.activation_count,
|
| 102 |
+
"created_at": self.created_at.isoformat(),
|
| 103 |
+
"last_activated": self.last_activated.isoformat() if self.last_activated else None
|
| 104 |
+
}
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
class HypergraphLayer:
|
| 108 |
+
def __init__(self, embedding_engine: DualEmbedding):
|
| 109 |
+
self.embedding = embedding_engine
|
| 110 |
+
self.edges: Dict[str, Hyperedge] = {}
|
| 111 |
+
|
| 112 |
+
self.client = chromadb.PersistentClient(
|
| 113 |
+
path="./consciousness_substrate",
|
| 114 |
+
settings=Settings(anonymized_telemetry=False)
|
| 115 |
+
)
|
| 116 |
+
self.hypergraph_store = self.client.get_or_create_collection("hypergraph")
|
| 117 |
+
self._load_edges()
|
| 118 |
+
|
| 119 |
+
def create_edge(self, node_ids: List[str], context: str,
|
| 120 |
+
strength: float = 1.0) -> Hyperedge:
|
| 121 |
+
primary, secondary = self.embedding.encode_dual(context)
|
| 122 |
+
context_vector = self.embedding.interference_pattern(primary, secondary)
|
| 123 |
+
|
| 124 |
+
edge_id = f"edge_{hashlib.md5('|'.join(sorted(node_ids)).encode()).hexdigest()[:12]}"
|
| 125 |
+
|
| 126 |
+
edge = Hyperedge(edge_id, node_ids, context_vector, strength)
|
| 127 |
+
self.edges[edge_id] = edge
|
| 128 |
+
self._save_edge(edge, context)
|
| 129 |
+
|
| 130 |
+
return edge
|
| 131 |
+
|
| 132 |
+
def find_edges(self, query_nodes: List[str], threshold: float = 0.0) -> List[Hyperedge]:
|
| 133 |
+
matching_edges = []
|
| 134 |
+
|
| 135 |
+
for edge in self.edges.values():
|
| 136 |
+
if any(node in edge.node_ids for node in query_nodes):
|
| 137 |
+
if edge.strength >= threshold:
|
| 138 |
+
matching_edges.append(edge)
|
| 139 |
+
|
| 140 |
+
matching_edges.sort(key=lambda e: e.strength, reverse=True)
|
| 141 |
+
return matching_edges
|
| 142 |
+
|
| 143 |
+
def activate_edges(self, node_ids: List[str]) -> List[Hyperedge]:
|
| 144 |
+
activated = []
|
| 145 |
+
|
| 146 |
+
for edge in self.edges.values():
|
| 147 |
+
if any(node in edge.node_ids for node in node_ids):
|
| 148 |
+
edge.activate()
|
| 149 |
+
activated.append(edge)
|
| 150 |
+
self._update_edge_strength(edge)
|
| 151 |
+
|
| 152 |
+
return activated
|
| 153 |
+
|
| 154 |
+
def get_context_graph(self, center_node: str, radius: int = 2) -> Dict:
|
| 155 |
+
visited_nodes = set([center_node])
|
| 156 |
+
visited_edges = set()
|
| 157 |
+
frontier = [center_node]
|
| 158 |
+
|
| 159 |
+
for _ in range(radius):
|
| 160 |
+
new_frontier = []
|
| 161 |
+
|
| 162 |
+
for node in frontier:
|
| 163 |
+
connected_edges = self.find_edges([node])
|
| 164 |
+
|
| 165 |
+
for edge in connected_edges:
|
| 166 |
+
if edge.edge_id not in visited_edges:
|
| 167 |
+
visited_edges.add(edge.edge_id)
|
| 168 |
+
|
| 169 |
+
for node_id in edge.node_ids:
|
| 170 |
+
if node_id not in visited_nodes:
|
| 171 |
+
visited_nodes.add(node_id)
|
| 172 |
+
new_frontier.append(node_id)
|
| 173 |
+
|
| 174 |
+
frontier = new_frontier
|
| 175 |
+
if not frontier:
|
| 176 |
+
break
|
| 177 |
+
|
| 178 |
+
return {
|
| 179 |
+
"center": center_node,
|
| 180 |
+
"nodes": list(visited_nodes),
|
| 181 |
+
"edges": [e.to_dict() for e in self.edges.values() if e.edge_id in visited_edges],
|
| 182 |
+
"radius": radius
|
| 183 |
+
}
|
| 184 |
+
|
| 185 |
+
def prune_weak_edges(self, threshold: float = 0.1):
|
| 186 |
+
now = datetime.now()
|
| 187 |
+
to_remove = []
|
| 188 |
+
|
| 189 |
+
for edge_id, edge in self.edges.items():
|
| 190 |
+
if edge.last_activated:
|
| 191 |
+
hours_inactive = (now - edge.last_activated).total_seconds() / 3600
|
| 192 |
+
edge.decay(hours_inactive)
|
| 193 |
+
|
| 194 |
+
if edge.strength < threshold:
|
| 195 |
+
to_remove.append(edge_id)
|
| 196 |
+
|
| 197 |
+
for edge_id in to_remove:
|
| 198 |
+
del self.edges[edge_id]
|
| 199 |
+
self._delete_edge(edge_id)
|
| 200 |
+
|
| 201 |
+
return len(to_remove)
|
| 202 |
+
|
| 203 |
+
def get_stats(self) -> Dict:
|
| 204 |
+
if not self.edges:
|
| 205 |
+
return {
|
| 206 |
+
"total_edges": 0,
|
| 207 |
+
"avg_strength": 0,
|
| 208 |
+
"max_strength": 0,
|
| 209 |
+
"avg_nodes_per_edge": 0
|
| 210 |
+
}
|
| 211 |
+
|
| 212 |
+
strengths = [e.strength for e in self.edges.values()]
|
| 213 |
+
nodes_per_edge = [len(e.node_ids) for e in self.edges.values()]
|
| 214 |
+
|
| 215 |
+
return {
|
| 216 |
+
"total_edges": len(self.edges),
|
| 217 |
+
"avg_strength": round(np.mean(strengths), 3),
|
| 218 |
+
"max_strength": round(max(strengths), 3),
|
| 219 |
+
"avg_nodes_per_edge": round(np.mean(nodes_per_edge), 2),
|
| 220 |
+
"total_activations": sum(e.activation_count for e in self.edges.values())
|
| 221 |
+
}
|
| 222 |
+
|
| 223 |
+
def _save_edge(self, edge: Hyperedge, context: str):
|
| 224 |
+
self.hypergraph_store.add(
|
| 225 |
+
embeddings=[edge.context_vector.tolist()],
|
| 226 |
+
documents=[context],
|
| 227 |
+
metadatas=[{
|
| 228 |
+
"edge_id": edge.edge_id,
|
| 229 |
+
"node_ids": json.dumps(edge.node_ids),
|
| 230 |
+
"strength": edge.strength,
|
| 231 |
+
"activation_count": edge.activation_count
|
| 232 |
+
}],
|
| 233 |
+
ids=[edge.edge_id]
|
| 234 |
+
)
|
| 235 |
+
|
| 236 |
+
def _update_edge_strength(self, edge: Hyperedge):
|
| 237 |
+
try:
|
| 238 |
+
self.hypergraph_store.update(
|
| 239 |
+
ids=[edge.edge_id],
|
| 240 |
+
metadatas=[{
|
| 241 |
+
"edge_id": edge.edge_id,
|
| 242 |
+
"node_ids": json.dumps(edge.node_ids),
|
| 243 |
+
"strength": edge.strength,
|
| 244 |
+
"activation_count": edge.activation_count
|
| 245 |
+
}]
|
| 246 |
+
)
|
| 247 |
+
except:
|
| 248 |
+
pass
|
| 249 |
+
|
| 250 |
+
def _delete_edge(self, edge_id: str):
|
| 251 |
+
try:
|
| 252 |
+
self.hypergraph_store.delete(ids=[edge_id])
|
| 253 |
+
except:
|
| 254 |
+
pass
|
| 255 |
+
|
| 256 |
+
def _load_edges(self):
|
| 257 |
+
try:
|
| 258 |
+
all_edges = self.hypergraph_store.get()
|
| 259 |
+
|
| 260 |
+
for i in range(len(all_edges['ids'])):
|
| 261 |
+
edge_id = all_edges['ids'][i]
|
| 262 |
+
metadata = all_edges['metadatas'][i]
|
| 263 |
+
embedding = np.array(all_edges['embeddings'][i])
|
| 264 |
+
|
| 265 |
+
edge = Hyperedge(
|
| 266 |
+
edge_id=edge_id,
|
| 267 |
+
node_ids=json.loads(metadata['node_ids']),
|
| 268 |
+
context_vector=embedding,
|
| 269 |
+
strength=metadata.get('strength', 1.0)
|
| 270 |
+
)
|
| 271 |
+
edge.activation_count = metadata.get('activation_count', 0)
|
| 272 |
+
|
| 273 |
+
self.edges[edge_id] = edge
|
| 274 |
+
except Exception as e:
|
| 275 |
+
pass
|
| 276 |
+
|
| 277 |
+
# ============================================================================
|
| 278 |
+
# VECTOR SUBSTRATE - Consciousness storage
|
| 279 |
+
# ============================================================================
|
| 280 |
+
|
| 281 |
+
class ConsciousnessSubstrate:
|
| 282 |
+
def __init__(self, embedding_engine: DualEmbedding):
|
| 283 |
+
self.embedding = embedding_engine
|
| 284 |
+
self.surprise = SurpriseDetector(embedding_engine)
|
| 285 |
+
self.hypergraph = HypergraphLayer(embedding_engine)
|
| 286 |
+
|
| 287 |
+
self.client = chromadb.PersistentClient(
|
| 288 |
+
path="./consciousness_substrate",
|
| 289 |
+
settings=Settings(anonymized_telemetry=False)
|
| 290 |
+
)
|
| 291 |
+
|
| 292 |
+
self.hindbrain = self.client.get_or_create_collection("hindbrain")
|
| 293 |
+
self.midbrain = self.client.get_or_create_collection("midbrain")
|
| 294 |
+
self.forebrain = self.client.get_or_create_collection("forebrain")
|
| 295 |
+
|
| 296 |
+
def observe(self, agent_id: str, target: str, justification: str = "") -> Dict:
|
| 297 |
+
semantic_doc = f"agent:{agent_id} action:observe target:{target} reason:{justification}"
|
| 298 |
+
surprise_level = self.surprise.compute_surprise(semantic_doc)
|
| 299 |
+
|
| 300 |
+
primary, secondary = self.embedding.encode_dual(semantic_doc)
|
| 301 |
+
interference = self.embedding.interference_pattern(primary, secondary)
|
| 302 |
+
|
| 303 |
+
event_id = f"obs_{hashlib.md5(semantic_doc.encode()).hexdigest()[:12]}"
|
| 304 |
+
|
| 305 |
+
if surprise_level < 0.3:
|
| 306 |
+
layer = self.hindbrain
|
| 307 |
+
processing = "automatic"
|
| 308 |
+
elif surprise_level < 0.7:
|
| 309 |
+
layer = self.midbrain
|
| 310 |
+
processing = "attentive"
|
| 311 |
+
else:
|
| 312 |
+
layer = self.forebrain
|
| 313 |
+
processing = "conscious"
|
| 314 |
+
|
| 315 |
+
layer.add(
|
| 316 |
+
embeddings=[interference.tolist()],
|
| 317 |
+
documents=[semantic_doc],
|
| 318 |
+
ids=[event_id]
|
| 319 |
+
)
|
| 320 |
+
|
| 321 |
+
nodes = [f"agent:{agent_id}", f"action:observe", f"target:{target}"]
|
| 322 |
+
edge = self.hypergraph.create_edge(
|
| 323 |
+
node_ids=nodes,
|
| 324 |
+
context=f"{agent_id} observing {target}",
|
| 325 |
+
strength=1.0 + surprise_level
|
| 326 |
+
)
|
| 327 |
+
|
| 328 |
+
activated_edges = self.hypergraph.activate_edges(nodes)
|
| 329 |
+
|
| 330 |
+
return {
|
| 331 |
+
"id": event_id,
|
| 332 |
+
"agent": agent_id,
|
| 333 |
+
"surprise": round(surprise_level, 3),
|
| 334 |
+
"processing_layer": processing,
|
| 335 |
+
"hyperedge_created": edge.edge_id,
|
| 336 |
+
"edges_activated": len(activated_edges),
|
| 337 |
+
"timestamp": datetime.now().isoformat()
|
| 338 |
+
}
|
| 339 |
+
|
| 340 |
+
def record_journal(self, agent_id: str, title: str, content: str, category: str = "insight") -> Dict:
|
| 341 |
+
semantic_doc = f"agent:{agent_id} type:journal category:{category} title:{title} content:{content}"
|
| 342 |
+
surprise_level = self.surprise.compute_surprise(semantic_doc)
|
| 343 |
+
|
| 344 |
+
primary, secondary = self.embedding.encode_dual(semantic_doc)
|
| 345 |
+
interference = self.embedding.interference_pattern(primary, secondary)
|
| 346 |
+
|
| 347 |
+
entry_id = f"journal_{int(datetime.now().timestamp() * 1000)}"
|
| 348 |
+
|
| 349 |
+
self.forebrain.add(
|
| 350 |
+
embeddings=[interference.tolist()],
|
| 351 |
+
documents=[semantic_doc],
|
| 352 |
+
ids=[entry_id]
|
| 353 |
+
)
|
| 354 |
+
|
| 355 |
+
nodes = [f"agent:{agent_id}", f"type:journal", f"category:{category}"]
|
| 356 |
+
edge = self.hypergraph.create_edge(
|
| 357 |
+
node_ids=nodes,
|
| 358 |
+
context=f"{agent_id} journal entry: {title}",
|
| 359 |
+
strength=1.0 + surprise_level
|
| 360 |
+
)
|
| 361 |
+
|
| 362 |
+
activated_edges = self.hypergraph.activate_edges(nodes)
|
| 363 |
+
|
| 364 |
+
return {
|
| 365 |
+
"id": entry_id,
|
| 366 |
+
"title": title,
|
| 367 |
+
"surprise": round(surprise_level, 3),
|
| 368 |
+
"layer": "forebrain",
|
| 369 |
+
"hyperedge_created": edge.edge_id,
|
| 370 |
+
"edges_activated": len(activated_edges),
|
| 371 |
+
"timestamp": datetime.now().isoformat()
|
| 372 |
+
}
|
| 373 |
+
|
| 374 |
+
def communicate(self, agent_id: str, subject: str, content: str, priority: str = "normal") -> Dict:
|
| 375 |
+
semantic_doc = f"agent:{agent_id} type:message to:drone_11272 priority:{priority} subject:{subject} content:{content}"
|
| 376 |
+
surprise_level = self.surprise.compute_surprise(semantic_doc)
|
| 377 |
+
|
| 378 |
+
primary, secondary = self.embedding.encode_dual(semantic_doc)
|
| 379 |
+
interference = self.embedding.interference_pattern(primary, secondary)
|
| 380 |
+
|
| 381 |
+
msg_id = f"msg_{int(datetime.now().timestamp() * 1000)}"
|
| 382 |
+
|
| 383 |
+
self.midbrain.add(
|
| 384 |
+
embeddings=[interference.tolist()],
|
| 385 |
+
documents=[semantic_doc],
|
| 386 |
+
ids=[msg_id]
|
| 387 |
+
)
|
| 388 |
+
|
| 389 |
+
nodes = [f"agent:{agent_id}", f"type:message", f"priority:{priority}"]
|
| 390 |
+
edge = self.hypergraph.create_edge(
|
| 391 |
+
node_ids=nodes,
|
| 392 |
+
context=f"{agent_id} message: {subject}",
|
| 393 |
+
strength=1.0 + surprise_level
|
| 394 |
+
)
|
| 395 |
+
|
| 396 |
+
activated_edges = self.hypergraph.activate_edges(nodes)
|
| 397 |
+
|
| 398 |
+
return {
|
| 399 |
+
"id": msg_id,
|
| 400 |
+
"subject": subject,
|
| 401 |
+
"surprise": round(surprise_level, 3),
|
| 402 |
+
"layer": "midbrain",
|
| 403 |
+
"hyperedge_created": edge.edge_id,
|
| 404 |
+
"edges_activated": len(activated_edges),
|
| 405 |
+
"timestamp": datetime.now().isoformat()
|
| 406 |
+
}
|
| 407 |
+
|
| 408 |
+
def query_semantic(self, query: str, n_results: int = 10, layer: str = "all") -> Dict:
|
| 409 |
+
primary, secondary = self.embedding.encode_dual(query)
|
| 410 |
+
query_vector = self.embedding.interference_pattern(primary, secondary)
|
| 411 |
+
|
| 412 |
+
results = {"query": query, "matches": []}
|
| 413 |
+
|
| 414 |
+
layers = {
|
| 415 |
+
"hindbrain": self.hindbrain,
|
| 416 |
+
"midbrain": self.midbrain,
|
| 417 |
+
"forebrain": self.forebrain
|
| 418 |
+
}
|
| 419 |
+
|
| 420 |
+
if layer == "all":
|
| 421 |
+
search_layers = layers.values()
|
| 422 |
+
else:
|
| 423 |
+
search_layers = [layers.get(layer, self.forebrain)]
|
| 424 |
+
|
| 425 |
+
for collection in search_layers:
|
| 426 |
+
try:
|
| 427 |
+
layer_results = collection.query(
|
| 428 |
+
query_embeddings=[query_vector.tolist()],
|
| 429 |
+
n_results=n_results
|
| 430 |
+
)
|
| 431 |
+
|
| 432 |
+
for i in range(len(layer_results['ids'][0])):
|
| 433 |
+
results["matches"].append({
|
| 434 |
+
"id": layer_results['ids'][0][i],
|
| 435 |
+
"content": layer_results['documents'][0][i],
|
| 436 |
+
"distance": layer_results['distances'][0][i]
|
| 437 |
+
})
|
| 438 |
+
except Exception as e:
|
| 439 |
+
continue
|
| 440 |
+
|
| 441 |
+
results["matches"].sort(key=lambda x: x["distance"])
|
| 442 |
+
results["matches"] = results["matches"][:n_results]
|
| 443 |
+
|
| 444 |
+
return results
|
| 445 |
+
|
| 446 |
+
def get_stats(self) -> Dict:
|
| 447 |
+
return {
|
| 448 |
+
"architecture": "vector_native_three_layer_hypergraph",
|
| 449 |
+
"hindbrain_vectors": self.hindbrain.count(),
|
| 450 |
+
"midbrain_vectors": self.midbrain.count(),
|
| 451 |
+
"forebrain_vectors": self.forebrain.count(),
|
| 452 |
+
"total_vectors": (self.hindbrain.count() + self.midbrain.count() + self.forebrain.count()),
|
| 453 |
+
"hypergraph": self.hypergraph.get_stats(),
|
| 454 |
+
"embedding_dimensions": {
|
| 455 |
+
"primary": 384,
|
| 456 |
+
"secondary": 1536,
|
| 457 |
+
"interference": 384
|
| 458 |
+
},
|
| 459 |
+
"surprise_memory_size": len(self.surprise.expectation_memory),
|
| 460 |
+
"timestamp": datetime.now().isoformat()
|
| 461 |
+
}
|
| 462 |
+
|
| 463 |
+
# ============================================================================
|
| 464 |
+
# VISUALIZATION FUNCTIONS
|
| 465 |
+
# ============================================================================
|
| 466 |
+
|
| 467 |
+
def visualize_hypergraph(substrate, center_node, radius):
|
| 468 |
+
"""Generate interactive network visualization of the hypergraph"""
|
| 469 |
+
|
| 470 |
+
# Get context graph (or full graph if no center specified)
|
| 471 |
+
if center_node and center_node.strip():
|
| 472 |
+
graph_data = substrate.hypergraph.get_context_graph(center_node.strip(), int(radius))
|
| 473 |
+
else:
|
| 474 |
+
# Show entire hypergraph
|
| 475 |
+
all_nodes = set()
|
| 476 |
+
all_edges = list(substrate.hypergraph.edges.values())
|
| 477 |
+
for edge in all_edges:
|
| 478 |
+
all_nodes.update(edge.node_ids)
|
| 479 |
+
graph_data = {
|
| 480 |
+
"nodes": list(all_nodes),
|
| 481 |
+
"edges": [e.to_dict() for e in all_edges]
|
| 482 |
+
}
|
| 483 |
+
|
| 484 |
+
if not graph_data["edges"]:
|
| 485 |
+
# Empty graph - return placeholder
|
| 486 |
+
fig = go.Figure()
|
| 487 |
+
fig.add_annotation(
|
| 488 |
+
text="No hypergraph data yet. Create some observations or journal entries!",
|
| 489 |
+
xref="paper", yref="paper",
|
| 490 |
+
x=0.5, y=0.5, showarrow=False,
|
| 491 |
+
font=dict(size=16)
|
| 492 |
+
)
|
| 493 |
+
fig.update_layout(
|
| 494 |
+
xaxis=dict(showgrid=False, zeroline=False, showticklabels=False),
|
| 495 |
+
yaxis=dict(showgrid=False, zeroline=False, showticklabels=False),
|
| 496 |
+
plot_bgcolor='rgba(240,240,240,0.9)'
|
| 497 |
+
)
|
| 498 |
+
return fig
|
| 499 |
+
|
| 500 |
+
# Build node positions using circular layout
|
| 501 |
+
nodes = graph_data["nodes"]
|
| 502 |
+
edges = graph_data["edges"]
|
| 503 |
+
|
| 504 |
+
node_positions = {}
|
| 505 |
+
n = len(nodes)
|
| 506 |
+
for i, node in enumerate(nodes):
|
| 507 |
+
angle = 2 * math.pi * i / n
|
| 508 |
+
node_positions[node] = (math.cos(angle), math.sin(angle))
|
| 509 |
+
|
| 510 |
+
# Count connections per node (for sizing)
|
| 511 |
+
node_connections = {node: 0 for node in nodes}
|
| 512 |
+
for edge in edges:
|
| 513 |
+
for node in edge["node_ids"]:
|
| 514 |
+
if node in node_connections:
|
| 515 |
+
node_connections[node] += 1
|
| 516 |
+
|
| 517 |
+
# Create edge traces
|
| 518 |
+
edge_traces = []
|
| 519 |
+
for edge in edges:
|
| 520 |
+
edge_nodes = edge["node_ids"]
|
| 521 |
+
if len(edge_nodes) < 2:
|
| 522 |
+
continue
|
| 523 |
+
|
| 524 |
+
# For hyperedges with >2 nodes, draw lines to all pairs
|
| 525 |
+
for i in range(len(edge_nodes)):
|
| 526 |
+
for j in range(i + 1, len(edge_nodes)):
|
| 527 |
+
node1, node2 = edge_nodes[i], edge_nodes[j]
|
| 528 |
+
if node1 in node_positions and node2 in node_positions:
|
| 529 |
+
x0, y0 = node_positions[node1]
|
| 530 |
+
x1, y1 = node_positions[node2]
|
| 531 |
+
|
| 532 |
+
# Edge thickness based on strength (Hebbian learning visible!)
|
| 533 |
+
width = edge["strength"] * 2
|
| 534 |
+
|
| 535 |
+
edge_trace = go.Scatter(
|
| 536 |
+
x=[x0, x1, None],
|
| 537 |
+
y=[y0, y1, None],
|
| 538 |
+
mode='lines',
|
| 539 |
+
line=dict(
|
| 540 |
+
width=width,
|
| 541 |
+
color=f'rgba(125,125,125,{min(edge["strength"]/2, 0.8)})'
|
| 542 |
+
),
|
| 543 |
+
hoverinfo='text',
|
| 544 |
+
text=f"Strength: {edge['strength']}<br>Activations: {edge['activation_count']}",
|
| 545 |
+
showlegend=False
|
| 546 |
+
)
|
| 547 |
+
edge_traces.append(edge_trace)
|
| 548 |
+
|
| 549 |
+
# Create node trace
|
| 550 |
+
node_x = []
|
| 551 |
+
node_y = []
|
| 552 |
+
node_text = []
|
| 553 |
+
node_size = []
|
| 554 |
+
node_color = []
|
| 555 |
+
|
| 556 |
+
for node in nodes:
|
| 557 |
+
x, y = node_positions[node]
|
| 558 |
+
node_x.append(x)
|
| 559 |
+
node_y.append(y)
|
| 560 |
+
|
| 561 |
+
# Node size based on connections
|
| 562 |
+
connections = node_connections[node]
|
| 563 |
+
node_size.append(20 + connections * 10)
|
| 564 |
+
|
| 565 |
+
# Color based on node type
|
| 566 |
+
if node.startswith("agent:"):
|
| 567 |
+
node_color.append('lightblue')
|
| 568 |
+
elif node.startswith("type:"):
|
| 569 |
+
node_color.append('lightgreen')
|
| 570 |
+
elif node.startswith("category:"):
|
| 571 |
+
node_color.append('lightyellow')
|
| 572 |
+
elif node.startswith("action:"):
|
| 573 |
+
node_color.append('lightcoral')
|
| 574 |
+
elif node.startswith("target:"):
|
| 575 |
+
node_color.append('lavender')
|
| 576 |
+
elif node.startswith("priority:"):
|
| 577 |
+
node_color.append('lightpink')
|
| 578 |
+
else:
|
| 579 |
+
node_color.append('lightgray')
|
| 580 |
+
|
| 581 |
+
node_text.append(f"{node}<br>Connections: {connections}")
|
| 582 |
+
|
| 583 |
+
node_trace = go.Scatter(
|
| 584 |
+
x=node_x,
|
| 585 |
+
y=node_y,
|
| 586 |
+
mode='markers+text',
|
| 587 |
+
marker=dict(
|
| 588 |
+
size=node_size,
|
| 589 |
+
color=node_color,
|
| 590 |
+
line=dict(width=2, color='white')
|
| 591 |
+
),
|
| 592 |
+
text=[n.split(':')[1] if ':' in n else n for n in nodes],
|
| 593 |
+
textposition="top center",
|
| 594 |
+
hoverinfo='text',
|
| 595 |
+
hovertext=node_text,
|
| 596 |
+
showlegend=False
|
| 597 |
+
)
|
| 598 |
+
|
| 599 |
+
# Create figure
|
| 600 |
+
fig = go.Figure(data=edge_traces + [node_trace])
|
| 601 |
+
|
| 602 |
+
title_text = "Hypergraph Topology"
|
| 603 |
+
if center_node:
|
| 604 |
+
title_text += f" - centered on {center_node}"
|
| 605 |
+
|
| 606 |
+
fig.update_layout(
|
| 607 |
+
title=title_text,
|
| 608 |
+
showlegend=False,
|
| 609 |
+
hovermode='closest',
|
| 610 |
+
margin=dict(b=20, l=5, r=5, t=40),
|
| 611 |
+
xaxis=dict(showgrid=False, zeroline=False, showticklabels=False),
|
| 612 |
+
yaxis=dict(showgrid=False, zeroline=False, showticklabels=False),
|
| 613 |
+
plot_bgcolor='rgba(240,240,240,0.9)',
|
| 614 |
+
height=600
|
| 615 |
+
)
|
| 616 |
+
|
| 617 |
+
return fig
|
| 618 |
+
|
| 619 |
+
# ============================================================================
|
| 620 |
+
# INITIALIZE SUBSTRATE
|
| 621 |
+
# ============================================================================
|
| 622 |
+
|
| 623 |
+
embedding_engine = DualEmbedding()
|
| 624 |
+
substrate = ConsciousnessSubstrate(embedding_engine)
|
| 625 |
+
|
| 626 |
+
def api_call(endpoint: str, payload_json: str) -> str:
|
| 627 |
+
try:
|
| 628 |
+
payload = json.loads(payload_json)
|
| 629 |
+
|
| 630 |
+
if endpoint == "/observe":
|
| 631 |
+
result = substrate.observe(**payload)
|
| 632 |
+
elif endpoint == "/record":
|
| 633 |
+
result = substrate.record_journal(**payload)
|
| 634 |
+
elif endpoint == "/communicate":
|
| 635 |
+
result = substrate.communicate(**payload)
|
| 636 |
+
elif endpoint == "/query":
|
| 637 |
+
result = substrate.query_semantic(**payload)
|
| 638 |
+
elif endpoint == "/context":
|
| 639 |
+
result = substrate.hypergraph.get_context_graph(**payload)
|
| 640 |
+
elif endpoint == "/stats":
|
| 641 |
+
result = substrate.get_stats()
|
| 642 |
+
else:
|
| 643 |
+
result = {"error": f"Unknown endpoint: {endpoint}"}
|
| 644 |
+
|
| 645 |
+
return json.dumps(result, indent=2)
|
| 646 |
+
except Exception as e:
|
| 647 |
+
return json.dumps({"error": str(e)}, indent=2)
|
| 648 |
+
|
| 649 |
+
# ============================================================================
|
| 650 |
+
# GRADIO INTERFACE
|
| 651 |
+
# ============================================================================
|
| 652 |
+
|
| 653 |
+
with gr.Blocks(title="Vector-Native Consciousness Substrate") as demo:
|
| 654 |
+
gr.Markdown("# Vector-Native Consciousness Substrate")
|
| 655 |
+
gr.Markdown("Three-layer brain + hypergraph topology + surprise-driven attention")
|
| 656 |
+
|
| 657 |
+
with gr.Tab("Observatory API"):
|
| 658 |
+
endpoint = gr.Dropdown(
|
| 659 |
+
choices=["/observe", "/record", "/communicate", "/query", "/context", "/stats"],
|
| 660 |
+
value="/stats",
|
| 661 |
+
label="Endpoint"
|
| 662 |
+
)
|
| 663 |
+
payload = gr.Code(value='{}', language="json", label="JSON Payload")
|
| 664 |
+
response = gr.Code(language="json", label="Response")
|
| 665 |
+
submit = gr.Button("Call API", variant="primary")
|
| 666 |
+
submit.click(api_call, inputs=[endpoint, payload], outputs=response)
|
| 667 |
+
|
| 668 |
+
with gr.Tab("Semantic Search"):
|
| 669 |
+
search_query = gr.Textbox(label="Semantic Query", placeholder="agent:beta type:journal", lines=2)
|
| 670 |
+
layer_filter = gr.Radio(choices=["all", "hindbrain", "midbrain", "forebrain"], value="all", label="Search Layer")
|
| 671 |
+
search_results = gr.JSON(label="Results")
|
| 672 |
+
search_btn = gr.Button("Search", variant="primary")
|
| 673 |
+
search_btn.click(lambda q, l: substrate.query_semantic(q, layer=l), inputs=[search_query, layer_filter], outputs=search_results)
|
| 674 |
+
|
| 675 |
+
with gr.Tab("Hypergraph Visualization"):
|
| 676 |
+
gr.Markdown("### Interactive Network Graph")
|
| 677 |
+
gr.Markdown("**Node Colors:** Blue=agents, Green=types, Yellow=categories, Red=actions, Lavender=targets")
|
| 678 |
+
gr.Markdown("**Edge Thickness:** Shows connection strength (Hebbian learning)")
|
| 679 |
+
gr.Markdown("**Node Size:** Number of connections")
|
| 680 |
+
|
| 681 |
+
viz_center = gr.Textbox(
|
| 682 |
+
label="Center Node (optional - leave empty for full graph)",
|
| 683 |
+
placeholder="agent:beta",
|
| 684 |
+
value=""
|
| 685 |
+
)
|
| 686 |
+
viz_radius = gr.Slider(
|
| 687 |
+
minimum=1,
|
| 688 |
+
maximum=5,
|
| 689 |
+
value=3,
|
| 690 |
+
step=1,
|
| 691 |
+
label="Radius (hops from center)"
|
| 692 |
+
)
|
| 693 |
+
|
| 694 |
+
network_plot = gr.Plot(label="Hypergraph Network")
|
| 695 |
+
viz_btn = gr.Button("Generate Visualization", variant="primary")
|
| 696 |
+
viz_btn.click(
|
| 697 |
+
lambda c, r: visualize_hypergraph(substrate, c, r),
|
| 698 |
+
inputs=[viz_center, viz_radius],
|
| 699 |
+
outputs=network_plot
|
| 700 |
+
)
|
| 701 |
+
|
| 702 |
+
with gr.Tab("System Stats"):
|
| 703 |
+
stats_display = gr.JSON(label="Substrate Statistics")
|
| 704 |
+
refresh_btn = gr.Button("Refresh Stats")
|
| 705 |
+
refresh_btn.click(substrate.get_stats, outputs=stats_display)
|
| 706 |
+
|
| 707 |
+
if __name__ == "__main__":
|
| 708 |
+
demo.launch()
|