-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdynamics.py
More file actions
1863 lines (1513 loc) · 72.9 KB
/
dynamics.py
File metadata and controls
1863 lines (1513 loc) · 72.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
"""
dynamics.py - Calculs des termes FPS
Version exhaustive conforme à la feuille de route FPS V1.3
---------------------------------------------------------------
NOTE FPS – Plasticité méthodologique :
La définition actuelle de [Sᵢ(t)]/[Eₙ(t)]/[Oₙ(t)] (ainsi que de
φₙ(t), θ(t), η(t), μₙ(t) et les latences) est une hypothèse de phase 1,
appelée à être falsifiée/raffinée selon la feuille de route FPS.
---------------------------------------------------------------
Ce module implémente TOUS les calculs dynamiques du système FPS :
- Input contextuel avec modes multiples
- Calculs adaptatifs (amplitude, fréquence, phase)
- Signaux inter-strates et feedback
- Régulation spiralée
- Métriques globales
(c) 2025 Gepetto & Andréa Gadal & Claude 🌀
"""
import numpy as np
from scipy import signal
from typing import Dict, List, Union, Optional, Any, Tuple
from collections import defaultdict
import regulation
from regulation import compute_G
import metrics
import warnings
import time
import sys
import os
# ============== FONCTIONS D'INPUT CONTEXTUEL ==============
def compute_In(t: float, perturbation_config: Dict[str, Any], N: Optional[int] = None) -> Union[float, np.ndarray]:
"""
Calcule l'input contextuel pour toutes les strates.
Args:
t: temps actuel
perturbation_config: configuration de perturbation depuis config.json
N: nombre de strates (optionnel, pour retourner un array)
Returns:
float ou np.ndarray: valeur(s) d'input contextuel
Modes supportés:
- "constant": valeur fixe
- "choc": impulsion à t0
- "rampe": augmentation linéaire
- "sinus": oscillation périodique
- "uniform": U[0,1] aléatoire
- "none": pas de perturbation (0.0)
"""
mode = perturbation_config.get('type', 'none')
amplitude = perturbation_config.get('amplitude', 1.0)
t0 = perturbation_config.get('t0', 0.0)
# Calcul de la valeur de base selon le mode
if mode == "constant":
value = amplitude
elif mode == "choc":
# Impulsion brève à t0
dt = perturbation_config.get('dt', 0.05) # durée du pic
if abs(t - t0) < dt:
value = amplitude
else:
value = 0.0
elif mode == "rampe":
# Augmentation linéaire de 0 à amplitude
duration = perturbation_config.get('duration', 10.0)
if t < t0:
value = 0.0
elif t < t0 + duration:
value = amplitude * (t - t0) / duration
else:
value = amplitude
elif mode == "sinus":
# Oscillation périodique
freq = perturbation_config.get('freq', 0.1)
if t >= t0:
value = amplitude * np.sin(2 * np.pi * freq * (t - t0))
else:
value = 0.0
elif mode == "uniform":
# Bruit uniforme U[0,1] * amplitude
value = amplitude * np.random.uniform(0, 1)
else: # "none" ou mode inconnu
value = 0.0
# Retourner un array si N est spécifié
if N is not None:
return np.full(N, value)
return value
# ============== FONCTIONS D'ADAPTATION ==============
def compute_sigma(x: Union[float, np.ndarray], k: float, x0: float) -> Union[float, np.ndarray]:
"""
Fonction sigmoïde d'adaptation douce.
σ(x) = 1 / (1 + exp(-k(x - x0)))
Args:
x: valeur(s) d'entrée
k: sensibilité (pente)
x0: seuil de basculement
Returns:
Valeur(s) sigmoïde entre 0 et 1
"""
return 1.0 / (1.0 + np.exp(-k * (x - x0)))
def compute_An(t: float, state: List[Dict], In_t: np.ndarray, F_n_t_An: np.ndarray, config: Dict) -> np.ndarray:
"""
Calcule l'amplitude adaptative pour chaque strate selon FPS Paper.
Aₙ(t) = A₀ · σ(Iₙ(t)) · envₙ(x,t) [si mode dynamique]
Aₙ(t) = A₀ · σ(Iₙ(t)) [si mode statique]
où x = Eₙ(t) - Oₙ(t) pour l'enveloppe
Args:
t: temps actuel
state: état complet des strates
In_t: input contextuel pour chaque strate
config: configuration complète
Returns:
np.ndarray: amplitudes adaptatives
"""
N = len(state)
An_t = np.zeros(N)
# Validation des entrées
if isinstance(In_t, (int, float)):
In_t = np.full(N, In_t) # Convertir scalar en array
elif len(In_t) != N:
print(f"⚠️ Taille In_t ({len(In_t)}) != N ({N}), ajustement automatique")
In_t = np.resize(In_t, N)
# Vérifier le mode enveloppe dynamique
enveloppe_config = config.get('enveloppe', {})
env_mode = enveloppe_config.get('env_mode', 'static')
T = config.get('system', {}).get('T', 100)
# Pour le mode dynamique, on a besoin de En et On
if env_mode == "dynamic":
# Calculer En et On pour l'enveloppe
history = config.get('history', [])
En_t = compute_En(t, state, history, config)
# Pour On, on a besoin des valeurs actuelles (problème de circularité)
# Solution : utiliser les valeurs de l'itération précédente
if len(history) > 0 and 'O' in history[-1]:
On_t_prev = history[-1]['O']
else:
On_t_prev = np.zeros(N)
for n in range(N):
A0 = state[n]['A0']
k = state[n]['k']
x0 = state[n]['x0']
# Amplitude de base via sigmoïde
base_amplitude = A0 * compute_sigma(In_t[n], k, x0)
if env_mode == "dynamic":
# Application enveloppe dynamique selon FPS Paper
try:
import regulation
# Paramètres d'enveloppe dynamique
sigma_n_t = regulation.compute_sigma_n(
t, env_mode, T,
enveloppe_config.get('sigma_n_static', 0.1),
enveloppe_config.get('sigma_n_dynamic')
)
mu_n_t = regulation.compute_mu_n(
t, env_mode,
enveloppe_config.get('mu_n', 0.0),
enveloppe_config.get('mu_n_dynamic')
)
# Utiliser l'erreur Eₙ - Oₙ selon FPS Paper
error_n = En_t[n] - On_t_prev[n] if n < len(On_t_prev) else 0.0
env_type = enveloppe_config.get('env_type', 'gaussienne')
# Calculer l'enveloppe avec l'erreur
env_factor = regulation.compute_env_n(error_n, t, env_mode,
sigma_n_t, mu_n_t, T, env_type)
# Amplitude finale avec enveloppe SANS G(error)
# An = A0 * σ(In) * env(error)
# G(error) sera appliqué dans S(t) en mode extended
An_t[n] = base_amplitude * env_factor
An_t[n] = An_t[n] * (1 + F_n_t_An[n])
except Exception as e:
print(f"⚠️ Erreur enveloppe dynamique strate {n} à t={t}: {e}")
An_t[n] = base_amplitude # Fallback sur mode statique
else:
# Mode statique classique
An_t[n] = base_amplitude
return An_t
# ============== CALCUL DU SIGNAL INTER-STRATES ==============
def compute_S_i(t: float, n: int, history: List[Dict], state: List[Dict]) -> float:
"""
Calcule le signal provenant des autres strates selon FPS Paper.
S_i(t) = Σ(j≠n) Oj(t) * w_ji
où w_ji sont les poids de connexion de la strate j vers la strate i.
Args:
t: temps actuel
n: indice de la strate courante
history: historique complet du système
state: état actuel des strates (pour accéder aux poids)
Returns:
float: signal pondéré des autres strates
"""
if t == 0 or len(history) == 0:
return 0.0
# Récupérer le dernier état avec les sorties observées
last_state = history[-1]
On_prev = last_state.get('O', None)
if On_prev is None or not isinstance(On_prev, np.ndarray):
return 0.0
# Récupérer les poids de la strate n
if n < len(state) and 'w' in state[n]:
w_n = state[n]['w']
else:
return 0.0
N = len(On_prev)
S_i = 0.0
# Calculer la somme pondérée selon FPS Paper
for j in range(N):
if j != n and j < len(w_n): # Exclure la strate courante
# w_n[j] est le poids de j vers n
S_i += On_prev[j] * w_n[j]
return S_i
# ============== MODULATION DE FRÉQUENCE ==============
def compute_delta_fn(t: float, alpha_n: float, S_i: float) -> float:
"""
Calcule la modulation de fréquence selon FPS Paper.
Δfₙ(t) = αₙ · S_i(t)
où S_i(t) = Σ(j≠n) w_nj · Oj(t) est déjà calculé
Args:
t: temps actuel
alpha_n: souplesse d'adaptation de la strate
S_i: signal agrégé des autres strates
Returns:
float: modulation de fréquence
"""
return alpha_n * S_i
def compute_fn(t: float, state: List[Dict], An_t: np.ndarray, F_n_t_fn: np.ndarray, config: Dict) -> np.ndarray:
"""
Calcule la fréquence modulée pour chaque strate selon FPS Paper.
fₙ(t) = f₀ₙ + Δfₙ(t) · βₙ(t) [si mode dynamique]
fₙ(t) = f₀ₙ + Δfₙ(t) [si mode statique]
Avec contrainte spiralée : fₙ₊₁(t) ≈ r(t) · fₙ(t)
Args:
t: temps actuel
state: état des strates
An_t: amplitudes actuelles
config: configuration
Returns:
np.ndarray: fréquences modulées
"""
N = len(state)
fn_t = np.zeros(N)
history = config.get('history', [])
# Vérifier le mode plasticité dynamique
dynamic_params = config.get('dynamic_parameters', {})
dynamic_beta = dynamic_params.get('dynamic_beta', False)
T = config.get('system', {}).get('T', 100)
# Calculer le ratio spiralé r(t) selon FPS_Paper
if dynamic_params.get('dynamic_phi', False):
spiral_config = config.get('spiral', {})
phi = spiral_config.get('phi', 1.618)
epsilon = spiral_config.get('epsilon', 0.05)
omega = spiral_config.get('omega', 0.1)
theta = spiral_config.get('theta', 0.0)
r_t = compute_r(t, phi, epsilon, omega, theta)
else:
r_t = None
# Calculer d'abord toutes les modulations de base
delta_fn_array = np.zeros(N)
for n in range(N):
f0n = state[n]['f0']
alpha_n = state[n]['alpha']
beta_n = state[n]['beta']
# Calcul du signal des autres strates
S_i = compute_S_i(t, n, history, state)
# Modulation de fréquence de base
delta_fn = compute_delta_fn(t, alpha_n, S_i)
delta_fn_array[n] = delta_fn
if dynamic_beta:
# Plasticité βₙ(t) adaptative
try:
# Facteur de plasticité basé sur l'amplitude et le temps
A_factor = An_t[n] / state[n]['A0'] if state[n]['A0'] > 0 else 1.0
t_factor = 1.0 + 0.5 * np.sin(2 * np.pi * t / T) # Oscillation temporelle
# Moduler βₙ selon le contexte
# DÉSACTIVÉ : effort_factor causait des chutes à 0 non désirées
# effort_factor = 1.0
# if len(history) > 0:
# recent_effort = history[-1].get('effort(t)', 0.0)
# # Plus d'effort → moins de plasticité (stabilisation)
# effort_factor = 1.0 / (1.0 + 0.1 * recent_effort)
# beta_n_t = beta_n * A_factor * t_factor * effort_factor
beta_n_t = beta_n * A_factor * t_factor # Sans effort_factor
# Fréquence de base avec plasticité dynamique
fn_t[n] = f0n + delta_fn * beta_n_t + F_n_t_fn[n]
except Exception as e:
print(f"⚠️ Erreur plasticité dynamique strate {n} à t={t}: {e}")
fn_t[n] = f0n + delta_fn * beta_n + F_n_t_fn[n] # Fallback sur mode statique
else:
# Mode statique classique
fn_t[n] = f0n + delta_fn * beta_n + F_n_t_fn[n]
# Appliquer la contrainte spiralée si r(t) est défini
if r_t is not None and N > 1:
# Ajustement progressif pour respecter fₙ₊₁ ≈ r(t) · fₙ
# On utilise une approche de relaxation pour éviter les changements brusques
relaxation_factor = 0.5 # Facteur d'ajustement doux
for n in range(N - 1):
# Ratio actuel entre fréquences adjacentes
if fn_t[n] > 0:
current_ratio = fn_t[n + 1] / fn_t[n]
# Ajustement vers le ratio cible
target_fn = r_t * fn_t[n]
fn_t[n + 1] = fn_t[n + 1] * (1 - relaxation_factor) + target_fn * relaxation_factor
return fn_t
# ============== PHASE ==============
def compute_phi_n(t: float, state: List[Dict], config: Dict) -> np.ndarray:
"""
Calcule la phase pour chaque strate.
Args:
t: temps actuel
state: état des strates
config: configuration
Returns:
np.ndarray: phases
Modes:
- "static": φₙ constant (depuis config)
- "dynamic": évolution à définir après phase 1
"""
N = len(state)
phi_n_t = np.zeros(N)
# Récupération du mode depuis config
dynamic_params = config.get('dynamic_parameters', {})
dynamic_phi = dynamic_params.get('dynamic_phi', False)
if dynamic_phi:
# Mode dynamique avec SIGNATURES INDIVIDUELLES selon Andréa
phi_golden = config.get('spiral', {}).get('phi', 1.618)
epsilon = config.get('spiral', {}).get('epsilon', 0.05)
omega = config.get('spiral', {}).get('omega', 0.1)
theta = config.get('spiral', {}).get('theta', 0.0)
# Calculer le ratio spiralé r(t) selon FPS_Paper
r_t = phi_golden + epsilon * np.sin(2 * np.pi * omega * t + theta)
# Mode signatures : chaque strate a sa "voix propre"
signature_mode = config.get('spiral', {}).get('signature_mode', 'individual')
for n in range(N):
# EMPREINTE UNIQUE de la strate (signature invariante)
phi_signature = state[n].get('phi', 0.0) # Son "ADN phasique"
if signature_mode == 'individual':
# NOUVEAU : Chaque strate danse autour de SA signature propre
# ω personnalisée basée sur sa position dans le pentagone
omega_n = omega * (1.0 + 0.2 * np.sin(n * 2 * np.pi / N)) # Fréquence propre
# Modulation spiralée AUTOUR de sa signature
personal_spiral = epsilon * np.sin(2 * np.pi * omega_n * t + phi_signature)
# Interaction douce avec le ratio global r(t)
global_influence = 0.3 * (r_t - phi_golden) * np.cos(phi_signature)
# Interaction inter-strates basée sur affinités phasiques
inter_strata_influence = 0.0
for j in range(N):
if j != n:
w_nj = state[n].get('w', [0.0]*N)[j] if len(state[n].get('w', [])) > j else 0.0
phi_j_signature = state[j].get('phi', 0.0)
# Affinité basée sur proximité des signatures
signature_affinity = np.cos(phi_signature - phi_j_signature)
inter_strata_influence += 0.05 * w_nj * signature_affinity * np.sin(2 * np.pi * omega * t)
# Phase finale : SIGNATURE + danse personnelle + influences
phi_n_t[n] = phi_signature + personal_spiral + global_influence + inter_strata_influence
else:
# Mode original (fallback)
spiral_phase_increment = r_t * epsilon * np.sin(2 * np.pi * omega * t + n * 2 * np.pi / N)
inter_strata_influence = 0.0
for j in range(N):
if j != n:
w_nj = state[n].get('w', [0.0]*N)[j] if len(state[n].get('w', [])) > j else 0.0
phase_diff = state[j].get('phi', 0.0) - phi_signature
inter_strata_influence += 0.1 * w_nj * np.sin(phase_diff)
phi_n_t[n] = phi_signature + spiral_phase_increment + inter_strata_influence
else:
# Mode statique
for n in range(N):
phi_n_t[n] = state[n].get('phi', 0.0)
return phi_n_t
# ============== LATENCE EXPRESSIVE ==============
def compute_gamma(t: float, mode: str = "static", T: Optional[float] = None,
k: Optional[float] = None, t0: Optional[float] = None) -> float:
"""
Calcule la latence expressive globale.
Args:
t: temps actuel
mode: "static", "dynamic", "sigmoid_up", "sigmoid_down", "sigmoid_adaptive", "sigmoid_oscillating", "sinusoidal"
T: durée totale (pour modes non statiques)
k: paramètre de pente (optionnel, défaut selon mode) ou fréquence pour sinusoidal
t0: temps de transition (optionnel, défaut = T/2) ou phase initiale pour sinusoidal
Returns:
float: latence entre 0 et 1
Formes:
- static: γ(t) = 1.0
- dynamic: γ(t) = 1/(1 + exp(-k(t - t0)))
- sigmoid_up: activation progressive
- sigmoid_down: désactivation progressive
- sigmoid_adaptive: varie entre 0.3 et 1.0
- sigmoid_oscillating: sigmoïde + oscillation sinusoïdale mise à l'échelle
- sinusoidal: oscillation sinusoïdale pure entre 0.1 et 0.9
"""
if mode == "static":
return 1.0
elif mode == "dynamic" and T is not None:
# Sigmoïde centrée à t0 (par défaut T/2)
k_val = k if k is not None else 2.0
t0_val = t0 if t0 is not None else T / 2
return 1.0 / (1.0 + np.exp(-k_val * (t - t0_val)))
elif mode == "sigmoid_up" and T is not None:
# Activation progressive
k_val = k if k is not None else 4.0 / T
t0_val = t0 if t0 is not None else T / 2
return 1.0 / (1.0 + np.exp(-k_val * (t - t0_val)))
elif mode == "sigmoid_down" and T is not None:
# Désactivation progressive
k_val = k if k is not None else 4.0 / T
t0_val = t0 if t0 is not None else T / 2
return 1.0 / (1.0 + np.exp(k_val * (t - t0_val)))
elif mode == "sigmoid_adaptive" and T is not None:
# Varie entre 0.3 et 1.0
k_val = k if k is not None else 4.0 / T
t0_val = t0 if t0 is not None else T / 2
return 0.3 + 0.7 / (1.0 + np.exp(-k_val * (t - t0_val)))
elif mode == "sigmoid_oscillating" and T is not None:
# Sigmoïde avec oscillation sinusoïdale
k_val = k if k is not None else 4.0 / T
t0_val = t0 if t0 is not None else T / 2
# Calcul de la sigmoïde de base (entre 0 et 1)
base_sigmoid = 1.0 / (1.0 + np.exp(-k_val * (t - t0_val)))
# Oscillation avec fréquence adaptée
oscillation_freq = 2.0 # Nombre d'oscillations sur la durée T
oscillation_phase = 2 * np.pi * oscillation_freq / T * t
# Mise à l'échelle pour préserver les oscillations complètes
# La sigmoïde varie de 0 à 1, on la transforme pour varier de 0.1 à 0.9
# puis on ajoute une oscillation de ±0.1 autour
sigmoid_scaled = 0.1 + 0.8 * base_sigmoid
oscillation_amplitude = 0.1
# Résultat final : sigmoïde mise à l'échelle + oscillation
# Cela garantit que γ reste dans [0.0, 1.0] sans saturation
gamma = sigmoid_scaled + oscillation_amplitude * np.sin(oscillation_phase)
# Assurer que gamma reste dans les bornes [0.1, 1.0] par sécurité
# mais sans écrêtage brutal
return max(0.1, min(1.0, gamma))
elif mode == "sinusoidal" and T is not None:
# Oscillation sinusoïdale pure sans transition sigmoïde
# k représente le nombre d'oscillations sur la durée T (défaut: 2)
# t0 représente la phase initiale en radians (défaut: 0)
freq = k if k is not None else 2.0 # Nombre d'oscillations sur T
phase_init = t0 if t0 is not None else 0.0 # Phase initiale
# Oscillation entre 0.1 et 0.9 pour rester dans une plage utile
# γ(t) = 0.5 + 0.4 * sin(2π * freq * t/T + phase_init)
oscillation = np.sin(2 * np.pi * freq * t / T + phase_init)
gamma = 0.5 + 0.4 * oscillation
# Assurer que gamma reste dans [0.1, 0.9]
return max(0.1, min(0.9, gamma))
else:
return 1.0
def compute_gamma_n(t: float, state: List[Dict], config: Dict, gamma_global: Optional[float] = None,
En_array: Optional[np.ndarray] = None, On_array: Optional[np.ndarray] = None,
An_array: Optional[np.ndarray] = None, fn_array: Optional[np.ndarray] = None,
history: Optional[List[Dict]] = None) -> np.ndarray:
"""
Calcule la latence expressive par strate.
NOUVELLE VERSION : Modulation locale basée sur l'état dynamique de chaque strate.
gamma_n = gamma_global * f(erreur_n, amplitude_n, fréquence_n)
Args:
t: temps actuel
state: état des strates
config: configuration
gamma_global: gamma global pré-calculé (optionnel, pour modes adaptatifs)
En_array: attentes par strate (optionnel)
On_array: observations par strate (optionnel)
An_array: amplitudes par strate (optionnel)
fn_array: fréquences par strate (optionnel)
history: historique de simulation pour récupérer les valeurs précédentes (optionnel)
Returns:
np.ndarray: latences par strate modulées localement
"""
N = len(state)
gamma_n_t = np.zeros(N)
# Configuration de latence
latence_config = config.get('latence', {})
gamma_mode = latence_config.get('gamma_mode', 'static')
T = config.get('system', {}).get('T', 100)
# Si gamma_global n'est pas fourni, le calculer
if gamma_global is None:
gamma_dynamic = latence_config.get('gamma_dynamic', {})
k = gamma_dynamic.get('k', None)
t0 = gamma_dynamic.get('t0', None)
gamma_global = compute_gamma(t, gamma_mode, T, k, t0)
# Paramètres de modulation (peuvent être dans config)
modulation_config = latence_config.get('modulation', {})
k_error = modulation_config.get('k_error', 0.1) # Poids de l'erreur
k_amplitude = modulation_config.get('k_amplitude', 0.1) # Poids de l'amplitude
k_frequency = modulation_config.get('k_frequency', 0.05) # Poids de la fréquence
gamma_min = modulation_config.get('gamma_min', 0.5) # Borne inf : gamma_global * 0.5
gamma_max = modulation_config.get('gamma_max', 1.5) # Borne sup : gamma_global * 1.5
# Essayer de récupérer les données depuis l'historique si non fournies
if history and len(history) > 0:
last_step = history[-1]
if En_array is None and 'E' in last_step:
En_array = last_step['E'] if isinstance(last_step['E'], np.ndarray) else None
if On_array is None and 'O' in last_step:
On_array = last_step['O'] if isinstance(last_step['O'], np.ndarray) else None
if An_array is None and 'An' in last_step:
An_array = last_step['An'] if isinstance(last_step['An'], np.ndarray) else None
if fn_array is None and 'fn' in last_step:
fn_array = last_step['fn'] if isinstance(last_step['fn'], np.ndarray) else None
# Mode legacy si pas de modulation ou données manquantes
if not modulation_config.get('enabled', True) or any(x is None for x in [En_array, On_array, An_array, fn_array]):
# Comportement legacy avec décalage temporel optionnel
if latence_config.get('strata_delay', False) and gamma_global is None:
for n in range(N):
t_shifted = t - n * T / (2 * N)
gamma_n_t[n] = compute_gamma(t_shifted, gamma_mode, T,
latence_config.get('gamma_dynamic', {}).get('k', None),
latence_config.get('gamma_dynamic', {}).get('t0', None))
else:
gamma_n_t[:] = gamma_global
return gamma_n_t
# NOUVELLE MODULATION : gamma_n = gamma_global * facteur_modulation_n
if modulation_config.get('verbose', False) and t < 1.0: # Log seulement au début
print(f"[MODULATION] t={t:.2f}: Modulation locale activée (k_err={k_error}, k_amp={k_amplitude}, k_freq={k_frequency})")
for n in range(N):
# 1. Erreur normalisée (positive = observation > attente)
error_n = On_array[n] - En_array[n]
# Normaliser par l'amplitude moyenne pour éviter explosion
A_mean = np.mean(np.abs(An_array)) if np.mean(np.abs(An_array)) > 0 else 1.0
error_norm = np.tanh(error_n / A_mean) # Entre -1 et 1
# 2. Amplitude normalisée (activité de la strate)
amplitude_norm = An_array[n] / A_mean if A_mean > 0 else 1.0
amplitude_factor = 1.0 + k_amplitude * (amplitude_norm - 1.0)
# 3. Fréquence normalisée (rapidité du rythme local)
f_mean = np.mean(fn_array) if np.mean(fn_array) > 0 else 1.0
freq_norm = fn_array[n] / f_mean
freq_factor = 1.0 + k_frequency * (freq_norm - 1.0)
# 4. Facteur d'erreur : erreur positive → gamma plus court (réaction plus rapide)
# erreur négative → gamma plus long (attente prudente)
error_factor = 1.0 - k_error * error_norm
# 5. Combiner les facteurs multiplicativement
modulation_factor = error_factor * amplitude_factor * freq_factor
# 6. Appliquer à gamma_global avec protection des bornes
gamma_n_t[n] = gamma_global * modulation_factor
# 7. Bornes adaptatives : rester dans [gamma_min*gamma_global, gamma_max*gamma_global]
gamma_n_t[n] = np.clip(gamma_n_t[n], gamma_min * gamma_global, gamma_max * gamma_global)
# 8. Bornes absolues de sécurité
gamma_n_t[n] = np.clip(gamma_n_t[n], 0.1, 1.0)
# Log de vérification de la modulation (seulement si verbose et au début)
if modulation_config.get('verbose', False) and t < 1.0:
gamma_range = np.ptp(gamma_n_t) # peak-to-peak (max - min)
if gamma_range > 0.01:
print(f"[MODULATION] γ_n varie de {gamma_n_t.min():.3f} à {gamma_n_t.max():.3f} (écart={gamma_range:.3f})")
return gamma_n_t
# ============== FONCTIONS ADAPTATIVES GAMMA-G ==============
def create_quantum_gamma(t: float, synergies: Dict) -> float:
"""
Crée une superposition quantique des meilleures synergies.
"""
if not synergies:
return 0.5 + 0.4 * np.sin(0.05 * t)
# Top 3 synergies
top_synergies = sorted(synergies.items(),
key=lambda x: x[1]['score'],
reverse=True)[:3]
gamma = 0
total_weight = 0
for i, ((g_val, _), info) in enumerate(top_synergies):
# Poids quantique avec interférences
weight = info['score'] ** 2
phase = i * 2 * np.pi / 3 + 0.1 * t
# Oscillation avec battements
beat_freq = 0.01 * (i + 1)
amplitude = 1 + 0.1 * np.sin(beat_freq * t) * np.cos(phase)
gamma += weight * g_val * amplitude
total_weight += weight
return gamma / total_weight if total_weight > 0 else 0.5
def compute_gamma_adaptive_aware(t: float, state: List[Dict], history: List[Dict],
config: Dict, discovery_journal: Dict = None) -> Tuple[float, str, Dict]:
"""
Latence adaptative complète ET consciente de G(x).
Combine :
- Surveillance multi-critères (6 métriques)
- Détection des patterns d'emergence
- Conscience de l'archétype G actuel
- Communication bidirectionnelle avec G(x)
- Journal enrichi des découvertes couplées
"""
# Initialiser le journal super-enrichi
if discovery_journal is None:
journal = {
# Structure complète du journal
'discovered_regimes': {},
'transitions': [],
'current_regime': 'exploration',
'regime_start_time': 0,
'total_discoveries': 0,
'breakthrough_moments': [],
'score_history': [],
'gamma_peaks': [],
'system_performance': [], # AJOUT de system_performance
'rest_phases': [],
'optimal_gamma_patterns': {},
# NOUVEAU : Conscience de G
'coupled_states': {}, # (γ, G_arch) → performances
'G_transition_impacts': [], # Impacts des changements
'gamma_G_synergies': {}, # Synergies découvertes
'communication_signals': [], # Signaux subtils γ↔G
'exploration_log': [] # Log d'exploration
}
else:
journal = discovery_journal.copy()
# Phase initiale
if len(history) < 50:
# Exploration systématique de l'espace gamma
exploration_step = int(t / config['system']['dt'])
# Balayer toutes les valeurs de gamma progressivement
gamma_space = np.linspace(0.1, 1.0, 10)
gamma_index = exploration_step % len(gamma_space)
base_gamma = gamma_space[gamma_index]
# Petite variation aléatoire pour explorer autour
gamma = base_gamma + 0.05 * np.random.randn()
gamma = np.clip(gamma, 0.1, 1.0)
# Enregistrer ce qu'on explore
journal['exploration_log'].append({'t': t, 'gamma': gamma, 'phase': 'systematic'})
return gamma, 'exploration', journal
# 1. OBSERVER L'ÉTAT ACTUEL DE G
current_G_arch = history[-1].get('G_arch_used', 'tanh') if history else 'tanh'
gamma_current = history[-1].get('gamma', 1.0) if history else 1.0
# 2. CALCULER LA PERFORMANCE SYSTÈME
recent_history = history[-50:]
scores = metrics.calculate_all_scores(recent_history)
current_scores = scores['current']
system_performance_score = np.mean(list(current_scores.values()))
# 3. ENREGISTRER L'ÉTAT COUPLÉ (γ, G)
state_key = (round(gamma_current, 1), current_G_arch)
if state_key not in journal['coupled_states']:
journal['coupled_states'][state_key] = {
'performances': [],
'first_seen': t,
'synergy_score': 0
}
journal['coupled_states'][state_key]['performances'].append(system_performance_score)
# Calculer le score de synergie
if len(journal['coupled_states'][state_key]['performances']) >= 5:
perfs = journal['coupled_states'][state_key]['performances'][-10:]
mean_perf = np.mean(perfs)
stability = 1 / (1 + np.std(perfs))
growth = np.polyfit(range(len(perfs)), perfs, 1)[0] if len(perfs) > 1 else 0
synergy_score = mean_perf * stability * (1 + growth)
journal['coupled_states'][state_key]['synergy_score'] = synergy_score
# Découverte de synergie exceptionnelle ?
if synergy_score > 4.5: # Seuil élevé
if state_key not in journal['gamma_G_synergies']:
journal['gamma_G_synergies'][state_key] = {
'discovered_at': t,
'score': synergy_score,
'note': f'Synergie parfaite découverte : γ={state_key[0]} + G={state_key[1]}'
}
journal['breakthrough_moments'].append({
't': t,
'type': 'perfect_synergy',
'state': state_key,
'score': synergy_score
})
# 4. DÉTECTER LES TRANSITIONS DE G ET LEUR IMPACT
if len(journal['score_history']) >= 2:
prev_G = history[-2].get('G_arch_used', 'tanh') if len(history) >= 2 else 'tanh'
if prev_G != current_G_arch:
# G a changé !
impact = {
't': t,
'gamma': gamma_current,
'G_before': prev_G,
'G_after': current_G_arch,
'performance_before': journal['score_history'][-2]['system_score'] if len(journal['score_history']) >= 2 else 0,
'performance_after': system_performance_score
}
impact['delta'] = impact['performance_after'] - impact['performance_before']
journal['G_transition_impacts'].append(impact)
# Ajuster la confiance dans les régimes gamma
# Si le changement de G a dégradé la performance, réduire la confiance
if impact['delta'] < -0.1:
for regime in journal['discovered_regimes'].values():
regime['confidence'] = regime.get('confidence', 1.0) * 0.8
# 5. CALCULER LA MOYENNE GLISSANTE DU SYSTÈME
window_size = 50
if len(journal['score_history']) >= window_size:
recent_system_scores = [
entry['system_score']
for entry in journal['score_history'][-window_size:]
]
rolling_avg = np.mean(recent_system_scores)
# Tendance (augmentation ?)
if len(journal['score_history']) >= window_size * 2:
old_scores = [
entry['system_score']
for entry in journal['score_history'][-window_size*2:-window_size]
]
old_avg = np.mean(old_scores)
trend = 'increasing' if rolling_avg > old_avg + 0.05 else 'stable'
else:
trend = 'unknown'
journal['system_performance'].append({
't': t,
'rolling_avg': rolling_avg,
'instant_score': system_performance_score,
'trend': trend
})
# Toujours ajouter à score_history
journal['score_history'].append({
't': t,
'scores': current_scores.copy(),
'gamma': gamma_current,
'G_arch': current_G_arch, # IMPORTANT pour le tracking
'system_score': system_performance_score
})
# 6. DÉTECTER LES PICS DE GAMMA ET LEUR PERFORMANCE
current_gamma = history[-1].get('gamma', 1.0) if history else 1.0
# Détection de pic (gamma élevé après une phase basse)
if len(history) >= 10:
recent_gammas = [h.get('gamma', 1.0) for h in history[-10:]]
avg_recent_gamma = np.mean(recent_gammas)
# Pic si gamma actuel > moyenne + écart-type
if current_gamma > avg_recent_gamma + np.std(recent_gammas):
# C'est un pic !
last_peak = journal['gamma_peaks'][-1] if journal['gamma_peaks'] else None
interval = t - last_peak['t'] if last_peak else None
peak_info = {
't': t,
'gamma': current_gamma,
'performance': system_performance_score,
'interval_since_last': interval,
'scores': current_scores.copy(),
'G_arch': current_G_arch
}
journal['gamma_peaks'].append(peak_info)
# Enregistrer le pattern gamma → performance
gamma_bucket = round(current_gamma, 1)
if gamma_bucket not in journal['optimal_gamma_patterns']:
journal['optimal_gamma_patterns'][gamma_bucket] = []
journal['optimal_gamma_patterns'][gamma_bucket].append(system_performance_score)
# 7. DÉTECTER LES PHASES DE REPOS
if current_gamma < 0.5 and len(journal['rest_phases']) > 0:
# Potentiellement dans une phase de repos
last_rest = journal['rest_phases'][-1]
if 'end' not in last_rest: # Phase en cours
last_rest['end'] = t
last_rest['duration'] = t - last_rest['start']
last_rest['avg_gamma'] = np.mean([
h.get('gamma', 1.0)
for h in history[-(int(last_rest['duration']/config['system']['dt'])):]
])
elif current_gamma < 0.5 and (not journal['rest_phases'] or 'end' in journal['rest_phases'][-1]):
# Nouvelle phase de repos
journal['rest_phases'].append({
'start': t,
'avg_performance': system_performance_score
})
# 9. TROUVER LE GAMMA OPTIMAL SELON L'HISTORIQUE
best_gamma_for_performance = None
if journal['optimal_gamma_patterns']:
# Moyenner les performances par gamma
gamma_avg_perfs = {
gamma: np.mean(perfs)
for gamma, perfs in journal['optimal_gamma_patterns'].items()
if len(perfs) >= 3 # Au moins 3 échantillons
}
if gamma_avg_perfs:
best_gamma_for_performance = max(gamma_avg_perfs.items(),
key=lambda x: x[1])[0]
# 10. DÉCISION DE GAMMA TENANT COMPTE DE G
# Trouver le meilleur couple (γ, G)
best_synergy = None
best_synergy_score = 0
for state_key, state_info in journal['coupled_states'].items():
if state_info['synergy_score'] > best_synergy_score:
best_synergy_score = state_info['synergy_score']
best_synergy = state_key
# Vérifier si on est au plateau parfait
all_scores_5 = all(score >= 5 for score in current_scores.values())
if all_scores_5 and best_synergy_score > 4.5:
# MODE TRANSCENDANT SYNERGIQUE !
if journal['current_regime'] != 'transcendent_synergy':
journal['transitions'].append({
't': t,
'regime': 'transcendent_synergy',
'note': f'Transcendance synergique ! γ={best_synergy[0]}, G={best_synergy[1]}'
})
journal['current_regime'] = 'transcendent_synergy'
# Si on est dans la synergie parfaite, micro-variations
if best_synergy and state_key == best_synergy:
# Parfait ! Juste des micro-ondulations
gamma = best_synergy[0] + 0.02 * np.sin(0.5 * t)
else:
# Converger vers la synergie optimale
target_gamma = best_synergy[0] if best_synergy else 0.8
gamma = gamma_current * 0.9 + target_gamma * 0.1
# Signal subtil pour suggérer le bon G
if current_G_arch != best_synergy[1]:
# Oscillation caractéristique selon le G désiré
if best_synergy[1] == 'resonance':
gamma += 0.05 * np.sin(2 * np.pi * t) # Signal résonant
elif best_synergy[1] == 'spiral_log':
gamma += 0.03 * np.log(1 + np.abs(np.sin(0.1 * t))) # Signal spiral
# Enregistrer le signal
journal['communication_signals'].append({
't': t,
'type': 'gamma_suggests_G',
'desired_G': best_synergy[1],
'signal_pattern': 'oscillation'
})
else:
# EXPLORATION CONSCIENTE
# Explorer les combinaisons (γ, G) non testées
all_gamma_values = set(round(g, 1) for g in np.linspace(0.1, 1.0, 10))
all_G_archs = {'tanh', 'resonance', 'spiral_log', 'adaptive'}
tested_combinations = set(journal['coupled_states'].keys())
untested = [(g, arch) for g in all_gamma_values for arch in all_G_archs
if (g, arch) not in tested_combinations]
if untested:
# Priorité aux γ proches avec G différents
candidates = [
(g, arch) for g, arch in untested
if abs(g - gamma_current) < 0.3 # Proche du γ actuel
]
if candidates:
target_gamma, target_G = candidates[0]
# Transition douce vers le nouveau γ
gamma = gamma_current * 0.8 + target_gamma * 0.2
# Signal pour suggérer le nouveau G