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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import numpy as np
3
+ import matplotlib.pyplot as plt
4
+ import matplotlib.patches as patches
5
+ from matplotlib.animation import FuncAnimation
6
+ import networkx as nx
7
+ import time
8
+ import random
9
+ import json
10
+ from datetime import datetime
11
+ import threading
12
+ import queue
13
+
14
+ class Neuron:
15
+ def __init__(self, neuron_id, x, y, z=0):
16
+ self.id = neuron_id
17
+ self.x = x
18
+ self.y = y
19
+ self.z = z
20
+ self.activation = random.random() * 0.1
21
+ self.specialization = random.choice([
22
+ "visual", "semantic", "temporal", "spatial", "abstract",
23
+ "linguistic", "logical", "creative", "memory", "learning"
24
+ ])
25
+ self.knowledge = set()
26
+ self.connections = []
27
+ self.quantum_state = [random.random() for _ in range(4)]
28
+ self.learning_rate = 0.1 + random.random() * 0.9
29
+ self.age = 0
30
+ self.experience = 0
31
+ self.fitness = 0
32
+ self.energy = random.random()
33
+ self.bias = random.uniform(-0.1, 0.1)
34
+ self.weights = {}
35
+ self.memory = []
36
+
37
+ class AdvancedNeuralNetwork:
38
+ def __init__(self):
39
+ self.neurons = []
40
+ self.connections = []
41
+ self.metrics = {
42
+ 'loss': 1.0,
43
+ 'efficiency': 0,
44
+ 'convergence': 0,
45
+ 'global_fitness': 0,
46
+ 'learning_rate': 0.1,
47
+ 'knowledge_growth': 0,
48
+ 'reasoning_capability': 0
49
+ }
50
+ self.specializations = [
51
+ "visual", "semantic", "temporal", "spatial", "abstract",
52
+ "linguistic", "logical", "creative", "memory", "learning"
53
+ ]
54
+ self.initialize_network()
55
+
56
+ def initialize_network(self, num_neurons=30):
57
+ """Inicializar la red neuronal con neuronas distribuidas"""
58
+ self.neurons = []
59
+ self.connections = []
60
+
61
+ # Crear neuronas especializadas
62
+ for i in range(num_neurons):
63
+ x = random.uniform(0.1, 0.9)
64
+ y = random.uniform(0.1, 0.9)
65
+ neuron = Neuron(i, x, y)
66
+ self.neurons.append(neuron)
67
+
68
+ # Crear conexiones iniciales
69
+ self.create_initial_connections()
70
+
71
+ def create_initial_connections(self):
72
+ """Crear conexiones iniciales entre neuronas"""
73
+ for i, neuron1 in enumerate(self.neurons):
74
+ for j, neuron2 in enumerate(self.neurons[i+1:], i+1):
75
+ distance = self.calculate_distance(neuron1, neuron2)
76
+ if distance < 0.3 and random.random() < 0.3:
77
+ weight = random.random()
78
+ neuron1.connections.append(j)
79
+ neuron2.connections.append(i)
80
+ neuron1.weights[j] = weight
81
+ neuron2.weights[i] = weight
82
+ self.connections.append({'from': i, 'to': j, 'weight': weight})
83
+
84
+ def calculate_distance(self, neuron1, neuron2):
85
+ """Calcular distancia euclidiana entre dos neuronas"""
86
+ dx = neuron1.x - neuron2.x
87
+ dy = neuron1.y - neuron2.y
88
+ dz = neuron1.z - neuron2.z
89
+ return np.sqrt(dx*dx + dy*dy + dz*dz)
90
+
91
+ def sigmoid(self, x):
92
+ """Función de activación sigmoid"""
93
+ return 1 / (1 + np.exp(-np.clip(x, -500, 500)))
94
+
95
+ def step(self):
96
+ """Ejecutar un paso de la simulación"""
97
+ # Actualizar activaciones
98
+ new_activations = []
99
+
100
+ for j, neuron in enumerate(self.neurons):
101
+ input_sum = 0
102
+ for i, source_neuron in enumerate(self.neurons):
103
+ if i == j:
104
+ continue
105
+ weight = source_neuron.weights.get(j, 0)
106
+ distance = self.calculate_distance(source_neuron, neuron)
107
+ attenuation = 1 / (1 + distance * 5)
108
+ input_sum += source_neuron.activation * weight * attenuation
109
+
110
+ # Influencia cuántica
111
+ quantum_influence = (neuron.quantum_state[0] - 0.5) * 0.8
112
+ new_activation = self.sigmoid(input_sum + neuron.bias + quantum_influence)
113
+ new_activations.append(new_activation)
114
+
115
+ # Aplicar nuevas activaciones con decay
116
+ for i, neuron in enumerate(self.neurons):
117
+ neuron.activation = new_activations[i] * 0.96
118
+ neuron.energy = neuron.activation
119
+ neuron.age += 0.01
120
+ neuron.experience += neuron.activation * 0.1
121
+
122
+ # Actualizar estado cuántico
123
+ for j in range(4):
124
+ neuron.quantum_state[j] = np.sin(time.time() * 0.001 + j) * neuron.activation
125
+
126
+ # Aprendizaje hebbiano
127
+ self.hebbian_learning()
128
+
129
+ # Actualizar métricas
130
+ self.update_metrics()
131
+
132
+ def hebbian_learning(self):
133
+ """Aplicar aprendizaje hebbiano"""
134
+ learning_rate = self.metrics['learning_rate'] * 0.01
135
+
136
+ for neuron in self.neurons:
137
+ for connected_id in neuron.connections:
138
+ if connected_id < len(self.neurons):
139
+ connected_neuron = self.neurons[connected_id]
140
+ delta = learning_rate * neuron.activation * connected_neuron.activation
141
+ current_weight = neuron.weights.get(connected_id, 0)
142
+ neuron.weights[connected_id] = max(0, min(4, current_weight * 0.999 + delta))
143
+
144
+ def update_metrics(self):
145
+ """Actualizar métricas de la red"""
146
+ active_neurons = sum(1 for n in self.neurons if n.activation > 0.1)
147
+ total_knowledge = sum(len(n.knowledge) for n in self.neurons)
148
+ total_energy = sum(n.activation for n in self.neurons)
149
+ max_energy = len(self.neurons)
150
+
151
+ self.metrics['efficiency'] = active_neurons / len(self.neurons) if self.neurons else 0
152
+ self.metrics['knowledge_growth'] = total_knowledge
153
+ self.metrics['global_fitness'] = total_energy / max_energy if max_energy > 0 else 0
154
+ self.metrics['convergence'] = min(self.metrics['efficiency'] * self.metrics['global_fitness'], 1)
155
+ self.metrics['reasoning_capability'] = len([n for n in self.neurons
156
+ if n.specialization == "logical" and n.activation > 0.3]) / 10
157
+
158
+ def add_neuron(self):
159
+ """Añadir una nueva neurona a la red"""
160
+ new_id = len(self.neurons)
161
+ x = random.uniform(0.1, 0.9)
162
+ y = random.uniform(0.1, 0.9)
163
+ new_neuron = Neuron(new_id, x, y)
164
+
165
+ # Conectar con neuronas cercanas
166
+ for existing_neuron in self.neurons:
167
+ distance = self.calculate_distance(new_neuron, existing_neuron)
168
+ if distance < 0.3:
169
+ weight = np.exp(-distance / 0.4) * (0.5 + random.random() * 0.9)
170
+ new_neuron.weights[existing_neuron.id] = weight
171
+ existing_neuron.weights[new_id] = weight
172
+ new_neuron.connections.append(existing_neuron.id)
173
+ existing_neuron.connections.append(new_id)
174
+
175
+ self.neurons.append(new_neuron)
176
+
177
+ def remove_neuron(self):
178
+ """Eliminar una neurona de la red"""
179
+ if len(self.neurons) <= 5:
180
+ return
181
+
182
+ removed = self.neurons.pop()
183
+ # Limpiar conexiones
184
+ for neuron in self.neurons:
185
+ if removed.id in neuron.weights:
186
+ del neuron.weights[removed.id]
187
+ if removed.id in neuron.connections:
188
+ neuron.connections.remove(removed.id)
189
+
190
+ # Actualizar conexiones
191
+ self.connections = [conn for conn in self.connections
192
+ if conn['from'] != removed.id and conn['to'] != removed.id]
193
+
194
+ def teach_concept(self, concept):
195
+ """Enseñar un concepto a la red"""
196
+ learning_neurons = [n for n in self.neurons if n.specialization == "learning"]
197
+ if learning_neurons:
198
+ best_learner = max(learning_neurons, key=lambda n: n.activation)
199
+ best_learner.knowledge.add(concept)
200
+ best_learner.activation += 0.5
201
+ best_learner.memory.append({
202
+ 'pattern': concept,
203
+ 'timestamp': time.time(),
204
+ 'strength': 1.0
205
+ })
206
+
207
+ # Propagar conocimiento
208
+ for connected_id in best_learner.connections:
209
+ if connected_id < len(self.neurons) and random.random() < 0.3:
210
+ connected_neuron = self.neurons[connected_id]
211
+ connected_neuron.knowledge.add(concept)
212
+ connected_neuron.activation += 0.2
213
+
214
+ def reset(self):
215
+ """Reiniciar la red neuronal"""
216
+ self.initialize_network()
217
+
218
+ # Instancia global de la red neuronal
219
+ global_network = AdvancedNeuralNetwork()
220
+
221
+ def create_network_visualization():
222
+ """Crear visualización de la red neuronal"""
223
+ fig, ax = plt.subplots(figsize=(12, 8))
224
+ ax.set_xlim(0, 1)
225
+ ax.set_ylim(0, 1)
226
+ ax.set_aspect('equal')
227
+ ax.set_facecolor('#0f172a')
228
+ fig.patch.set_facecolor('#0f172a')
229
+
230
+ # Colores por especialización
231
+ colors = {
232
+ 'visual': '#ef4444', 'semantic': '#22c55e', 'temporal': '#3b82f6',
233
+ 'spatial': '#eab308', 'abstract': '#a855f7', 'linguistic': '#06b6d4',
234
+ 'logical': '#f97316', 'creative': '#84cc16', 'memory': '#f59e0b',
235
+ 'learning': '#ec4899'
236
+ }
237
+
238
+ # Dibujar conexiones
239
+ for conn in global_network.connections:
240
+ from_neuron = global_network.neurons[conn['from']]
241
+ to_neuron = global_network.neurons[conn['to']]
242
+ ax.plot([from_neuron.x, to_neuron.x], [from_neuron.y, to_neuron.y],
243
+ 'b-', alpha=0.3, linewidth=0.5)
244
+
245
+ # Dibujar neuronas
246
+ for neuron in global_network.neurons:
247
+ size = 50 + neuron.activation * 300
248
+ color = colors.get(neuron.specialization, '#ffffff')
249
+ alpha = 0.3 + neuron.activation * 0.7
250
+
251
+ circle = plt.Circle((neuron.x, neuron.y), 0.02,
252
+ color=color, alpha=alpha, zorder=10)
253
+ ax.add_patch(circle)
254
+
255
+ # Mostrar ID para neuronas muy activas
256
+ if neuron.activation > 0.7:
257
+ ax.text(neuron.x, neuron.y + 0.03, str(neuron.id),
258
+ ha='center', va='bottom', color='white', fontsize=8)
259
+
260
+ # Efecto de conocimiento
261
+ if neuron.knowledge:
262
+ knowledge_circle = plt.Circle((neuron.x, neuron.y), 0.025,
263
+ fill=False, edgecolor='#22c55e',
264
+ linewidth=2, alpha=0.6, zorder=11)
265
+ ax.add_patch(knowledge_circle)
266
+
267
+ ax.set_title('Red Neuronal IA Avanzada - Visualización en Tiempo Real',
268
+ color='white', fontsize=16, pad=20)
269
+ ax.set_xlabel('')
270
+ ax.set_ylabel('')
271
+ ax.tick_params(colors='white')
272
+
273
+ # Leyenda
274
+ legend_elements = []
275
+ for spec, color in colors.items():
276
+ legend_elements.append(plt.Line2D([0], [0], marker='o', color='w',
277
+ markerfacecolor=color, markersize=8,
278
+ label=spec.capitalize()))
279
+
280
+ ax.legend(handles=legend_elements, loc='upper left', bbox_to_anchor=(1, 1),
281
+ facecolor='#1e293b', edgecolor='#475569', labelcolor='white')
282
+
283
+ plt.tight_layout()
284
+ return fig
285
+
286
+ def step_simulation():
287
+ """Ejecutar un paso de la simulación"""
288
+ global_network.step()
289
+ return create_network_visualization(), get_metrics_display()
290
+
291
+ def get_metrics_display():
292
+ """Obtener display de métricas"""
293
+ metrics = global_network.metrics
294
+ return f"""
295
+ ## 📊 Métricas de la Red Neuronal
296
+
297
+ - **Eficiencia**: {metrics['efficiency']:.1%}
298
+ - **Convergencia**: {metrics['convergence']:.1%}
299
+ - **Fitness Global**: {metrics['global_fitness']:.1%}
300
+ - **Neuronas**: {len(global_network.neurons)}
301
+ - **Conexiones**: {len(global_network.connections)}
302
+ - **Conocimiento Total**: {metrics['knowledge_growth']}
303
+ - **Capacidad de Razonamiento**: {metrics['reasoning_capability']:.1%}
304
+ """
305
+
306
+ def teach_concept_to_network(concept):
307
+ """Enseñar concepto a la red"""
308
+ if concept.strip():
309
+ global_network.teach_concept(concept.strip())
310
+ return (create_network_visualization(),
311
+ get_metrics_display(),
312
+ f"✅ Concepto '{concept}' enseñado exitosamente a la red",
313
+ "")
314
+ return create_network_visualization(), get_metrics_display(), "❌ Por favor ingresa un concepto válido", concept
315
+
316
+ def add_neuron_to_network():
317
+ """Añadir neurona a la red"""
318
+ global_network.add_neuron()
319
+ return create_network_visualization(), get_metrics_display(), "➕ Nueva neurona añadida"
320
+
321
+ def remove_neuron_from_network():
322
+ """Remover neurona de la red"""
323
+ global_network.remove_neuron()
324
+ return create_network_visualization(), get_metrics_display(), "➖ Neurona eliminada"
325
+
326
+ def reset_network():
327
+ """Reiniciar la red"""
328
+ global_network.reset()
329
+ return create_network_visualization(), get_metrics_display(), "🔄 Red neuronal reiniciada"
330
+
331
+ def auto_simulation_steps():
332
+ """Ejecutar múltiples pasos automáticamente"""
333
+ for _ in range(5):
334
+ global_network.step()
335
+ time.sleep(0.1)
336
+ return create_network_visualization(), get_metrics_display()
337
+
338
+ # Crear la interfaz Gradio
339
+ def create_gradio_interface():
340
+ with gr.Blocks(
341
+ theme=gr.themes.Soft(
342
+ primary_hue="blue",
343
+ secondary_hue="slate",
344
+ neutral_hue="slate",
345
+ ).set(
346
+ body_background_fill="#0f172a",
347
+ block_background_fill="#1e293b",
348
+ block_border_color="#475569",
349
+ input_background_fill="#334155",
350
+ button_primary_background_fill="#3b82f6",
351
+ button_primary_text_color="white",
352
+ ),
353
+ css="""
354
+ .gradio-container {
355
+ background: linear-gradient(135deg, #0f172a 0%, #1e3a8a 50%, #0f172a 100%);
356
+ min-height: 100vh;
357
+ }
358
+ .gr-button {
359
+ border-radius: 8px;
360
+ font-weight: 600;
361
+ }
362
+ .gr-panel {
363
+ border-radius: 12px;
364
+ border: 1px solid #475569;
365
+ }
366
+ """,
367
+ title="🧠 NEBULA - Red Neuronal IA Avanzada"
368
+ ) as iface:
369
+
370
+ gr.HTML("""
371
+ <div style="text-align: center; padding: 20px;">
372
+ <h1 style="color: white; font-size: 3rem; margin-bottom: 10px;">
373
+ 🧠 NEBULA - Red Neuronal IA Avanzada ⚡
374
+ </h1>
375
+ <p style="color: #cbd5e1; font-size: 1.2rem;">
376
+ Simulación interactiva con aprendizaje automático y supervisión por IA
377
+ </p>
378
+ <p style="color: #94a3b8; font-size: 1rem; margin-top: 10px;">
379
+ Una demostración avanzada de redes neuronales con especialización funcional y aprendizaje adaptativo
380
+ </p>
381
+ </div>
382
+ """)
383
+
384
+ with gr.Row():
385
+ with gr.Column(scale=2):
386
+ plot_output = gr.Plot(
387
+ value=create_network_visualization(),
388
+ label="🌐 Visualización de Red Neuronal",
389
+ show_label=True
390
+ )
391
+
392
+ with gr.Row():
393
+ step_btn = gr.Button("🔄 Paso Manual", variant="primary")
394
+ auto_btn = gr.Button("⚡ 5 Pasos Auto", variant="secondary")
395
+ reset_btn = gr.Button("🔄 Reiniciar", variant="stop")
396
+
397
+ with gr.Row():
398
+ add_neuron_btn = gr.Button("➕ Añadir Neurona")
399
+ remove_neuron_btn = gr.Button("➖ Remover Neurona")
400
+
401
+ with gr.Column(scale=1):
402
+ metrics_display = gr.Markdown(
403
+ value=get_metrics_display(),
404
+ label="📊 Métricas en Tiempo Real"
405
+ )
406
+
407
+ with gr.Group():
408
+ gr.HTML("<h3 style='color: white; text-align: center;'>📚 Enseñanza Manual</h3>")
409
+ concept_input = gr.Textbox(
410
+ placeholder="Enseña un concepto a la red...",
411
+ label="💡 Concepto",
412
+ lines=2
413
+ )
414
+ teach_btn = gr.Button("🎯 Enseñar Concepto", variant="primary")
415
+ status_output = gr.Textbox(
416
+ label="Estado",
417
+ interactive=False,
418
+ lines=2
419
+ )
420
+
421
+ # Información adicional
422
+ with gr.Row():
423
+ with gr.Column():
424
+ gr.HTML("""
425
+ <div style="background: #1e293b; padding: 20px; border-radius: 12px; margin-top: 20px; border: 1px solid #475569;">
426
+ <h3 style="color: white; margin-bottom: 15px;">🔬 Especializaciones Neuronales</h3>
427
+ <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 10px;">
428
+ <div style="color: #ef4444;">🔴 Visual - Procesamiento visual</div>
429
+ <div style="color: #22c55e;">🟢 Semántica - Significado y conceptos</div>
430
+ <div style="color: #3b82f6;">🔵 Temporal - Secuencias temporales</div>
431
+ <div style="color: #eab308;">🟡 Espacial - Relaciones espaciales</div>
432
+ <div style="color: #a855f7;">🟣 Abstracta - Pensamiento abstracto</div>
433
+ <div style="color: #06b6d4;">🔷 Lingüística - Procesamiento de lenguaje</div>
434
+ <div style="color: #f97316;">🟠 Lógica - Razonamiento lógico</div>
435
+ <div style="color: #84cc16;">🟢 Creativa - Generación creativa</div>
436
+ <div style="color: #f59e0b;">🟨 Memoria - Almacenamiento</div>
437
+ <div style="color: #ec4899;">🟡 Aprendizaje - Adquisición de conocimiento</div>
438
+ </div>
439
+ </div>
440
+ """)
441
+
442
+ # Event handlers
443
+ step_btn.click(
444
+ step_simulation,
445
+ outputs=[plot_output, metrics_display]
446
+ )
447
+
448
+ auto_btn.click(
449
+ auto_simulation_steps,
450
+ outputs=[plot_output, metrics_display]
451
+ )
452
+
453
+ teach_btn.click(
454
+ teach_concept_to_network,
455
+ inputs=[concept_input],
456
+ outputs=[plot_output, metrics_display, status_output, concept_input]
457
+ )
458
+
459
+ concept_input.submit(
460
+ teach_concept_to_network,
461
+ inputs=[concept_input],
462
+ outputs=[plot_output, metrics_display, status_output, concept_input]
463
+ )
464
+
465
+ add_neuron_btn.click(
466
+ add_neuron_to_network,
467
+ outputs=[plot_output, metrics_display, status_output]
468
+ )
469
+
470
+ remove_neuron_btn.click(
471
+ remove_neuron_from_network,
472
+ outputs=[plot_output, metrics_display, status_output]
473
+ )
474
+
475
+ reset_btn.click(
476
+ reset_network,
477
+ outputs=[plot_output, metrics_display, status_output]
478
+ )
479
+
480
+ # Footer
481
+ gr.HTML("""
482
+ <div style="text-align: center; padding: 20px; margin-top: 30px; border-top: 1px solid #475569;">
483
+ <p style="color: #94a3b8;">
484
+ 🚀 Desarrollado por <strong>Agnuxo</strong> |
485
+ 💡 Simulación avanzada de redes neuronales con IA supervisada
486
+ </p>
487
+ <p style="color: #64748b; font-size: 0.9rem;">
488
+ Esta demostración muestra conceptos de neurociencia computacional,
489
+ aprendizaje automático y sistemas adaptativos complejos.
490
+ </p>
491
+ </div>
492
+ """)
493
+
494
+ return iface
495
+
496
+ if __name__ == "__main__":
497
+ iface = create_gradio_interface()
498
+ iface.launch(
499
+ server_name="0.0.0.0",
500
+ server_port=7860,
501
+ share=False
502
+ )