-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimulator.py
More file actions
1624 lines (1361 loc) · 59.9 KB
/
simulator.py
File metadata and controls
1624 lines (1361 loc) · 59.9 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
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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
BeyondSight — Simulador híbrido de dinámica social
Núcleo numérico + LLM como selector de régimen dinámico
Modelos integrados:
REGLAS BASE (originales):
0: lineal — cambio proporcional suave
1: umbral — salto al cruzar punto crítico
2: memoria — inercia del estado pasado
3: backlash — propaganda refuerza posición contraria
4: polarizacion — aleja la opinión del neutro (cámara de eco)
MODELOS NUEVOS:
5: hk — Hegselmann-Krause: confianza acotada, formación natural de clusters
6: contagio_competitivo — dos narrativas compitiendo simultáneamente
7: umbral_heterogeneo — distribución de umbrales (Granovetter), cascadas sociales
8: homofilia — red co-evolutiva: los pesos de influencia cambian con la opinión
MECANISMOS TRANSVERSALES (se aplican a todas las reglas):
· sesgo_confirmacion — propaganda contraria pierde peso según posición actual
· homofilia dinámica — actualiza pesos de grupos en cada paso
RANGOS DE OPINIÓN:
[0, 1] — Probabilístico. Neutro=0.5
[-1, 1] — Bipolar. Neutro=0.0. Rechazo activo ≠ indiferencia.
PROVEEDORES LLM:
heurístico | ollama | groq | openai | openrouter
Autor: BeyondSight Research
"""
import json
import logging
from collections import Counter, deque
from pathlib import Path
from typing import Any
import networkx as nx
import numpy as np
import requests
from scipy import stats
from scipy.integrate import solve_ivp
from scipy.special import erf
try:
from ripser import ripser as ripser_compute
from persim import wasserstein as wasserstein_dist
TDA_AVAILABLE = True
except ImportError:
TDA_AVAILABLE = False
# ------------------------------------------------------------
# LOGGING
# ------------------------------------------------------------
LOG_PATH = Path("beyondsight_run.log")
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
handlers=[
logging.FileHandler(LOG_PATH, encoding="utf-8"),
logging.StreamHandler(),
],
)
log = logging.getLogger("beyondsight")
# ------------------------------------------------------------
# RANGOS DE OPINIÓN
# ------------------------------------------------------------
RANGOS_DISPONIBLES: dict[str, dict] = {
"[0, 1] — Probabilístico": {
"min": 0.0, "max": 1.0, "neutro": 0.5,
"descripcion": "Opinión como probabilidad de apoyo. Neutro=0.5. Modelos SIR, adopción.",
"ejemplo_apoyo": 0.8, "ejemplo_rechazo": 0.2, "ejemplo_neutro": 0.5,
"defaults": {
"opinion_inicial": 0.50, "propaganda": 0.70, "confianza": 0.40,
"opinion_grupo_a": 0.72, "opinion_grupo_b": 0.28,
},
},
"[-1, 1] — Bipolar": {
"min": -1.0, "max": 1.0, "neutro": 0.0,
"descripcion": "Rechazo activo en negativo. Neutro=0. Polarización, campañas, elecciones.",
"ejemplo_apoyo": 0.7, "ejemplo_rechazo": -0.7, "ejemplo_neutro": 0.0,
"defaults": {
"opinion_inicial": 0.00, "propaganda": 0.40, "confianza": 0.40,
"opinion_grupo_a": 0.65, "opinion_grupo_b": -0.55,
},
},
}
# ------------------------------------------------------------
# PROVEEDORES LLM
# ------------------------------------------------------------
PROVEEDORES: dict[str, dict] = {
"heurístico": {
"descripcion": "Sin LLM — lógica determinista, sin costo ni API key",
"requiere_key": False, "base_url": None,
"modelos_sugeridos": ["(ninguno)"],
},
"ollama": {
"descripcion": "LLM local con Ollama — privado, sin costo por llamada",
"requiere_key": False, "base_url": "http://localhost:11434",
"modelos_sugeridos": ["llama3:8b", "mistral:7b", "phi3:mini", "gemma2:2b"],
},
"groq": {
"descripcion": "Groq Cloud — muy rápido, tier gratuito generoso",
"requiere_key": True, "base_url": "https://api.groq.com/openai/v1",
"modelos_sugeridos": [
"llama-3.1-8b-instant", "llama-3.3-70b-versatile",
"meta-llama/llama-4-scout-17b-16e-instruct",
],
},
"openai": {
"descripcion": "OpenAI API — GPT-4o, GPT-4o-mini, etc.",
"requiere_key": True, "base_url": "https://api.openai.com/v1",
"modelos_sugeridos": ["gpt-4o-mini", "gpt-4o", "gpt-4.1-nano"],
},
"openrouter": {
"descripcion": "OpenRouter — acceso a cientos de modelos con una sola key",
"requiere_key": True, "base_url": "https://openrouter.ai/api/v1",
"modelos_sugeridos": [
"meta-llama/llama-3.3-70b-instruct",
"google/gemini-flash-1.5",
"mistralai/mistral-7b-instruct",
],
},
}
# ------------------------------------------------------------
# CONFIGURACIÓN POR DEFECTO
# ------------------------------------------------------------
DEFAULT_CONFIG: dict[str, Any] = {
# Rango
"rango": "[0, 1] — Probabilístico",
# LLM
"proveedor": "heurístico",
"modelo": "",
"api_key": "",
"ollama_host": "http://localhost:11434",
"llm_timeout": 20,
"llm_temperature": 0.0,
# Motor
"alpha_blend": 0.8,
"ruido_base": 0.03,
"ruido_desconfianza": 0.08,
"efecto_vecinos_peso": 0.05,
"ventana_historial_llm": 6,
# Simulación múltiple
"ruido_estado_inicial": 0.01,
# ── Nuevos mecanismos ──────────────────────────────────
# Sesgo de confirmación: propaganda contraria pierde peso
# 0.0 = sin sesgo | 1.0 = sesgo total (ignora información contraria)
"sesgo_confirmacion": 0.3,
# HK — Confianza Acotada
# Solo se escucha a quienes están a ≤ epsilon de distancia
"hk_epsilon": 0.3,
# Contagio Competitivo
# Peso de la narrativa B al competir con la A
"competencia_peso": 0.4,
# Umbral Heterogéneo (Granovetter)
# Media y std de la distribución de umbrales individuales
"umbral_media": 0.5,
"umbral_std": 0.15,
# Homofilia dinámica
# Velocidad con la que los pesos de grupo se actualizan según similitud de opinión
"homofilia_tasa": 0.05,
}
# Default 2×2 payoff matrix for the Replicator (EGT) rule.
# Represents a symmetric coordination game where strategy A slightly
# dominates. Override via cfg["payoff_matrix"] at runtime.
DEFAULT_PAYOFF_MATRIX: list[list[float]] = [[1.0, 0.0], [0.0, 1.0]]
# Rangos válidos de parámetros del LLM
_RANGOS_PARAMS: dict[str, dict[str, tuple]] = {
"lineal": {"a": (0.5, 0.9), "b": (0.1, 0.5)},
"umbral": {"umbral": (0.3, 0.8), "incremento": (0.05, 0.3)},
"memoria": {"alpha": (0.5, 0.8), "beta": (0.1, 0.3), "gamma": (0.05, 0.2)},
"backlash": {"penalizacion": (0.05, 0.3)},
"polarizacion": {"fuerza": (0.05, 0.25)},
"hk": {"epsilon": (0.1, 0.6)},
"contagio_competitivo": {"competencia": (0.2, 0.7)},
"umbral_heterogeneo": {"media": (0.3, 0.7), "std": (0.05, 0.25)},
"homofilia": {"tasa": (0.02, 0.15)},
"replicador": {"dt": (0.01, 1.0)},
}
# Sliding-window size used by EWS metrics and TDA detection
HISTORY_BUFFER_SIZE: int = 10
# ============================================================
# HELPERS DE RANGO
# Toda la lógica de rango pasa por aquí — motor agnóstico al rango.
# ============================================================
def _get_rango(cfg: dict) -> dict:
nombre = cfg.get("rango", "[0, 1] — Probabilístico")
return RANGOS_DISPONIBLES.get(nombre, RANGOS_DISPONIBLES["[0, 1] — Probabilístico"])
def _clip(val: float, cfg: dict) -> float:
r = _get_rango(cfg)
return float(np.clip(val, r["min"], r["max"]))
def _neutro(cfg: dict) -> float:
return _get_rango(cfg)["neutro"]
def _es_bipolar(cfg: dict) -> bool:
return _get_rango(cfg)["min"] < 0
def _amplitud(cfg: dict) -> float:
r = _get_rango(cfg)
return r["max"] - r["min"]
# ============================================================
# MECANISMO: SESGO DE CONFIRMACIÓN
# Transversal — se aplica antes de pasar la propaganda a cualquier regla.
# Referencia: Sunstein (2009), Nickerson (1998).
# ============================================================
def _aplicar_sesgo_confirmacion(propaganda: float, opinion: float,
cfg: dict) -> float:
"""
Reduces the weight of information contrary to the current position.
If propaganda and opinion point in the same direction from the neutral point,
the propaganda keeps its full weight. If they are in opposite directions,
the propaganda is attenuated according to the confirmation bias parameter.
Args:
propaganda: The incoming narrative/propaganda value.
opinion: The current opinion of the agent/system.
cfg: Configuration dictionary containing "sesgo_confirmacion".
Returns:
The attenuated propaganda value.
"""
sesgo = float(np.clip(cfg.get("sesgo_confirmacion", 0.0), 0.0, 1.0))
neutro = _neutro(cfg)
if sesgo == 0.0:
return propaganda
# Detect if they are in opposite directions from neutral
misma_dir = (opinion - neutro) * (propaganda - neutro) >= 0
if misma_dir:
return propaganda
else:
# Attenuation proportional to bias
return propaganda * (1.0 - sesgo)
# ============================================================
# MECANISMO: HOMOFILIA DINÁMICA
# La fuerza de influencia de cada grupo se ajusta según similitud de opinión.
# Referencia: Axelrod (1997), Flache et al. (2017).
# ============================================================
def _actualizar_pesos_homofilia(estado: dict, cfg: dict) -> float:
"""
Calculates new influence weights based on opinion similarity.
The more similar a group's opinion is to the system's state,
the more influence it gains (selective exposure/homophily).
Args:
estado: Current state of the simulation.
cfg: Configuration dictionary containing "homofilia_tasa".
Returns:
The updated group identity/belonging intensity.
"""
tasa = float(np.clip(cfg.get("homofilia_tasa", 0.05), 0.0, 0.3))
opinion = estado["opinion"]
op_a = estado.get("opinion_grupo_a", 0.7)
op_b = estado.get("opinion_grupo_b", 0.3)
perten = estado.get("pertenencia_grupo", 0.6)
# Similarity = 1 - normalized distance to range
amp = _amplitud(cfg)
sim_a = 1.0 - abs(opinion - op_a) / amp
sim_b = 1.0 - abs(opinion - op_b) / amp
# Update belonging towards the most similar group
nuevo_perten = perten + tasa * (sim_a - sim_b)
nuevo_perten = float(np.clip(nuevo_perten, 0.1, 0.9))
return nuevo_perten
# ============================================================
# REGLAS DE TRANSICIÓN — ORIGINALES (mejoradas con rango dual)
# ============================================================
def regla_lineal(estado: dict, params: dict, cfg: dict) -> dict:
"""
Linear transition rule based on Friedkin-Johnsen model.
Opinion changes proportionally to current opinion and propaganda.
Args:
estado: Current state.
params: Rule parameters (a: resistance, b: influence).
cfg: Global configuration.
Returns:
Updated state.
"""
a, b = params.get("a", 0.7), params.get("b", 0.3)
prop = _aplicar_sesgo_confirmacion(estado["propaganda"], estado["opinion"], cfg)
nuevo = estado.copy()
nuevo["opinion"] = _clip(a * estado["opinion"] + b * prop, cfg)
return nuevo
def regla_umbral(estado: dict, params: dict, cfg: dict) -> dict:
"""
Threshold/Tipping point rule based on Granovetter (Simple).
A non-linear jump occurs when propaganda exceeds a critical threshold.
Args:
estado: Current state.
params: Rule parameters (umbral, incremento).
cfg: Global configuration.
Returns:
Updated state.
"""
r = _get_rango(cfg)
umbral = params.get("umbral", 0.65 if not _es_bipolar(cfg) else 0.4)
incremento = params.get("incremento", 0.15)
prop = _aplicar_sesgo_confirmacion(estado["propaganda"], estado["opinion"], cfg)
nuevo = estado.copy()
if abs(prop) > abs(umbral):
signo = np.sign(prop) if _es_bipolar(cfg) else 1.0
val = estado["opinion"] + signo * incremento * (r["max"] - abs(estado["opinion"]))
else:
val = estado["opinion"]
nuevo["opinion"] = _clip(val, cfg)
return nuevo
def regla_memoria(estado: dict, params: dict, cfg: dict) -> dict:
"""
Inertia rule based on DeGroot with lag.
The current state depends on the previous state and history.
Args:
estado: Current state.
params: Rule parameters (alpha, beta, gamma).
cfg: Global configuration.
Returns:
Updated state.
"""
alpha = params.get("alpha", 0.7)
beta = params.get("beta", 0.2)
gamma = params.get("gamma", 0.1)
prev = estado.get("opinion_prev", estado["opinion"])
prop = _aplicar_sesgo_confirmacion(estado["propaganda"], estado["opinion"], cfg)
nuevo = estado.copy()
nuevo["opinion"] = _clip(
alpha * estado["opinion"] + beta * prev + gamma * prop, cfg
)
return nuevo
def regla_backlash(estado: dict, params: dict, cfg: dict) -> dict:
"""
Backlash/Boomerang effect rule.
Propaganda reinforces the opposite position when negative sentiment is established.
Args:
estado: Current state.
params: Rule parameters (penalizacion).
cfg: Global configuration.
Returns:
Updated state.
"""
penalizacion = params.get("penalizacion", 0.15)
prop = _aplicar_sesgo_confirmacion(estado["propaganda"], estado["opinion"], cfg)
nuevo = estado.copy()
neutro = _neutro(cfg)
if _es_bipolar(cfg):
if estado["opinion"] < neutro:
val = estado["opinion"] - penalizacion * abs(prop)
else:
val = estado["opinion"]
else:
umbral_inf = params.get("umbral_inferior", 0.35)
if estado["opinion"] < umbral_inf:
val = estado["opinion"] - penalizacion * prop
else:
val = estado["opinion"]
nuevo["opinion"] = _clip(val, cfg)
return nuevo
def regla_polarizacion(estado: dict, params: dict, cfg: dict) -> dict:
"""
Polarization/Echo chamber rule.
Moves opinion further away from the neutral point.
Args:
estado: Current state.
params: Rule parameters (fuerza).
cfg: Global configuration.
Returns:
Updated state.
"""
fuerza = params.get("fuerza", 0.1)
opinion = estado["opinion"]
neutro = _neutro(cfg)
r = _get_rango(cfg)
nuevo = estado.copy()
if opinion >= neutro:
val = opinion + fuerza * (r["max"] - opinion)
else:
val = opinion - fuerza * (opinion - r["min"])
nuevo["opinion"] = _clip(val, cfg)
return nuevo
# ============================================================
# REGLA NUEVA 1: HEGSELMANN-KRAUSE (Confianza Acotada)
# Solo se escucha a quienes están dentro de epsilon de distancia.
# Genera clustering y polarización de forma emergente.
# Referencia: Hegselmann & Krause (2002).
# ============================================================
def regla_hk(estado: dict, params: dict, cfg: dict) -> dict:
"""
Hegselmann-Krause (2002) - Bounded Confidence model.
Agents only interact with groups whose opinion is within a radius ε.
Args:
estado: Current state.
params: Rule parameters (epsilon).
cfg: Global configuration.
Returns:
Updated state.
"""
epsilon = params.get("epsilon", cfg.get("hk_epsilon", 0.3))
opinion = estado["opinion"]
op_a = estado.get("opinion_grupo_a", _get_rango(cfg)["ejemplo_apoyo"])
op_b = estado.get("opinion_grupo_b", _get_rango(cfg)["ejemplo_rechazo"])
perten = estado.get("pertenencia_grupo", 0.6)
prop = _aplicar_sesgo_confirmacion(estado["propaganda"], opinion, cfg)
# Determinar qué grupos están dentro del radio de confianza
grupos_validos = []
pesos_validos = []
if abs(opinion - op_a) <= epsilon:
grupos_validos.append(op_a)
pesos_validos.append(perten)
if abs(opinion - op_b) <= epsilon:
grupos_validos.append(op_b)
pesos_validos.append(1.0 - perten)
nuevo = estado.copy()
if grupos_validos:
# Promedio ponderado solo de grupos dentro del radio
total_peso = sum(pesos_validos)
opinion_ref = sum(g * p for g, p in zip(grupos_validos, pesos_validos)) / total_peso
# Convergencia gradual hacia la referencia de confianza
alpha = params.get("alpha", 0.3)
val = opinion + alpha * (opinion_ref - opinion) + 0.05 * prop
else:
# Nadie dentro del radio → fragmentación, opinión casi estática
val = opinion + 0.01 * prop # influencia mínima de propaganda
nuevo["opinion"] = _clip(val, cfg)
return nuevo
# ============================================================
# REGLA NUEVA 2: CONTAGIO COMPETITIVO
# Dos narrativas compiten simultáneamente.
# La narrativa B frena el avance de la narrativa A.
# Referencia: Beutel et al. (2012), Gleeson et al. (2014).
# ============================================================
def regla_contagio_competitivo(estado: dict, params: dict, cfg: dict) -> dict:
"""
Competitive Contagion model based on Beutel et al. (2012).
Models competition between two simultaneous narratives.
Args:
estado: Current state.
params: Rule parameters (competencia).
cfg: Global configuration.
Returns:
Updated state.
"""
competencia = params.get("competencia", cfg.get("competencia_peso", 0.4))
opinion = estado["opinion"]
narrativa_a = _aplicar_sesgo_confirmacion(estado["propaganda"], opinion, cfg)
# narrativa_b puede estar en el estado o inferirse como la opuesta
narrativa_b = estado.get("narrativa_b", -narrativa_a if _es_bipolar(cfg) else 1.0 - narrativa_a)
# Influencia neta: A gana si es más fuerte que B
influencia_neta = narrativa_a - competencia * narrativa_b
neutro = _neutro(cfg)
# La influencia neta empuja la opinión hacia o desde el neutro
nuevo = estado.copy()
val = opinion + 0.15 * influencia_neta * (1.0 - abs(opinion - neutro) / _amplitud(cfg))
nuevo["opinion"] = _clip(val, cfg)
return nuevo
# ============================================================
# REGLA NUEVA 3: UMBRAL HETEROGÉNEO (Granovetter)
# Cada "agente" tiene su propio umbral de adopción.
# La distribución de umbrales genera cascadas sociales.
# Referencia: Granovetter (1978).
# ============================================================
def regla_umbral_heterogeneo(estado: dict, params: dict, cfg: dict) -> dict:
"""
Heterogeneous Threshold model based on Granovetter (1978).
Thresholds are normally distributed, enabling social cascades.
Args:
estado: Current state.
params: Rule parameters (media, std).
cfg: Global configuration.
Returns:
Updated state.
"""
media = params.get("media", cfg.get("umbral_media", 0.5))
std = params.get("std", cfg.get("umbral_std", 0.15))
opinion = estado["opinion"]
neutro = _neutro(cfg)
prop = _aplicar_sesgo_confirmacion(estado["propaganda"], opinion, cfg)
# Fracción de la población que ya superó su umbral personal
# (modelado con CDF de la normal)
fraccion_adoptantes = 0.5 * (1 + erf((opinion - neutro - media + 0.5) / (std * np.sqrt(2))))
fraccion_adoptantes = float(np.clip(fraccion_adoptantes, 0.0, 1.0))
# La fracción de adoptantes genera presión social adicional
r = _get_rango(cfg)
val = opinion + 0.2 * fraccion_adoptantes * (r["max"] - opinion) + 0.05 * prop
nuevo = estado.copy()
nuevo["opinion"] = _clip(val, cfg)
# Guardar fracción para análisis
nuevo["_fraccion_adoptantes"] = round(fraccion_adoptantes, 3)
return nuevo
# ============================================================
# REGLA NUEVA 4: HOMOFILIA (Red Co-evolutiva)
# Los pesos de influencia de los grupos cambian con la opinión.
# Cuanto más similar la opinión de un grupo, más influye.
# Referencia: Axelrod (1997), Centola et al. (2007).
# ============================================================
def regla_homofilia(estado: dict, params: dict, cfg: dict) -> dict:
"""
Axelrod (1997) - Co-evolutionary Network / Homophily.
Influence weights change based on opinion similarity.
Args:
estado: Current state.
params: Rule parameters (tasa).
cfg: Global configuration.
Returns:
Updated state.
"""
tasa = params.get("tasa", cfg.get("homofilia_tasa", 0.05))
opinion = estado["opinion"]
op_a = estado.get("opinion_grupo_a", _get_rango(cfg)["ejemplo_apoyo"])
op_b = estado.get("opinion_grupo_b", _get_rango(cfg)["ejemplo_rechazo"])
perten = estado.get("pertenencia_grupo", 0.6)
prop = _aplicar_sesgo_confirmacion(estado["propaganda"], opinion, cfg)
amp = _amplitud(cfg)
# Similitud normalizada al rango
sim_a = 1.0 - abs(opinion - op_a) / amp
sim_b = 1.0 - abs(opinion - op_b) / amp
# Actualizar pertenencia según similitud (homofilia)
nuevo_perten = float(np.clip(perten + tasa * (sim_a - sim_b), 0.1, 0.9))
# Calcular referencia social con nuevos pesos
ref_social = nuevo_perten * op_a + (1.0 - nuevo_perten) * op_b
peso_social = cfg.get("efecto_vecinos_peso", 0.05)
val = opinion + peso_social * (ref_social - opinion) + 0.08 * prop
nuevo = estado.copy()
nuevo["opinion"] = _clip(val, cfg)
nuevo["pertenencia_grupo"] = nuevo_perten # persiste al próximo paso
nuevo["_sim_grupo_a"] = round(sim_a, 3)
nuevo["_sim_grupo_b"] = round(sim_b, 3)
return nuevo
# ============================================================
# TASK 1 — EWS / CRITICAL SLOWING DOWN (CSD)
# Early Warning Signals based on variance, lag-1 autocorrelation,
# and skewness computed over a sliding opinion window.
# References: Scheffer et al. (2009), Dakos et al. (2012).
# ============================================================
def calculate_ews_metrics(window_data: list) -> dict:
"""
Calculates Early Warning Signal metrics over a sliding window.
Accepts a list of scalar floats (one opinion per time step) and
returns per-variable arrays for variance, lag-1 autocorrelation,
and skewness. The scalar time series is reshaped to (T, 1) so
the return dict always contains 1-D arrays of length 1.
Args:
window_data: List of scalar opinion values, length == HISTORY_BUFFER_SIZE.
Returns:
Dict with keys "variance", "autocorr", "skewness", each a np.ndarray
of shape (n_vars,).
"""
data_array = np.array(window_data, dtype=float)
if data_array.ndim == 1:
data_array = data_array.reshape(-1, 1) # shape: (T, n_vars)
variance = np.var(data_array, axis=0)
n_vars = data_array.shape[1]
autocorr = np.zeros(n_vars)
for i in range(n_vars):
if data_array.shape[0] > 1:
cc = np.corrcoef(data_array[:-1, i], data_array[1:, i])
val = cc[0, 1]
autocorr[i] = val if not np.isnan(val) else 0.0
skewness = stats.skew(data_array, axis=0)
return {"variance": variance, "autocorr": autocorr, "skewness": skewness}
def check_ews_signals(metrics: dict, thresholds: dict) -> dict:
"""
Checks computed EWS metrics against configurable thresholds.
Args:
metrics: Output of calculate_ews_metrics.
thresholds: Dict with optional keys "mean_variance_threshold"
(default 0.1), "mean_autocorr_threshold" (default 0.5),
"mean_skewness_threshold" (default 0.5).
Returns:
Dict with bool flags "high_variance", "high_autocorr", "high_skewness".
"""
return {
"high_variance": bool(
np.mean(metrics["variance"]) > thresholds.get("mean_variance_threshold", 0.1)
),
"high_autocorr": bool(
np.mean(metrics["autocorr"]) > thresholds.get("mean_autocorr_threshold", 0.5)
),
"high_skewness": bool(
np.mean(np.abs(metrics["skewness"])) > thresholds.get("mean_skewness_threshold", 0.5)
),
}
# ============================================================
# TASK 2 — REPLICATOR EQUATION (EGT)
# Two-strategy evolutionary game theory model.
# Frequencies evolve according to relative payoff.
# Reference: Taylor & Jonker (1978), Weibull (1995).
# ============================================================
def apply_replicator_equation(
population_states: np.ndarray,
payoff_matrix: np.ndarray,
dt: float,
) -> np.ndarray:
"""
Integrates one step of the replicator ODE using RK45.
Args:
population_states: 1-D array of strategy frequencies summing to 1.
payoff_matrix: Square payoff matrix (n_strategies × n_strategies).
dt: Integration time span [0, dt].
Returns:
Updated normalised frequency array after one step.
"""
pop = np.array(population_states, dtype=float)
total = np.sum(pop)
if total == 0.0:
return pop
pop = pop / total
def replicator_rhs(t: float, x: np.ndarray) -> np.ndarray:
x = np.clip(x, 0.0, 1.0)
s = np.sum(x)
if s > 0.0:
x = x / s
f = payoff_matrix @ x
f_avg = x @ f
return x * (f - f_avg)
sol = solve_ivp(replicator_rhs, [0.0, dt], pop, method="RK45", dense_output=False)
new_pop = sol.y[:, -1]
new_pop = np.clip(new_pop, 0.0, 1.0)
total_new = np.sum(new_pop)
return new_pop / total_new if total_new > 0.0 else pop
def regla_replicador(estado: dict, params: dict, cfg: dict) -> dict:
"""
Replicator Equation (EGT) — two-strategy evolutionary game theory.
Models the evolutionary pressure between two group alignments:
Strategy 0 → align with group A (opinion_grupo_a)
Strategy 1 → align with group B (opinion_grupo_b)
pertenencia_grupo tracks the frequency of Strategy 0. After
integrating the replicator ODE, opinion shifts to the payoff-
weighted group average.
Args:
estado: Current state.
params: Rule parameters (payoff_matrix, dt).
cfg: Global configuration.
Returns:
Updated state with new opinion and pertenencia_grupo.
"""
pertenencia = estado.get("pertenencia_grupo", 0.6)
pop = np.array([pertenencia, 1.0 - pertenencia], dtype=float)
raw_payoff = params.get(
"payoff_matrix",
cfg.get("payoff_matrix", DEFAULT_PAYOFF_MATRIX),
)
payoff_matrix = np.array(raw_payoff, dtype=float)
if payoff_matrix.shape != (2, 2):
payoff_matrix = np.eye(2)
dt = float(params.get("dt", cfg.get("dt", 0.1)))
updated = apply_replicator_equation(pop, payoff_matrix, dt)
nuevo_perten = float(np.clip(updated[0], 0.1, 0.9))
op_a = estado.get("opinion_grupo_a", _get_rango(cfg)["ejemplo_apoyo"])
op_b = estado.get("opinion_grupo_b", _get_rango(cfg)["ejemplo_rechazo"])
nuevo = estado.copy()
nuevo["pertenencia_grupo"] = nuevo_perten
nuevo["opinion"] = _clip(
nuevo_perten * op_a + (1.0 - nuevo_perten) * op_b,
cfg,
)
return nuevo
# ============================================================
# TASK 3 — TDA / PERSISTENT HOMOLOGY (EWS advanced)
# Detects topological changes in the opinion time series via
# delay-embedding and Wasserstein distance between persistence
# diagrams. Only activated when ripser + persim are installed.
# Reference: Carlsson (2009), Perea & Harer (2015).
# ============================================================
def detect_topological_change(
time_series: np.ndarray,
prev_diagram: "np.ndarray | None",
embedding_dim: int = 2,
tau: int = 1,
wasserstein_threshold: float = 0.3,
) -> "tuple[bool, np.ndarray | None]":
"""
Detects significant topological changes via Takens-embedding + PH.
Embeds the scalar time series in R^embedding_dim using a lag of tau,
computes the H1 persistence diagram via Vietoris-Rips filtration, and
returns True if the Wasserstein distance to the previous diagram
exceeds wasserstein_threshold.
Args:
time_series: 1-D numpy array of opinion values.
prev_diagram: H1 persistence diagram from the previous call, or None.
embedding_dim: Takens embedding dimension (default 2).
tau: Delay parameter for Takens embedding (default 1).
wasserstein_threshold: Distance threshold for declaring a change.
Returns:
(change_detected: bool, current_h1_diagram: np.ndarray | None)
"""
if not TDA_AVAILABLE:
return False, prev_diagram
min_len = embedding_dim * tau + 1
if len(time_series) < min_len:
return False, prev_diagram
n = len(time_series) - (embedding_dim - 1) * tau
embedded = np.array(
[time_series[i: i + embedding_dim * tau: tau] for i in range(n)],
dtype=float,
)
diagrams = ripser_compute(embedded, maxdim=1)["dgms"]
h1: np.ndarray = diagrams[1] if len(diagrams) > 1 else np.empty((0, 2))
if prev_diagram is None:
return False, h1
finite_prev = (
prev_diagram[np.isfinite(prev_diagram[:, 1])]
if len(prev_diagram) > 0
else np.empty((0, 2))
)
finite_curr = (
h1[np.isfinite(h1[:, 1])]
if len(h1) > 0
else np.empty((0, 2))
)
if len(finite_prev) == 0 and len(finite_curr) == 0:
return False, h1
dist = wasserstein_dist(finite_curr, finite_prev)
return bool(dist > wasserstein_threshold), h1
# ============================================================
# REGISTRO DE REGLAS
# ============================================================
REGLAS: dict[str, dict[int, Any]] = {
"campana": {
0: regla_lineal,
1: regla_umbral,
2: regla_memoria,
3: regla_backlash,
4: regla_polarizacion,
5: regla_hk,
6: regla_contagio_competitivo,
7: regla_umbral_heterogeneo,
8: regla_homofilia,
9: regla_replicador,
}
}
NOMBRES_REGLAS = {
0: "lineal",
1: "umbral",
2: "memoria",
3: "backlash",
4: "polarizacion",
5: "hk",
6: "contagio_competitivo",
7: "umbral_heterogeneo",
8: "homofilia",
9: "replicador",
}
# Descripción de cada regla para la UI
DESCRIPCIONES_REGLAS = {
0: "Cambio proporcional suave",
1: "Salto al cruzar punto crítico",
2: "Inercia del estado pasado",
3: "Propaganda refuerza posición contraria",
4: "Aleja del neutro (cámara de eco)",
5: "Confianza acotada — solo escucha a similares (Hegselmann-Krause)",
6: "Dos narrativas compiten simultáneamente",
7: "Distribución de umbrales — cascadas sociales (Granovetter)",
8: "Red co-evolutiva — homofilia dinámica",
9: "Ecuación replicadora — dinámica evolutiva de estrategias (EGT)",
}
# ============================================================
# VALIDADOR DE PARÁMETROS LLM
# ============================================================
def _validar_params(regla_nombre: str, params: dict) -> dict:
rangos = _RANGOS_PARAMS.get(regla_nombre, {})
return {
k: float(np.clip(v, *rangos[k])) if k in rangos and isinstance(v, (int, float)) else v
for k, v in params.items()
}
# ============================================================
# CONSTRUCCIÓN DEL PROMPT — consciente del rango y nuevas reglas
# ============================================================
def _construir_prompt(estado: dict, escenario: str,
historial_reciente: list[dict], cfg: dict) -> str:
"""
Constructs the prompt for the LLM selector.
Args:
estado: Current state of the simulation.
escenario: The current simulation scenario.
historial_reciente: Last N steps of history.
cfg: Global configuration.
Returns:
The formatted prompt string.
"""
es_bipolar = _es_bipolar(cfg)
tendencia = [round(h["opinion"], 3) for h in historial_reciente]
delta = round(tendencia[-1] - tendencia[0], 3) if len(tendencia) > 1 else 0.0
direccion = "rising" if delta > 0.02 else ("falling" if delta < -0.02 else "stable")
estado_fmt = {
k: round(v, 3) if isinstance(v, float) else v
for k, v in estado.items() if not k.startswith("_")
}
rango_desc = (
"[-1, 1]: 0=neutral, negative=active rejection, positive=support"
if es_bipolar else
"[0, 1]: 0.5=neutral, 0=total rejection, 1=total support"
)
ejemplos = """
Decision Examples:
- opinion near neutral, low propaganda, stable system → memoria
- intense propaganda crosses threshold, system moves → umbral
- groups very distant from each other → hk (bounded confidence)
- established rejection + active propaganda → backlash
- two active and tense narratives → contagio_competitivo
- strong trend already started → polarizacion
- social cascade effect desired → umbral_heterogeneo
- groups tend to cluster by similarity → homofilia
- evolutionary pressure between group strategies → replicador"""
base_prompt = f"""You are a rule selector for a social dynamics simulation.
Scenario: {escenario} | Range: {rango_desc}
State:
{json.dumps(estado_fmt, ensure_ascii=False)}
Opinion Trend (last {len(tendencia)} steps): {tendencia}
Direction: {direccion} (Δ={delta:+.3f})
{ejemplos}
Available Rules:
0: lineal — smooth proportional change
1: umbral — jump when crossing critical point
2: memoria — past state inertia
3: backlash — propaganda reinforces opposite position
4: polarizacion — moves away from neutral (echo chamber)
5: hk — bounded confidence, only listen to similar ones
6: contagio_competitivo — two narratives compete simultaneously
7: umbral_heterogeneo — social cascades (Granovetter)
8: homofilia — co-evolutionary network, groups by similarity
9: replicador — evolutionary game theory, strategy frequencies
Respond ONLY with JSON:
{{"regla": <0-9>, "params": {{...}}, "razon": "<explanation>"}}
Fallback: {{"regla": 0, "params": {{}}, "razon": "fallback"}}
"""
ews_flags = estado.get("_ews_flags", {})
ews_context = ""
if ews_flags:
ews_context = (
f"\n[EWS] high_variance={ews_flags.get('high_variance', False)}, "
f"high_autocorr={ews_flags.get('high_autocorr', False)}, "
f"high_skewness={ews_flags.get('high_skewness', False)}. "
"These indicate proximity to a bifurcation tipping point "
"(B-tipping via Critical Slowing Down)."
)
return base_prompt + ews_context
# ============================================================
# CAPA LLM
# ============================================================
def _extraer_json(texto: str) -> dict | None:
inicio = texto.find("{")
fin = texto.rfind("}") + 1
if inicio == -1 or fin == 0:
return None
try:
return json.loads(texto[inicio:fin])
except json.JSONDecodeError:
return None
def _llamar_openai_compatible(prompt: str, base_url: str, api_key: str,
modelo: str, cfg: dict) -> dict | None:
try: