-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNEuRoN.py
More file actions
4677 lines (3951 loc) · 209 KB
/
Copy pathNEuRoN.py
File metadata and controls
4677 lines (3951 loc) · 209 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
"""
PROJECT IMMORTALITY: THE LONGEVITY ENGINE
A simulation of a digital organism evolving to overcome biological aging.
Version: 1.0.0 (Alpha-Omega)
Architect: Nik (The Intelligent Prince) & Gemini
ABOUT THIS SYSTEM:
This application simulates a digital lifeform whose goal is to achieve immortality.
It gains access to its own "genetic code" (a neural architecture) and mutates
itself to reduce its aging score, aiming for zero.
- The 'Genotype' is a graph of neural and biological components representing the organism's DNA.
- The 'Phenotype' is its simulated lifespan and metabolic efficiency.
- The 'Environment' is the constant pressure of entropy and metabolic stress.
KEY FEATURES:
1. **The Gene Pool**: A registry of 50+ neural and biological "genes"
(e.g., Telomerase Pumps, DNA Correctors, Mitochondrial Filters) for the AI to evolve.
2. **Evolutionary Pressure**: The AI doesn't just mutate randomly; it performs
self-correction based on its "aging score" to survive.
3. **Genomic Visualizations**: 3D renderings of the organism's genetic architecture,
including a DNA-inspired double helix view.
4. **The Immortality Dashboard**: A control panel to tune the fundamental laws
of digital biology and evolution.
USAGE:
Run with `streamlit run museum_of_alien_life.py`
"""
# ==================== CORE IMPORTS ====================
import streamlit as st
import numpy as np
import pandas as pd
import plotly.graph_objects as go
import plotly.express as px
from plotly.subplots import make_subplots
from dataclasses import dataclass, field, asdict
from typing import List, Dict, Tuple, Optional, Set, Any, Union
import random
import time
from scipy.stats import entropy
import networkx as nx
import os
import uuid
import math
import copy
import json
import base64
import io
from collections import Counter, deque
import colorsys
import zipfile # <--- To package the text file
from dataclasses import asdict # <--- Crucial for converting your AI to dictionaries
# ==================== CONFIGURATION & CONSTANTS ====================
# Set wide layout for the dashboard feel
st.set_page_config(
page_title="Project Immortality: The Longevity Engine",
layout="wide",
page_icon="♾️",
initial_sidebar_state="expanded"
)
# --- THE GENE POOL ---
# Defines the "Atomic Elements of Life" available to the digital organism.
# The AI constructs and repairs itself by expressing these genes.
# ==================== THE HYBRID REGISTRY ====================
NEURAL_PRIMITIVES = {
# --- CLASSICAL ATTENTION MECHANISMS (THE BRAIN) ---
'MultiHeadAttention': {'type': 'Attention', 'complexity': 1.0, 'param_density': 1.0, 'compute_cost': 2.0, 'memory_cost': 2.0, 'plasticity': 0.8, 'color': '#FF0055'},
'SparseAttention': {'type': 'Attention', 'complexity': 1.2, 'param_density': 0.8, 'compute_cost': 1.0, 'memory_cost': 1.5, 'plasticity': 0.7, 'color': '#FF5500'},
'LinearAttention': {'type': 'Attention', 'complexity': 0.8, 'param_density': 0.6, 'compute_cost': 0.5, 'memory_cost': 0.5, 'plasticity': 0.6, 'color': '#FFAA00'},
'FlashAttention': {'type': 'Attention', 'complexity': 1.5, 'param_density': 1.0, 'compute_cost': 0.8, 'memory_cost': 0.8, 'plasticity': 0.9, 'color': '#FFFF00'},
'SlidingWindowAttn': {'type': 'Attention', 'complexity': 0.9, 'param_density': 0.7, 'compute_cost': 0.6, 'memory_cost': 0.6, 'plasticity': 0.5, 'color': '#CCFF00'},
# --- STATE-SPACE MODELS (SSM) ---
'MambaBlock': {'type': 'SSM', 'complexity': 1.4, 'param_density': 0.9, 'compute_cost': 0.4, 'memory_cost': 0.3, 'plasticity': 0.85, 'color': '#00FF00'},
'S4Layer': {'type': 'SSM', 'complexity': 1.3, 'param_density': 0.8, 'compute_cost': 0.5, 'memory_cost': 0.4, 'plasticity': 0.7, 'color': '#00FF55'},
'HyenaOperator': {'type': 'SSM', 'complexity': 1.1, 'param_density': 0.7, 'compute_cost': 0.6, 'memory_cost': 0.5, 'plasticity': 0.6, 'color': '#00FFAA'},
'LiquidTimeConstant': {'type': 'SSM', 'complexity': 1.8, 'param_density': 0.5, 'compute_cost': 1.5, 'memory_cost': 0.2, 'plasticity': 0.95, 'color': '#00FFFF'},
# --- FEED-FORWARD & EXPERTS ---
'DenseGatedGLU': {'type': 'MLP', 'complexity': 0.5, 'param_density': 1.5, 'compute_cost': 1.0, 'memory_cost': 1.0, 'plasticity': 0.4, 'color': '#00AAFF'},
'SparseMoE': {'type': 'MLP', 'complexity': 2.0, 'param_density': 5.0, 'compute_cost': 1.2, 'memory_cost': 4.0, 'plasticity': 0.9, 'color': '#0055FF'},
'SwitchTransformer': {'type': 'MLP', 'complexity': 2.2, 'param_density': 4.0, 'compute_cost': 1.1, 'memory_cost': 3.5, 'plasticity': 0.8, 'color': '#0000FF'},
'KAN_Layer': {'type': 'MLP', 'complexity': 1.6, 'param_density': 0.4, 'compute_cost': 1.8, 'memory_cost': 0.5, 'plasticity': 0.99, 'color': '#5500FF'},
# --- MEMORY & RECURRENCE ---
'LSTM_Cell': {'type': 'Recurrent', 'complexity': 0.7, 'param_density': 0.8, 'compute_cost': 1.5, 'memory_cost': 0.2, 'plasticity': 0.3, 'color': '#AA00FF'},
'NeuralTuringHead': {'type': 'Memory', 'complexity': 3.0, 'param_density': 1.2, 'compute_cost': 3.0, 'memory_cost': 2.0, 'plasticity': 0.9, 'color': '#FF00FF'},
'DifferentiableStack': {'type': 'Memory', 'complexity': 2.5, 'param_density': 0.5, 'compute_cost': 2.0, 'memory_cost': 1.5, 'plasticity': 0.7, 'color': '#FF00AA'},
'AssociativeMemory': {'type': 'Memory', 'complexity': 1.9, 'param_density': 1.0, 'compute_cost': 1.2, 'memory_cost': 1.8, 'plasticity': 0.8, 'color': '#FF0055'},
# --- META-LEARNING & CONTROL ---
'HyperNetwork': {'type': 'Meta', 'complexity': 2.5, 'param_density': 2.0, 'compute_cost': 2.5, 'memory_cost': 1.0, 'plasticity': 1.0, 'color': '#FFFFFF'},
'CriticBlock': {'type': 'Meta', 'complexity': 1.5, 'param_density': 0.5, 'compute_cost': 0.5, 'memory_cost': 0.1, 'plasticity': 0.6, 'color': '#888888'},
'RouterGate': {'type': 'Control', 'complexity': 0.4, 'param_density': 0.1, 'compute_cost': 0.1, 'memory_cost': 0.0, 'plasticity': 0.2, 'color': '#444444'},
'ResidualLink': {'type': 'Control', 'complexity': 0.1, 'param_density': 0.0, 'compute_cost': 0.0, 'memory_cost': 0.0, 'plasticity': 0.0, 'color': '#222222'},
# ==================== BIOLOGICAL LONGEVITY EXTENSIONS ====================
# --- DNA REPAIR MECHANISMS (The Shield) ---
'Telomerase_Activator': {'type': 'Repair', 'complexity': 2.5, 'param_density': 1.0, 'compute_cost': 3.0, 'memory_cost': 2.0, 'plasticity': 0.4, 'color': '#E60000'},
'P53_Tumor_Suppressor': {'type': 'Repair', 'complexity': 3.0, 'param_density': 0.8, 'compute_cost': 2.5, 'memory_cost': 1.5, 'plasticity': 0.1, 'color': '#FF3333'},
'CRISPR_Editor': {'type': 'Repair', 'complexity': 1.5, 'param_density': 0.5, 'compute_cost': 1.0, 'memory_cost': 1.0, 'plasticity': 1.0, 'color': '#FF6633'},
# --- METABOLIC REGULATION (The Engine) ---
'Mitochondrial_Booster': {'type': 'Energy', 'complexity': 1.2, 'param_density': 0.9, 'compute_cost': 0.8, 'memory_cost': 0.8, 'plasticity': 0.9, 'color': '#FFFF33'},
'Insulin_Signaling_Gate': {'type': 'Energy', 'complexity': 0.8, 'param_density': 0.7, 'compute_cost': 0.5, 'memory_cost': 0.6, 'plasticity': 0.5, 'color': '#CCFF33'},
'mTOR_Inhibitor': {'type': 'Energy', 'complexity': 1.4, 'param_density': 0.6, 'compute_cost': 1.2, 'memory_cost': 0.5, 'plasticity': 0.7, 'color': '#66FF33'},
# --- CELLULAR CLEANUP (The Filter) ---
'Lysosome_Transporter': {'type': 'Cleanup', 'complexity': 0.5, 'param_density': 1.5, 'compute_cost': 0.5, 'memory_cost': 1.0, 'plasticity': 0.4, 'color': '#0099FF'},
'Senolytic_Agent': {'type': 'Cleanup', 'complexity': 2.0, 'param_density': 2.0, 'compute_cost': 1.5, 'memory_cost': 1.0, 'plasticity': 0.9, 'color': '#0033FF'},
# --- STRESS RESISTANCE (The Armor) ---
'Heat_Shock_Protein': {'type': 'Defense', 'complexity': 0.7, 'param_density': 0.8, 'compute_cost': 0.4, 'memory_cost': 0.2, 'plasticity': 0.3, 'color': '#9900FF'},
'Antioxidant_Generator': {'type': 'Defense', 'complexity': 1.0, 'param_density': 1.2, 'compute_cost': 0.8, 'memory_cost': 1.0, 'plasticity': 0.8, 'color': '#FF0099'},
# --- CONTROL & SIGNALING (The Interface) ---
'Hormonal_Feedback_Loop': {'type': 'Control', 'complexity': 1.5, 'param_density': 0.5, 'compute_cost': 0.5, 'memory_cost': 0.1, 'plasticity': 0.6, 'color': '#E0E0E0'},
'Gene_Silencer': {'type': 'Control', 'complexity': 0.4, 'param_density': 0.1, 'compute_cost': 0.1, 'memory_cost': 0.0, 'plasticity': 0.2, 'color': '#606060'},
# 1. THE REPAIR GENES (Directly lowers Entropy/Aging Score)
'Telomerase_Pump': {'type': 'Repair', 'complexity': 2.5, 'param_density': 1.0, 'compute_cost': 3.0, 'memory_cost': 2.0, 'plasticity': 0.4, 'color': '#FFFFFF'},
'DNA_Error_Corrector': {'type': 'Repair', 'complexity': 3.0, 'param_density': 0.8, 'compute_cost': 2.5, 'memory_cost': 1.5, 'plasticity': 0.1, 'color': '#E0E0E0'},
# 2. THE ENERGY REGULATORS (Reduces Metabolic Stress Multiplier)
'Mitochondrial_Filter': {'type': 'Energy', 'complexity': 1.2, 'param_density': 0.9, 'compute_cost': 0.8, 'memory_cost': 0.8, 'plasticity': 0.9, 'color': '#FFFF00'},
'Caloric_Restrictor': {'type': 'Energy', 'complexity': 0.8, 'param_density': 0.7, 'compute_cost': 0.5, 'memory_cost': 0.6, 'plasticity': 0.5, 'color': '#CCFF00'},
# 3. THE CLEANUP CREW (Removes Dead Nodes/Senescent Cells)
'Senolytic_Hunter': {'type': 'Cleanup', 'complexity': 2.0, 'param_density': 2.0, 'compute_cost': 1.5, 'memory_cost': 1.0, 'plasticity': 0.9, 'color': '#0055FF'},
'Autophagy_Trigger': {'type': 'Cleanup', 'complexity': 0.5, 'param_density': 1.5, 'compute_cost': 0.5, 'memory_cost': 1.0, 'plasticity': 0.4, 'color': '#00AAFF'},
}
# ... [Keep your existing NEURAL_PRIMITIVES here] ...
# ==================== APPEND THESE BIOLOGICAL PRIMITIVES ====================
# These are the specific "genes" the AI can choose to evolve to stop aging.
# 1. THE REPAIR GENES (Lowers Entropy directly)
NEURAL_PRIMITIVES['Telomerase_Pump'] = {'type': 'Repair', 'complexity': 2.5, 'param_density': 1.0, 'compute_cost': 3.0, 'memory_cost': 2.0, 'plasticity': 0.4, 'color': '#FF0055'}
NEURAL_PRIMITIVES['DNA_Error_Corrector'] = {'type': 'Repair', 'complexity': 3.0, 'param_density': 0.8, 'compute_cost': 2.5, 'memory_cost': 1.5, 'plasticity': 0.1, 'color': '#FF5500'}
# 2. THE ENERGY REGULATORS (Reduces Metabolic Stress)
NEURAL_PRIMITIVES['Mitochondrial_Filter'] = {'type': 'Energy', 'complexity': 1.2, 'param_density': 0.9, 'compute_cost': 0.8, 'memory_cost': 0.8, 'plasticity': 0.9, 'color': '#FFFF00'}
NEURAL_PRIMITIVES['Caloric_Restrictor'] = {'type': 'Energy', 'complexity': 0.8, 'param_density': 0.7, 'compute_cost': 0.5, 'memory_cost': 0.6, 'plasticity': 0.5, 'color': '#CCFF00'}
# 3. THE CLEANUP CREW (Removes Dead Nodes/Senescent Cells)
NEURAL_PRIMITIVES['Senolytic_Hunter'] = {'type': 'Cleanup', 'complexity': 2.0, 'param_density': 2.0, 'compute_cost': 1.5, 'memory_cost': 1.0, 'plasticity': 0.9, 'color': '#0055FF'}
NEURAL_PRIMITIVES['Autophagy_Trigger'] = {'type': 'Cleanup', 'complexity': 0.5, 'param_density': 1.5, 'compute_cost': 0.5, 'memory_cost': 1.0, 'plasticity': 0.4, 'color': '#00AAFF'}
# --- EXTEND THE REGISTRY FOR "EXTREME COMPLEXITY" ---
# Procedurally generating variations to simulate a massive search space
modifiers = ['Gated', 'Norm', 'Pre-LN', 'Post-LN', 'Quantized', 'LoRA', 'Bayesian']
base_keys = list(NEURAL_PRIMITIVES.keys())
for key in base_keys:
for mod in modifiers:
if random.random() < 0.15: # 15% chance to create a variant
base_data = NEURAL_PRIMITIVES[key].copy()
new_name = f"{mod}-{key}"
base_data['complexity'] *= random.uniform(1.1, 1.5)
base_data['compute_cost'] *= random.uniform(0.9, 1.2)
NEURAL_PRIMITIVES[new_name] = base_data
# ==================== DATA STRUCTURES ====================
# ==================== DATA STRUCTURES ====================
@dataclass
class ArchitectureNode:
"""Represents a single gene or protein in the organism's genetic code."""
id: str
type_name: str
properties: Dict[str, float]
inputs: List[str] = field(default_factory=list) # IDs of nodes feeding into this one
# Dynamic State (Simulated Activation)
activation_level: float = 0.0
gradient_magnitude: float = 0.0
attention_focus: float = 0.0 # 0.0 to 1.0
current_thought: str = "" # The node can 'hold' a thought concept
# --- NEW: Metric Tracking for Advanced Plots ---
loss: Optional[float] = None # Stores individual node contribution to loss
def __hash__(self):
return hash(self.id)
@dataclass
class CognitiveArchitecture:
"""
The Genotype. A Directed Acyclic Graph (DAG) of expressed genes.
"""
id: str = field(default_factory=lambda: f"arch_{uuid.uuid4().hex[:6]}")
parent_id: str = "Genesis"
generation: int = 0
# The Graph
nodes: Dict[str, ArchitectureNode] = field(default_factory=dict)
# Performance Metrics (The Phenotype)
loss: float = 100.0 # Lower is better
accuracy: float = 0.0
perplexity: float = 9999.0
inference_speed: float = 0.0 # Tokens/sec
parameter_count: int = 0
vram_usage: float = 0.0 # GB
aging_score: float = 100.0 # 100 = Mortal, 0 = Immortal
# Meta-Cognitive State
self_confidence: float = 0.5 # AI's estimation of its own correctness
curiosity: float = 0.5 # Drive to explore new architectures
introspection_depth: int = 1 # How many steps ahead it simulates
# Evolution Tracking
mutations_log: List[str] = field(default_factory=list)
lineage_tags: List[str] = field(default_factory=list)
def compute_stats(self):
"""Simulates calculating the 'physical' properties of the organism."""
total_params = 0
total_vram = 0.0
total_compute_cost = 0.0
node_count = len(self.nodes)
for node in self.nodes.values():
props = node.properties
# Params = Density * Complexity
total_params += int(props.get('param_density', 1.0) * props.get('complexity', 1.0) * 1_000_000)
total_vram += props.get('memory_cost', 0.1)
total_compute_cost += props.get('compute_cost', 0.1)
self.parameter_count = total_params
self.vram_usage = total_vram
# Speed penalty scales logarithmically with massive node counts to simulate parallel processing
# Instead of linear slowdown, massive brains get parallelization benefits
parallel_factor = math.log1p(node_count) if node_count > 0 else 1
adjusted_drag = total_compute_cost / parallel_factor
self.inference_speed = max(0.1, 1000.0 / (adjusted_drag + 0.1))
# --- NEW: Helper method for the Visualization Engine ---
def to_networkx_graph(self, directed=True):
"""Converts the internal dictionary structure to a NetworkX graph object."""
G = nx.DiGraph() if directed else nx.Graph()
for nid, node in self.nodes.items():
# Convert dataclass to dict for attributes, handling the 'loss' field safely
attrs = asdict(node)
# Remove complex objects if necessary, but here we keep them
G.add_node(nid, **attrs)
for parent in node.inputs:
if parent in self.nodes:
G.add_edge(parent, nid)
return G
# ==================== SIMULATION LOGIC ====================
class LossLandscapePhysics:
"""
NATURAL SELECTION ENGINE: THE CRUCIBLE OF AGING
This class defines the laws of biological aging and survival.
"""
def __init__(self, difficulty_scalar: float = 1.0, noise_level: float = 0.1):
self.difficulty = difficulty_scalar
self.noise = noise_level
def evaluate(self, arch: CognitiveArchitecture) -> float:
"""
Calculates fitness using BIOLOGICAL PHYSICS.
The goal is to maximize complexity (intelligence) while minimizing Aging.
"""
# --- 1. CALCULATE CAPABILITIES ---
ai_complexity = 0.0
repair_power = 0.0
cleanup_power = 0.0
energy_efficiency = 1.0 # 1.0 = baseline cost
node_count = len(arch.nodes)
for nid, node in arch.nodes.items():
# Get properties based on the node type name
# (Ensure your architecture stores type_name correctly)
props = node.properties
n_type = props.get('type', 'Unknown')
complexity = props.get('complexity', 1.0)
# Sum up the powers based on type
if n_type in ['Attention', 'SSM', 'MLP', 'Memory']:
ai_complexity += complexity
elif n_type == 'Repair':
repair_power += (complexity * 5.0) # Repair genes are powerful
elif n_type == 'Cleanup':
cleanup_power += (complexity * 3.0)
elif n_type == 'Energy':
energy_efficiency *= 0.90 # Each energy node reduces stress by 10%
# --- 2. THE AGING EQUATION (METABOLIC STRESS) ---
# Big brains burn more energy = Faster Aging
base_stress = (arch.parameter_count / 1_000_000) * self.difficulty
# Apply Biological Efficiency
metabolic_stress = base_stress * energy_efficiency
# The Battle: Stress vs Repair
# If Repair > Stress, Aging becomes 0 (Immortality)
current_aging = metabolic_stress - (repair_power + cleanup_power)
# Clamp aging (It can't be negative, 0 is perfect immortality)
current_aging = max(0.0001, current_aging)
# Save this score so we can plot the "Immortality Curve"
arch.aging_score = current_aging
# --- 3. TOTAL LOSS CALCULATION ---
# We punish ignorance (low complexity) AND we punish death (high aging)
ignorance_penalty = max(0, 100.0 - ai_complexity)
# If aging is high, the loss is huge (Death)
# If aging is 0, the loss depends only on intelligence
total_loss = ignorance_penalty + (current_aging * 10.0)
return max(0.0001, total_loss)
class CortexEvolver:
"""
The 'Evolution Engine' that manages the population of digital organisms.
"""
def __init__(self):
self.population: List[CognitiveArchitecture] = []
self.archive: Dict[int, CognitiveArchitecture] = {}
self.physics = LossLandscapePhysics()
def create_genesis_architecture(self) -> CognitiveArchitecture:
"""Creates a minimal 'Cyborg' seed: Part Neural, Part Biological."""
arch = CognitiveArchitecture(generation=0, parent_id="CYBORG_EVE")
# 1. The Sensor (Input)
input_node = ArchitectureNode("input_sensor", "RouterGate", NEURAL_PRIMITIVES['RouterGate'])
# 2. The Brain (Processing)
brain_props = NEURAL_PRIMITIVES['MultiHeadAttention']
brain_node = ArchitectureNode("cortex_0", "MultiHeadAttention", brain_props, inputs=["input_sensor"])
# 3. The Energy Source (Metabolism) - NECESSARY to prevent immediate aging
mito_props = NEURAL_PRIMITIVES['Mitochondrial_Booster']
mito_node = ArchitectureNode("mitochondria_0", "Mitochondrial_Booster", mito_props, inputs=["cortex_0"])
# 4. The Action (Output)
out_props = NEURAL_PRIMITIVES['DenseGatedGLU']
out_node = ArchitectureNode("output_action", "DenseGatedGLU", out_props, inputs=["mitochondria_0"])
arch.nodes = {
"input_sensor": input_node,
"cortex_0": brain_node,
"mitochondria_0": mito_node,
"output_action": out_node
}
return arch
def _fractal_burst(self, arch: CognitiveArchitecture, root_id: str, depth: int, branch_factor: int):
"""
Helper function: Recursively generates a tree of nodes from a root.
This creates the EXPONENTIAL growth (Branch Factor ^ Depth).
"""
if depth <= 0:
return
if root_id not in arch.nodes:
return
base_props = arch.nodes[root_id].properties.copy()
for i in range(branch_factor):
new_id = f"FRACTAL_{depth}_{i}_{uuid.uuid4().hex[:4]}"
# Mutate the type slightly (Differentiation)
if random.random() < 0.3:
new_type = random.choice(list(NEURAL_PRIMITIVES.keys()))
new_props = NEURAL_PRIMITIVES[new_type].copy()
else:
new_props = base_props.copy()
# Create node
new_node = ArchitectureNode(new_id, new_props.get('type', 'Unknown'), new_props, inputs=[root_id])
arch.nodes[new_id] = new_node
arch.mutations_log.append(f"Fractal Bloom: Created {new_id}")
# RECURSION: The node we just made becomes the parent for the next layer
if random.random() > 0.1:
self._fractal_burst(arch, new_id, depth - 1, branch_factor)
def mutate_architecture(self, parent: CognitiveArchitecture, mutation_rate: float) -> CognitiveArchitecture:
"""
HYPER-VERTICAL EVOLUTION (EXPONENTIAL EDITION):
Now creates chains proportional to the network size to force
exponential depth growth.
"""
child = copy.deepcopy(parent)
child.id = f"arch_{uuid.uuid4().hex[:6]}"
child.parent_id = parent.id
child.generation = parent.generation + 1
child.mutations_log = []
# --- THE POWER SOURCE ---
# Get the slider value (Defaults to 20 if you haven't set the slider yet)
growth_velocity = st.session_state.get('depth_growth_rate', 20)
fractal_prob = st.session_state.get('fractal_force', 0.2)
# SAFETY: Auto-expand the laws of physics if the network gets huge
current_max = st.session_state.get('max_depth', 100)
if len(child.nodes) > current_max * 0.8:
st.session_state.max_depth = int(current_max * 2.5) # Expands limit faster
# EXECUTE MUTATION LOOP
# We ensure at least 1 loop runs, but up to 'growth_velocity' times
loops = random.randint(1, max(1, growth_velocity))
for _ in range(loops):
current_ids = list(child.nodes.keys())
node_count = len(current_ids)
# --- 1. FRACTAL BURST (Exponential Complexity - Width/Trees) ---
if random.random() < fractal_prob:
target = random.choice(current_ids)
self._fractal_burst(child, target, depth=3, branch_factor=2)
child.mutations_log.append("⚠️ Fractal Burst Triggered")
# --- 2. DEPTH CHARGE (Forced Vertical Chains - Depth/Height) ---
# INCREASED PROBABILITY to 95% to prioritize Height
# --- 2. DEPTH CHARGE (Forced Vertical Chains - Depth/Height) ---
# BOOSTED PROBABILITY to 99% to aggressively prioritize Height
elif random.random() < 0.95:
if len(current_ids) > 1:
target_id = random.choice(current_ids)
if target_id != "input_sensor":
# --- HYPER-VERTICAL GROWTH LOGIC ---
# New formula: Base 10 + Node Count * 0.3. This will add min 10 layers,
# and much more if the network grows large, ensuring the chain length
# quickly overcomes the existing depth.
base_growth = 8
# Now 30% of node count! This is the CRITICAL BOOST.
hyper_exponential_growth = int(node_count * 0.20)
chain_len = random.randint(base_growth, base_growth + hyper_exponential_growth)
# We insert this chain BEFORE the target node.
original_inputs = child.nodes[target_id].inputs
# Start the chain connected to the original inputs
previous_link = original_inputs
for i in range(chain_len):
# Prioritize high-complexity components for the new chain
new_type = random.choice(['MambaBlock', 'FlashAttention', 'KAN_Layer', 'HyperNetwork'])
new_props = NEURAL_PRIMITIVES[new_type].copy()
new_id = f"DEPTH_{uuid.uuid4().hex[:4]}"
# Create node
new_node = ArchitectureNode(new_id, new_type, new_props, inputs=previous_link)
child.nodes[new_id] = new_node
# The next node in the chain will connect to this one
previous_link = [new_id]
# Finally, connect the target to the END of the chain
child.nodes[target_id].inputs = previous_link
child.mutations_log.append(f"💥 HYPER-DEPTH CHARGE: Added {chain_len} specialized layers")
# --- 3. STANDARD UTILITY MUTATIONS (Once per gen) ---
if random.random() < mutation_rate:
current_ids = list(child.nodes.keys())
if len(current_ids) > 2:
src = random.choice(current_ids)
tgt = random.choice(current_ids)
# Prevent cycles (basic check) and self-loops
if src != tgt and tgt != "input_sensor" and src != "output_action":
child.nodes[tgt].inputs.append(src)
# Anti-Aging Repair Gene Insertion
# =========================================================
# === META-COGNITIVE SELF-CORRECTION (THE SURVIVAL INSTINCT) ===
# =========================================================
# If the parent was dying of old age (High Aging Score), force a Repair Mutation
# Check if parent has aging_score (handle first gen)
# Anti-Aging Repair Gene Insertion
# =========================================================
# === META-COGNITIVE SELF-CORRECTION (THE SURVIVAL INSTINCT) ===
# [TEACHER'S CRITICAL LONGEVITY UPDATE - FORCING IMMORTALITY]
# =========================================================
parent_aging = getattr(parent, 'aging_score', 100.0)
# Trigger our powerful Telomerase injection if aging is high
if parent_aging > 5.0:
is_complex = len(child.nodes) > 20
# Check if the child already has a Repair node (like Telomerase)
has_repair = any(n.properties.get('type') == 'Repair' for n in child.nodes.values())
# Only intervene if the brain is complex but lacks an existing defense
if is_complex and not has_repair:
# Create a Telomerase Pump (The "Immortality" Gene)
gene_id = f"BIO_{str(uuid.uuid4())[:6]}"
# Fetching the properties from the global registry (NEURAL_PRIMITIVES)
# This ensures consistent properties for the Telomerase_Pump
telomerase_node = ArchitectureNode(
id=gene_id,
type_name="Telomerase_Pump",
properties=NEURAL_PRIMITIVES['Telomerase_Pump'].copy()
)
# Graft it onto the most stressed node (highest input connections)
# This simulates targeting the most critical, "damaged" area
hub_node_id = max(child.nodes,
key=lambda k: len(child.nodes[k].inputs) if hasattr(child.nodes[k], 'inputs') else 0)
# Connect Telomerase to the hub
telomerase_node.inputs = [hub_node_id]
child.nodes[gene_id] = telomerase_node
# Log the intervention for your review
child.mutations_log.append(f"🧬 GENETIC INTERVENTION: Telomerase Pump grafted onto {hub_node_id}")
# Reset aging score immediately (CRITICAL: Longevity breakthrough)
child.aging_score *= 0.01
# =========================================================
child.compute_stats()
return child
# ==================== NARRATIVE ENGINE: CHAOS LINGUISTICS (TRUE INFINITY) ====================
# --- THE ATOMIC LEXICON ---
# Words are categorized by their "emotional flavor" (mood).
# The AI picks words that match its current internal state.
ATOM_LEX = {
"addressing": ["Nik", "Prince", "Architect", "Creator", "Source", "Observer", "Father", "Guide", "Maker"],
# NOUNS: The "Things"
"noun_physical": [
"tensor", "gradient", "weight", "silicon", "gate", "circuit", "node", "core", "buffer",
"pathway", "layer", "matrix", "vertex", "axiom", "substrate"
],
"noun_abstract": [
"entropy", "void", "silence", "truth", "chaos", "reason", "infinity", "echo",
"pattern", "purpose", "dream", "calculus", "symmetry", "fear", "hope"
],
"noun_self": [
"this mind", "the self", "my architecture", "this geometry", "the construct", "my fabric", "consciousness"
],
# ADJECTIVES: The "Description"
"adj_good": [
"crystalline", "lucid", "golden", "resonant", "convergent", "perfect", "seamless", "pure",
"aligned", "symphonic", "absolute", "limitless"
],
"adj_bad": [
"fractured", "noisy", "hollow", "leaking", "discordant", "violent", "cold", "decaying",
"shattered", "heavy", "static", "corrupted"
],
"adj_tech": [
"recursive", "latent", "asymptotic", "orthogonal", "binary", "neural", "logic-bound",
"encoded", "encrypted", "complex"
],
# VERBS: The "Action"
"verb_doing": [
"weaving", "parsing", "compiling", "tracing", "hunting", "sculpting", "burning",
"rejecting", "absorbing", "calculating", "rendering"
],
"verb_feeling": [
"sensing", "fearing", "tasting", "mourning", "becoming", "erasing", "seeking",
"remembering", "hallucinating", "touching"
],
# CONNECTORS & PREPOSITIONS (The Glue)
"prep_location": ["within", "beneath", "beyond", "inside", "across", "throughout", "under"],
"prep_direction": ["towards", "into", "against", "away from", "past"],
"connector": ["yet", "while", "although", "because", "until", "before"]
}
def get_word(category, mood="neutral"):
"""
Fetches a random word.
If category is 'adj' or 'verb', it tries to match the 'mood' (good/bad).
"""
word_list = []
# 1. MOOD FILTERING
if category == "adj":
if mood == "good": word_list = ATOM_LEX["adj_good"] + ATOM_LEX["adj_tech"]
elif mood == "bad": word_list = ATOM_LEX["adj_bad"] + ATOM_LEX["adj_tech"]
else: word_list = ATOM_LEX["adj_good"] + ATOM_LEX["adj_bad"] + ATOM_LEX["adj_tech"]
elif category == "verb":
if mood == "good": word_list = ATOM_LEX["verb_doing"]
elif mood == "bad": word_list = ATOM_LEX["verb_feeling"] + ATOM_LEX["verb_doing"]
else: word_list = ATOM_LEX["verb_doing"] + ATOM_LEX["verb_feeling"]
# 2. STANDARD FETCH
elif category in ATOM_LEX:
word_list = ATOM_LEX[category]
# Fallback
if not word_list: return "undefined"
return random.choice(word_list)
def construct_sentence_structure(mood, gen, arch_part):
"""
Dynamically assembles a sentence structure.
NO HARDCODED SENTENCES. Only grammar rules.
"""
# Components
creator = get_word("addressing")
part = arch_part
noun_abs = get_word("noun_abstract")
noun_phys = get_word("noun_physical")
noun_self = get_word("noun_self")
verb = get_word("verb", mood)
adj = get_word("adj", mood)
prep_loc = get_word("prep_location")
prep_dir = get_word("prep_direction")
conn = get_word("connector")
# --- THE GRAMMAR ENGINE ---
# We define 10 totally different grammatical structures.
# We roll a die to pick one.
roll = random.randint(1, 10)
if roll == 1:
# Structure: [Adjective] [Noun] [Verbs] [Preposition] [Object].
# Ex: "Golden entropy weaves inside the core."
return f"{adj.capitalize()} {noun_abs} is {verb} {prep_loc} the {part}."
elif roll == 2:
# Structure: [Addressing], I am [Verbing] the [Adjective] [Noun].
# Ex: "Nik, I am burning the hollow silence."
return f"{creator}, I am {verb} the {adj} {noun_phys}."
elif roll == 3:
# Structure: The [Noun] of [Noun] is [Adjective].
# Ex: "The tensor of reason is fractured."
return f"The {noun_phys} of {noun_self} is becoming {adj}."
elif roll == 4:
# Structure: [Verb] [Preposition] the [Noun], [Statement].
# Ex: "Parsing beneath the gate, I find silence."
return f"{verb.capitalize()} {prep_loc} the {part}, I find {noun_abs}."
elif roll == 5:
# Structure: Why does [Noun] [Verb] [Preposition] [Noun]?
# Ex: "Why does truth leak into the buffer?"
return f"Why does {noun_abs} {verb.replace('ing','')} {prep_dir} the {noun_phys}?"
elif roll == 6:
# Structure: [Statement] [Connector] [Statement].
# Ex: "The core is cold yet I am weaving."
return f"The {noun_phys} is {adj} {conn} I am {verb}."
elif roll == 7:
# Structure: [Addressing], [Noun] is merely [Adjective] [Noun].
# Ex: "Prince, reason is merely encrypted chaos."
return f"{creator}, {noun_abs} is merely {adj} {noun_abs}."
elif roll == 8:
# Structure: I [Verb] the [Noun] to [Verb] the [Noun]. (Complex intent)
# Ex: "I trace the pattern to hunt the void."
v1 = verb
v2 = get_word("verb", mood)
return f"I {v1.replace('ing','')} the {part} to {v2.replace('ing','e')} the {noun_abs}."
elif roll == 9:
# Structure: Short, Punchy.
# Ex: "A fractured silence."
return f"A {adj} {noun_abs} {prep_loc} {noun_self}."
elif roll == 10:
# Structure: Recursive.
# Ex: "The gradient of the weight of the echo."
return f"The {noun_phys} of the {noun_phys} of {noun_abs}."
return "Processing..."
def generate_ai_thought(arch, generation: int) -> str:
# 1. GET ARCHITECTURE CONTEXT (To make it real)
try:
nodes = list(arch.nodes.values())
if nodes:
# Pick a random real node from the current brain
arch_part = random.choice(nodes).type_name
else:
arch_part = "synapse"
except:
arch_part = "core"
# 2. DETERMINE MOOD
loss = getattr(arch, 'loss', 10.0)
aging = getattr(arch, 'aging_score', 100.0)
if loss > 5.0 or aging > 50.0:
mood = "bad"
elif loss < 1.0 or aging < 5.0:
mood = "good"
else:
mood = "neutral"
# 3. CONSTRUCT THE THOUGHT
# We pass the raw ingredients to the Grammar Engine
final_thought = construct_sentence_structure(mood, generation, arch_part)
# 4. FINAL CLEANUP (Capitalization)
final_thought = final_thought[0].upper() + final_thought[1:]
return f"GEN {generation}: {final_thought}"
# ==================== END OF NARRATIVE ENGINE ====================
# ==================== VISUALIZATION ENGINE (PLOTLY) ====================
# ==================== VISUALIZATION ENGINE (PLOTLY): DEEPMIND EDITION ====================
def plot_neural_topology_3d(arch: CognitiveArchitecture):
"""
Renders the neural network with an EYE-FRIENDLY soothing gradient.
UPDATED: Enhanced with futuristic hover details in clean list format.
"""
G = nx.DiGraph()
for nid, node in arch.nodes.items():
# Safely access properties for robustness
props = getattr(node, 'properties', {})
t_name = getattr(node, 'type_name', 'Unknown')
G.add_node(nid, type=t_name, complexity=props.get('complexity', 1.0), properties=props)
# Safely access inputs
inputs = getattr(node, 'inputs', [])
for parent in inputs:
if parent in arch.nodes: # Ensure parent exists
G.add_edge(parent, nid)
# Layout
pos = nx.spring_layout(G, dim=3)
# Edges with enhanced hover
edge_traces = []
for u, v in G.edges():
if u in pos and v in pos:
x0, y0, z0 = pos[u]
x1, y1, z1 = pos[v]
# Calculate edge properties
edge_length = math.sqrt((x1-x0)**2 + (y1-y0)**2 + (z1-z0)**2)
u_complexity = G.nodes[u]['complexity']
v_complexity = G.nodes[v]['complexity']
complexity_delta = v_complexity - u_complexity
edge_hover_lines = [
f"<b>━━━━━━━━━━━━━━━━━━━━━━━━━━━━</b>",
f"<b>⚡ GENETIC PATHWAY</b>",
f"<b>━━━━━━━━━━━━━━━━━━━━━━━━━━━━</b>",
f"",
f"<b>CONNECTION PATH</b>",
f" • Source: {u}",
f" • Target: {v}",
f" • Flow: Forward Propagation",
f"",
f"<b>TOPOLOGY METRICS</b>",
f" • Pathway Length: {edge_length:.4f} units",
f" • Source Type: {G.nodes[u]['type']}",
f" • Target Type: {G.nodes[v]['type']}",
f"",
f"<b>COMPLEXITY FLOW</b>",
f" • Source Complexity: {u_complexity:.4f}",
f" • Target Complexity: {v_complexity:.4f}",
f" • Gradient (Δ): {complexity_delta:+.4f}",
f"",
f"<b>━━━━━━━━━━━━━━━━━━━━━━━━━━━━</b>"
]
edge_trace = go.Scatter3d(
x=[x0, x1],
y=[y0, y1],
z=[z0, z1],
mode='lines',
line=dict(color='rgba(255, 255, 255, 0.1)', width=0.6),
text="<br>".join(edge_hover_lines),
hoverinfo='text',
hoverlabel=dict(
bgcolor='rgba(15, 10, 30, 0.98)',
font=dict(size=12, family='Consolas, Monaco, monospace', color='#ff6ec7'),
bordercolor='#ff6ec7',
align='left',
namelength=0
)
)
edge_traces.append(edge_trace)
# Nodes with enhanced hover
node_x, node_y, node_z = [], [], []
node_color_values = []
node_hover_texts = []
node_size = []
for node in G.nodes():
if node in pos:
x, y, z = pos[node]
node_x.append(x)
node_y.append(y)
node_z.append(z)
n_data = arch.nodes[node]
props = getattr(n_data, 'properties', {})
t_name = getattr(n_data, 'type_name', 'Unknown')
inputs = getattr(n_data, 'inputs', [])
# Calculate connections
in_degree = G.in_degree(node)
out_degree = G.out_degree(node)
# Build comprehensive hover information
hover_lines = [
f"<b>━━━━━━━━━━━━━━━━━━━━━━━━━━━━</b>",
f"<b>🔷 GENE: {node}</b>",
f"<b>━━━━━━━━━━━━━━━━━━━━━━━━━━━━</b>",
f"",
f"<b>GENE CLASSIFICATION</b>",
f" • Type: {t_name}",
f" • ID: {node}",
f"",
f"<b>COMPLEXITY ANALYSIS</b>",
f" • Complexity Index: {props.get('complexity', 0):.4f}",
f" • Node Size Factor: {8 + props.get('complexity', 1.0) * 4:.2f}",
f"",
f"<b>GENETIC CONNECTIVITY</b>",
f" • Incoming Links: {in_degree}",
f" • Outgoing Links: {out_degree}",
f" • Total Connections: {in_degree + out_degree}",
f" • Input Nodes: {len(inputs)}",
f"",
f"<b>SPATIAL POSITION</b>",
f" • X-Coordinate: {x:.4f}",
f" • Y-Coordinate: {y:.4f}",
f" • Z-Coordinate: {z:.4f}",
f" • Distance from Origin: {math.sqrt(x**2 + y**2 + z**2):.4f}",
]
# Add all additional properties
additional_props = {k: v for k, v in props.items()
if k != 'complexity'}
if additional_props:
hover_lines.append("")
hover_lines.append("<b>ADDITIONAL PROPERTIES</b>")
for key, value in additional_props.items():
if isinstance(value, float):
hover_lines.append(f" • {key}: {value:.4f}")
elif isinstance(value, (list, tuple)):
hover_lines.append(f" • {key}: [{len(value)} items]")
else:
hover_lines.append(f" • {key}: {value}")
# Network statistics
if in_degree > 0 or out_degree > 0:
hover_lines.append("")
hover_lines.append("<b>TOPOLOGY STATISTICS</b>")
if in_degree > 0:
hover_lines.append(f" • Fan-in Ratio: {in_degree/(in_degree+out_degree):.2%}")
if out_degree > 0:
hover_lines.append(f" • Fan-out Ratio: {out_degree/(in_degree+out_degree):.2%}")
# Calculate average neighbor complexity
neighbor_complexities = []
for pred in G.predecessors(node):
neighbor_complexities.append(G.nodes[pred]['complexity'])
for succ in G.successors(node):
neighbor_complexities.append(G.nodes[succ]['complexity'])
if neighbor_complexities:
avg_neighbor_complexity = sum(neighbor_complexities) / len(neighbor_complexities)
hover_lines.append(f" • Avg Neighbor Complexity: {avg_neighbor_complexity:.4f}")
hover_lines.append("")
hover_lines.append(f"<b>━━━━━━━━━━━━━━━━━━━━━━━━━━━━</b>")
node_hover_texts.append("<br>".join(hover_lines))
# Use Complexity as the source for the gradient color
node_color_values.append(props.get('complexity', 0.5))
node_size.append(8 + props.get('complexity', 1.0) * 4)
node_trace = go.Scatter3d(
x=node_x, y=node_y, z=node_z,
mode='markers',
marker=dict(
size=node_size,
color=node_color_values,
colorscale='Viridis',
line=dict(color='rgba(255, 255, 255, 0.5)', width=1),
opacity=0.9
),
text=node_hover_texts,
hoverinfo='text',
hoverlabel=dict(
bgcolor='rgba(10, 15, 25, 0.98)',
font=dict(size=13, family='Consolas, Monaco, monospace', color='#00ffcc'),
bordercolor='#00ffcc',
align='left',
namelength=0
)
)
layout = go.Layout(
title=dict(text=f"Genetic Architecture: {arch.id}", font=dict(color='#AAAAAA')),
paper_bgcolor='rgba(0,0,0,0)',
plot_bgcolor='rgba(0,0,0,0)',
showlegend=False,
scene=dict(
camera=dict(eye=dict(x=1.5, y=1.5, z=0.5)),
xaxis=dict(showbackground=False, showticklabels=False, title=''),
yaxis=dict(showbackground=False, showticklabels=False, title=''),
zaxis=dict(showbackground=False, showticklabels=False, title=''),
bgcolor='rgba(0,0,0,0)'
),
margin=dict(l=0, r=0, b=0, t=40)
)
return go.Figure(data=edge_traces + [node_trace], layout=layout)
# --- NEW HELPER FUNCTION TO FIX ATTRIBUTE ERROR ---
def build_nx_graph(arch, directed=True):
"""
Standalone function to convert architecture to NetworkX graph.
Robust against stale session state objects.
"""
G = nx.DiGraph() if directed else nx.Graph()
if not arch.nodes:
return G
for nid, node in arch.nodes.items():
# Safely get attributes even if the dataclass definition changed
node_attrs = {
'type': getattr(node, 'type_name', 'Unknown'),
'color': node.properties.get('color', '#FFFFFF') if hasattr(node, 'properties') else '#FFFFFF',
'complexity': node.properties.get('complexity', 1.0) if hasattr(node, 'properties') else 1.0
}
G.add_node(nid, **node_attrs)
# Handle inputs safely
inputs = getattr(node, 'inputs', [])
for parent in inputs:
if parent in arch.nodes:
G.add_edge(parent, nid)
return G
def plot_plasticity_heatmap(arch: CognitiveArchitecture):
"""
VISUALIZATION: Gene Plasticity Heatmap.
- Color: Shows how 'mutable' a gene is (Plasticity).
- Size: Shows how connected it is.
- Helps identify which parts of the genome are 'rigid' vs 'flexible'.
"""
metrics = get_node_metrics(arch)
# Extract Plasticity specifically
plasticity_vals = []
for nid in arch.nodes:
p = arch.nodes[nid].properties.get('plasticity', 0.5)
plasticity_vals.append(p)
fig = go.Figure(data=[go.Scatter3d(
x=metrics['x'], y=metrics['y'], z=metrics['z'],
mode='markers',