Spaces:
Sleeping
Sleeping
File size: 13,378 Bytes
4a0fa9c |
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 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 |
"""
NEBULA EMERGENT - Examples and Use Cases
Author: Francisco Angulo de Lafuente
This file contains examples of how to use the NEBULA EMERGENT system
"""
import numpy as np
import matplotlib.pyplot as plt
from typing import List, Tuple
import json
# Note: These examples assume you have the nebula_emergent module
# In the Space, this is integrated into app.py
def example_basic_usage():
"""Basic example of creating and evolving a NEBULA system"""
print("=" * 50)
print("Example 1: Basic System Creation and Evolution")
print("=" * 50)
# Import the system (in production, this would be from the main module)
from app import NebulaEmergent
# Create a system with 1000 neurons
nebula = NebulaEmergent(n_neurons=1000)
print(f"Created system with {nebula.n_neurons} neurons")
# Enable all physics
nebula.gravity_enabled = True
nebula.quantum_enabled = True
nebula.photon_enabled = True
# Evolve for 100 steps
for i in range(100):
nebula.evolve()
if i % 20 == 0:
metrics = nebula.metrics
print(f"Step {i}: Energy={metrics['energy']:.6f}, "
f"Entropy={metrics['entropy']:.3f}, "
f"Clusters={metrics['clusters']}")
# Extract final state
clusters = nebula.extract_clusters()
print(f"\nFinal state: {len(clusters)} clusters formed")
return nebula
def example_pattern_recognition():
"""Example of using NEBULA for pattern recognition"""
print("=" * 50)
print("Example 2: Pattern Recognition")
print("=" * 50)
from app import NebulaEmergent
# Create system
nebula = NebulaEmergent(n_neurons=5000)
# Create a simple pattern (checkerboard)
pattern = np.array([
[1, 0, 1, 0, 1],
[0, 1, 0, 1, 0],
[1, 0, 1, 0, 1],
[0, 1, 0, 1, 0],
[1, 0, 1, 0, 1]
])
print("Input pattern (5x5 checkerboard):")
print(pattern)
# Encode the pattern
nebula.encode_problem(pattern)
# Evolve until convergence
previous_clusters = 0
stable_count = 0
for i in range(500):
nebula.evolve()
clusters = nebula.extract_clusters()
current_clusters = len(clusters)
# Check for stability
if current_clusters == previous_clusters:
stable_count += 1
else:
stable_count = 0
previous_clusters = current_clusters
# Stop if stable for 20 steps
if stable_count >= 20:
print(f"System stabilized at step {i} with {current_clusters} clusters")
break
if i % 50 == 0:
print(f"Step {i}: {current_clusters} clusters, "
f"Emergence score: {nebula.metrics['emergence_score']:.3f}")
# Decode the solution
solution = nebula.decode_solution()
print(f"\nDecoded solution shape: {solution.shape}")
print(f"Solution values (first 10): {solution[:10]}")
return nebula, solution
def example_optimization_problem():
"""Example of solving an optimization problem"""
print("=" * 50)
print("Example 3: Function Optimization")
print("=" * 50)
from app import NebulaEmergent
# Create system
nebula = NebulaEmergent(n_neurons=2000)
# Define a function to optimize: f(x,y) = -(x^2 + y^2) + 4*sin(x*y)
# We want to find the maximum
# Create a grid of function values
x = np.linspace(-2, 2, 20)
y = np.linspace(-2, 2, 20)
X, Y = np.meshgrid(x, y)
Z = -(X**2 + Y**2) + 4*np.sin(X*Y)
# Normalize to [0, 1]
Z_norm = (Z - Z.min()) / (Z.max() - Z.min())
print(f"Optimizing function: f(x,y) = -(xΒ² + yΒ²) + 4*sin(x*y)")
print(f"Function value range: [{Z.min():.3f}, {Z.max():.3f}]")
# Encode the function landscape
nebula.encode_problem(Z_norm)
# Use simulated annealing
nebula.temperature = 1000.0 # Start with high temperature
best_value = -np.inf
best_position = None
for i in range(200):
nebula.evolve()
# Cool down
nebula.temperature *= 0.98
# Find the neuron with highest activation
activations = [n.activation for n in nebula.neurons]
best_idx = np.argmax(activations)
best_neuron = nebula.neurons[best_idx]
if best_neuron.activation > best_value:
best_value = best_neuron.activation
best_position = best_neuron.position
if i % 40 == 0:
print(f"Step {i}: Temperature={nebula.temperature:.1f}, "
f"Best value={best_value:.3f}")
print(f"\nOptimization complete!")
print(f"Best position found: {best_position}")
print(f"Best value: {best_value:.3f}")
return nebula, best_position
def example_traveling_salesman():
"""Example of solving TSP with NEBULA"""
print("=" * 50)
print("Example 4: Traveling Salesman Problem")
print("=" * 50)
from app import NebulaEmergent
from scipy.spatial.distance import cdist
# Create system
nebula = NebulaEmergent(n_neurons=3000)
# Generate random cities
n_cities = 8
cities = np.random.random((n_cities, 2))
print(f"Solving TSP for {n_cities} cities")
# Calculate distance matrix
distances = cdist(cities, cities)
# Encode distances (inverted so shorter = higher activation)
encoded_distances = 1.0 / (distances + 0.1)
np.fill_diagonal(encoded_distances, 0)
# Flatten and encode
nebula.encode_problem(encoded_distances)
# High temperature for exploration
nebula.temperature = 2000.0
best_route = None
best_distance = float('inf')
for i in range(300):
nebula.evolve()
# Anneal
nebula.temperature *= 0.97
# Extract solution
solution = nebula.decode_solution()
# Convert to route (simplified)
if len(solution) >= n_cities:
route = np.argsort(solution[:n_cities])
# Calculate route distance
route_distance = sum(
distances[route[j], route[(j+1) % n_cities]]
for j in range(n_cities)
)
if route_distance < best_distance:
best_distance = route_distance
best_route = route
if i % 50 == 0:
print(f"Step {i}: Best distance={best_distance:.3f}, "
f"Temperature={nebula.temperature:.1f}")
print(f"\nTSP Solution found!")
print(f"Best route: {best_route}")
print(f"Total distance: {best_distance:.3f}")
return nebula, best_route, cities
def example_quantum_computation():
"""Example of using quantum features"""
print("=" * 50)
print("Example 5: Quantum Computation Features")
print("=" * 50)
from app import NebulaEmergent
# Create system with enhanced quantum features
nebula = NebulaEmergent(n_neurons=1000)
nebula.quantum_enabled = True
nebula.gravity_enabled = False # Disable gravity to focus on quantum
nebula.photon_enabled = True
print("Quantum processor initialized with {} qubits".format(
nebula.quantum_processor.n_qubits))
# Create entangled states
print("\nCreating quantum superposition and entanglement...")
for i in range(100):
nebula.evolve()
if i % 20 == 0:
coherence = nebula.metrics['quantum_coherence']
print(f"Step {i}: Quantum coherence={coherence:.3f}")
# Measure quantum state
outcome = nebula.quantum_processor.measure()
print(f"\nQuantum measurement outcome: {bin(outcome)}")
# Check for quantum correlations
entangled_neurons = [
i for i, n in enumerate(nebula.neurons)
if n.entanglement is not None
]
print(f"Number of entangled neurons: {len(entangled_neurons)}")
return nebula
def example_emergent_behavior():
"""Example demonstrating emergent behavior"""
print("=" * 50)
print("Example 6: Emergent Behavior and Self-Organization")
print("=" * 50)
from app import NebulaEmergent
# Create a large system
nebula = NebulaEmergent(n_neurons=5000)
# Start with random initial conditions
print("Starting with random initial conditions...")
# Track emergence over time
emergence_history = []
cluster_history = []
for i in range(500):
nebula.evolve()
if i % 10 == 0:
emergence_history.append(nebula.metrics['emergence_score'])
cluster_history.append(nebula.metrics['clusters'])
if i % 100 == 0:
print(f"Step {i}: "
f"Emergence={nebula.metrics['emergence_score']:.3f}, "
f"Clusters={nebula.metrics['clusters']}, "
f"Entropy={nebula.metrics['entropy']:.3f}")
# Analyze emergent patterns
print("\n" + "=" * 30)
print("Emergent Behavior Analysis:")
print("=" * 30)
print(f"Initial emergence score: {emergence_history[0]:.3f}")
print(f"Final emergence score: {emergence_history[-1]:.3f}")
print(f"Maximum emergence: {max(emergence_history):.3f}")
print(f"\nInitial clusters: {cluster_history[0]}")
print(f"Final clusters: {cluster_history[-1]}")
print(f"Maximum clusters: {max(cluster_history)}")
# Check for phase transitions
emergence_gradient = np.gradient(emergence_history)
phase_transitions = np.where(np.abs(emergence_gradient) > 0.5)[0]
if len(phase_transitions) > 0:
print(f"\nPhase transitions detected at steps: "
f"{phase_transitions * 10}")
else:
print("\nNo significant phase transitions detected")
return nebula, emergence_history, cluster_history
def example_data_export():
"""Example of exporting and analyzing data"""
print("=" * 50)
print("Example 7: Data Export and Analysis")
print("=" * 50)
from app import NebulaEmergent
import pandas as pd
# Create and evolve system
nebula = NebulaEmergent(n_neurons=500)
# Collect data over time
data_history = []
for i in range(100):
nebula.evolve()
# Collect comprehensive data
state = {
'time_step': i,
'energy': nebula.metrics['energy'],
'entropy': nebula.metrics['entropy'],
'clusters': nebula.metrics['clusters'],
'quantum_coherence': nebula.metrics['quantum_coherence'],
'emergence_score': nebula.metrics['emergence_score'],
'fps': nebula.metrics['fps'],
'temperature': nebula.temperature,
'mean_activation': np.mean([n.activation for n in nebula.neurons]),
'std_activation': np.std([n.activation for n in nebula.neurons])
}
data_history.append(state)
# Convert to DataFrame
df = pd.DataFrame(data_history)
print("Data collection complete!")
print("\nDataFrame shape:", df.shape)
print("\nDataFrame columns:", df.columns.tolist())
print("\nSummary statistics:")
print(df.describe())
# Export to different formats
print("\nExporting data...")
# CSV export
csv_data = df.to_csv(index=False)
print(f"CSV data size: {len(csv_data)} bytes")
# JSON export
json_data = df.to_json(orient='records', indent=2)
print(f"JSON data size: {len(json_data)} bytes")
# Save sample files
with open('nebula_data.csv', 'w') as f:
f.write(csv_data)
print("Saved: nebula_data.csv")
with open('nebula_data.json', 'w') as f:
f.write(json_data)
print("Saved: nebula_data.json")
return df
def run_all_examples():
"""Run all examples in sequence"""
print("\n" + "π" * 25)
print("NEBULA EMERGENT - Complete Example Suite")
print("π" * 25 + "\n")
examples = [
("Basic Usage", example_basic_usage),
("Pattern Recognition", example_pattern_recognition),
("Optimization", example_optimization_problem),
("Traveling Salesman", example_traveling_salesman),
("Quantum Features", example_quantum_computation),
("Emergent Behavior", example_emergent_behavior),
("Data Export", example_data_export)
]
results = {}
for name, func in examples:
try:
print(f"\n{'='*60}")
print(f"Running: {name}")
print('='*60)
result = func()
results[name] = "β
Success"
print(f"\n{name} completed successfully!")
except Exception as e:
results[name] = f"β Error: {str(e)}"
print(f"\n{name} failed: {e}")
print("\nPress Enter to continue to next example...")
input()
# Summary
print("\n" + "=" * 60)
print("EXAMPLE SUITE SUMMARY")
print("=" * 60)
for name, status in results.items():
print(f"{name}: {status}")
print("\nπ Example suite completed!")
if __name__ == "__main__":
# Run all examples
run_all_examples()
|