Spaces:
Sleeping
Sleeping
""" | |
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() | |