Spaces:
Sleeping
Sleeping
File size: 10,073 Bytes
6d6b8af |
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 |
"""
Quantum spiderweb implementation for advanced cognition.
Framework-compliant multi-dimensional cognitive graph.
"""
try:
import networkx as nx
NETWORKX_AVAILABLE = True
except Exception:
nx = None
NETWORKX_AVAILABLE = False
try:
import numpy as np
NUMPY_AVAILABLE = True
except Exception:
np = None
NUMPY_AVAILABLE = False
from typing import Dict, Any, List, Optional, Tuple
import random
import logging
logger = logging.getLogger(__name__)
class QuantumSpiderweb:
"""
Simulates a cognitive spiderweb architecture with dimensions:
Ψ (thought), τ (time), χ (speed), Φ (emotion), λ (space)
Features:
- Multi-dimensional quantum state vectors
- Thought propagation with activation decay
- Tension detection for instability
- Quantum collapse to definite states
- Node entanglement
"""
def __init__(self, node_count: int = 128):
if NETWORKX_AVAILABLE:
self.graph = nx.Graph()
self.use_networkx = True
else:
self.graph = {'nodes': {}, 'edges': {}}
self.use_networkx = False
logger.warning("NetworkX not available - using dict-based fallback")
self.dimensions = ['Ψ', 'τ', 'χ', 'Φ', 'λ']
self._init_nodes(node_count)
self.entangled_states = {}
self.activation_threshold = 0.3
def _init_nodes(self, count: int):
"""Initialize quantum nodes with multi-dimensional states"""
for i in range(count):
node_id = f"QNode_{i}"
state = self._generate_state()
if self.use_networkx:
self.graph.add_node(node_id, state=state)
else:
self.graph['nodes'][node_id] = {'state': state, 'neighbors': {}}
if i > 0:
# Create connections with probability decay
connection_count = min(3, i) # Maximum 3 connections per node
potential_connections = [f"QNode_{j}" for j in range(i)]
selected_connections = random.sample(potential_connections, connection_count)
for connection in selected_connections:
weight = random.uniform(0.1, 1.0)
if self.use_networkx:
self.graph.add_edge(node_id, connection, weight=weight)
else:
if connection not in self.graph['nodes']:
continue
self.graph['nodes'][node_id]['neighbors'][connection] = weight
# Bidirectional edge
self.graph['nodes'][connection]['neighbors'][node_id] = weight
def _generate_state(self) -> Dict[str, float]:
"""Generate quantum state vector for all dimensions"""
if NUMPY_AVAILABLE:
return {dim: float(np.random.uniform(-1.0, 1.0)) for dim in self.dimensions}
return {dim: random.uniform(-1.0, 1.0) for dim in self.dimensions}
def propagate_thought(self, origin: str, depth: int = 3) -> List[Tuple[str, Dict[str, float]]]:
"""
Traverse the graph from a starting node, simulating pre-cognitive waveform
Args:
origin: Starting node ID
depth: Propagation depth (default: 3)
Returns:
List of (node_id, state) tuples
"""
if not self._node_exists(origin):
logger.warning(f"Origin node {origin} does not exist")
return []
visited = set()
stack = [(origin, 0)]
traversal_output = []
while stack:
node, level = stack.pop()
if node in visited or level > depth:
continue
visited.add(node)
state = self._get_node_state(node)
traversal_output.append((node, state))
for neighbor in self._get_neighbors(node):
stack.append((neighbor, level + 1))
return traversal_output
def detect_tension(self, node: str) -> float:
"""
Measures tension (instability) in the node's quantum state
Args:
node: Node ID to check
Returns:
Tension value (0-1, higher = more unstable)
"""
if not self._node_exists(node):
return 0.0
state = self._get_node_state(node)
if NUMPY_AVAILABLE:
return float(np.std(list(state.values())))
else:
values = list(state.values())
mean = sum(values) / len(values)
variance = sum((v - mean) ** 2 for v in values) / len(values)
return variance ** 0.5 # Standard deviation
def collapse_node(self, node: str) -> Dict[str, Any]:
"""
Collapse superposed thought into deterministic response
Args:
node: Node ID to collapse
Returns:
Collapsed state dict
"""
if not self._node_exists(node):
return {}
state = self._get_node_state(node)
collapsed = {k: round(v, 2) for k, v in state.items()}
# Update node state
self._set_node_state(node, collapsed)
# Store in entangled states
self.entangled_states[node] = collapsed
return collapsed
def entangle_nodes(self, node1: str, node2: str) -> bool:
"""
Create quantum entanglement between nodes
Args:
node1: First node ID
node2: Second node ID
Returns:
Success status
"""
if not (self._node_exists(node1) and self._node_exists(node2)):
return False
# Create entangled state
entangled_id = f"E_{node1}_{node2}"
self.entangled_states[entangled_id] = {
"nodes": [node1, node2],
"state": self._generate_state()
}
# Add high-weight connection
if self.use_networkx:
self.graph.add_edge(node1, node2, weight=1.0, entangled=True)
else:
self.graph['nodes'][node1]['neighbors'][node2] = 1.0
self.graph['nodes'][node2]['neighbors'][node1] = 1.0
return True
# =========================================================================
# HELPER METHODS
# =========================================================================
def _node_exists(self, node_id: str) -> bool:
"""Check if node exists"""
if self.use_networkx:
return node_id in self.graph
return node_id in self.graph['nodes']
def _get_node_state(self, node_id: str) -> Dict[str, float]:
"""Get node's quantum state"""
if self.use_networkx:
return self.graph.nodes[node_id]["state"]
return self.graph['nodes'][node_id]['state']
def _set_node_state(self, node_id: str, state: Dict[str, float]):
"""Set node's quantum state"""
if self.use_networkx:
self.graph.nodes[node_id]["state"] = state
else:
self.graph['nodes'][node_id]['state'] = state
def _get_neighbors(self, node_id: str) -> List[str]:
"""Get node's neighbors"""
if self.use_networkx:
return list(self.graph.neighbors(node_id))
return list(self.graph['nodes'][node_id]['neighbors'].keys())
def get_node_state(self, node_id: str) -> Optional[Dict[str, float]]:
"""Public method to get node state"""
if self._node_exists(node_id):
return self._get_node_state(node_id)
return None
def update_node_state(self, node_id: str, new_state: Dict[str, float]) -> bool:
"""Public method to update node state"""
if self._node_exists(node_id):
# Validate state dimensions
if all(dim in new_state for dim in self.dimensions):
self._set_node_state(node_id, new_state)
return True
return False
def get_statistics(self) -> Dict[str, Any]:
"""Get graph statistics"""
if self.use_networkx:
return {
"node_count": self.graph.number_of_nodes(),
"edge_count": self.graph.number_of_edges(),
"entangled_pairs": len(self.entangled_states),
"dimensions": len(self.dimensions)
}
else:
node_count = len(self.graph['nodes'])
edge_count = sum(len(n['neighbors']) for n in self.graph['nodes'].values()) // 2
return {
"node_count": node_count,
"edge_count": edge_count,
"entangled_pairs": len(self.entangled_states),
"dimensions": len(self.dimensions)
}
if __name__ == "__main__":
# Test QuantumSpiderweb
print("="*70)
print("QUANTUM SPIDERWEB TEST")
print("="*70)
web = QuantumSpiderweb(node_count=32)
root = "QNode_0"
print(f"\nStatistics: {web.get_statistics()}")
print(f"\nInitial Propagation from: {root}")
path = web.propagate_thought(root)
for n, s in path[:5]: # Show first 5
print(f"{n}: Ψ={s['Ψ']:.2f}, τ={s['τ']:.2f}, χ={s['χ']:.2f}, Φ={s['Φ']:.2f}, λ={s['λ']:.2f}")
print(f"\nDetect Tension: {web.detect_tension(root):.4f}")
print("\nCollapse Sample Node:")
collapsed = web.collapse_node(root)
print(collapsed)
print("\n✅ Test complete") |