-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhibridas.py
More file actions
185 lines (142 loc) · 6.67 KB
/
hibridas.py
File metadata and controls
185 lines (142 loc) · 6.67 KB
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
# hibridas.py (Versión 3.1 - Fix para Dashboard: Retorna resultados)
# ========================================
# SIMULADOR DE CIVILIZACIONES HÍBRIDAS
# Versión 3.1 - 11 nov 2025 - Cristian Querol (Retorna dict para dashboard)
# ========================================
# Docstring: Sim co-evolución humano-IA con emergencias.
import random
import matplotlib.pyplot as plt
import networkx as nx
from datetime import datetime
from typing import List, Dict, Tuple
import argparse
from config import *
from utils import setup_logging, guardar_estado, contar_culturas
plt.rcParams['font.family'] = 'Segoe UI Emoji'
log = setup_logging()
class Agente:
"""Agente con attrs evolutivos."""
def __init__(self, id: int, tipo: str, cultura: int = None):
self.id = id
self.tipo = tipo
self.cultura = cultura if cultura is not None else random.randint(0, 3)
self.energia = ENERGIA_INICIAL
self.mitos: List[str] = []
self.generacion_nacimiento = 0
def reproducir(a1, a2, gen_actual, next_id):
if a1.energia < COSTO_REPRODUCCION or a2.energia < COSTO_REPRODUCCION:
return None
if a1.cultura != a2.cultura:
return None
tipo_hijo = random.choice([a1.tipo, a2.tipo])
hijo = Agente(next_id[0], tipo_hijo, cultura=a1.cultura)
hijo.generacion_nacimiento = gen_actual
a1.energia -= COSTO_REPRODUCCION
a2.energia -= COSTO_REPRODUCCION
mitos_padres = [m for a in (a1, a2) if a.mitos for m in a.mitos]
if mitos_padres:
hijo.mitos.append(random.choice(mitos_padres) + " (heredado)")
next_id[0] += 1
log.info(f"Nacimiento híbrido ID {hijo.id} | Tipo: {tipo_hijo} | Gen: {gen_actual}")
return hijo
def simular(args) -> Dict[str, any]:
log.info("INICIO DE SIMULACIÓN HÍBRIDA")
mitad = args.pob // 2
poblacion = [Agente(i, "humano") for i in range(mitad)] + \
[Agente(i + mitad, "ia") for i in range(mitad)]
G = nx.complete_graph(len(poblacion))
historia = []
next_id = [args.pob]
for gen in range(args.gens):
vivos = [a for a in poblacion if a.energia > 0]
if not vivos:
log.warning("EXTINCIÓN TOTAL")
break
nuevos = []
for _ in range(len(vivos) // 2):
if random.random() < PROB_REPRODUCCION:
a1, a2 = random.sample(vivos, 2)
hijo = reproducir(a1, a2, gen, next_id)
if hijo:
nuevos.append(hijo)
G.add_node(hijo.id)
G.add_edges_from([(a1.id, hijo.id), (a2.id, hijo.id)])
poblacion.extend(nuevos)
for a in vivos[:]:
vecino = random.choice(vivos)
if vecino == a: continue
if random.random() < PROB_CONTAGIO:
a.cultura = vecino.cultura
if a.tipo == "ia" and random.random() < 0.5:
a.mitos.append(random.choice(MITOS_IA))
if vecino.tipo == "ia" and a.tipo == "humano" and vecino.mitos:
a.mitos.append(vecino.mitos[-1] + " (adoptado)")
a.energia -= COSTO_VIDA
if gen % 25 == 0 and gen > 0 and len(vivos) > 8:
from deap import tools
from evolution import toolbox, generar_mito_ia
pop = toolbox.population(n=min(12, len(vivos)//3))
for ind, agente in zip(pop, random.sample(vivos, len(pop))):
ind[:] = [agente.cultura] * 5
offspring = toolbox.select(pop, len(pop))
offspring = list(map(toolbox.clone, offspring))
for child1, child2 in zip(offspring[::2], offspring[1::2]):
if random.random() < 0.5:
toolbox.mate(child1, child2)
del child1.fitness.values
del child2.fitness.values
for mutant in offspring:
if random.random() < 0.2:
toolbox.mutate(mutant)
del mutant.fitness.values
for ind, agente in zip(offspring, random.sample(vivos, len(offspring))):
nueva_cultura = tools.selBest([ind], 1)[0][0]
if nueva_cultura != agente.cultura:
vieja = CULTURAS[agente.cultura]
nueva = CULTURAS[nueva_cultura]
agente.cultura = nueva_cultura
mito = generar_mito_ia(f"cambio de {vieja} a {nueva} por evolución")
agente.mitos.append(mito)
log.info(f"EVOLUCIÓN | {agente.id} → {nueva} | Mito: {mito}")
if gen % 20 == 0 or gen == args.gens - 1:
culturas = contar_culturas(vivos)
historia.append((gen, culturas.get(0,0), culturas.get(1,0),
culturas.get(2,0), culturas.get(3,0)))
guardar_estado(poblacion, gen, historia)
log.info(f"Gen {gen} | Vivos: {len(vivos)} | Total: {len(poblacion)}")
plt.figure(figsize=(14, 9))
plt.suptitle(f"Simulación Híbrida - {datetime.now().strftime('%d/%m %H:%M')}")
plt.subplot(2, 1, 1)
if historia:
gen, col, ind, cre, tec = zip(*historia)
plt.plot(gen, col, 'o-', label=f"Colectivista", color="green")
plt.plot(gen, ind, 's-', label=f"Individualista", color="red")
plt.plot(gen, cre, '^-', label=f"Creativa", color="purple")
plt.plot(gen, tec, 'd-', label=f"Tecnocrática", color="blue")
plt.legend()
plt.ylabel("Población")
plt.grid(alpha=0.3)
plt.title("Evolución Cultural con Reproducción")
plt.subplot(2, 1, 2)
pos = nx.spring_layout(G, k=0.15, iterations=50)
colores = ['orange' if a.tipo == "humano" else 'cyan' for a in poblacion]
nx.draw(G, pos, node_color=colores, node_size=200, alpha=0.7, with_labels=False)
plt.title("Red Social Final (Nodos: Humanos=🟠, IAs=🔵)")
plt.tight_layout()
plt.savefig("outputs/ultimo_grafo.png", dpi=150, bbox_inches='tight')
if not args.dashboard_mode:
plt.show()
log.info("SIMULACIÓN FINALIZADA - Gráfico y JSON guardados")
return {
"G": G,
"historia": historia,
"poblacion": poblacion,
"CULTURAS": CULTURAS
}
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Simulador de Civilizaciones Híbridas")
parser.add_argument("--gens", type=int, default=GENERACIONES, help="Generaciones")
parser.add_argument("--pob", type=int, default=POBLACION_INICIAL, help="Población inicial")
parser.add_argument("--dashboard_mode", action="store_true", help="Modo para dashboard (no show plt)")
args = parser.parse_args()
simular(args)