-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsim.py
More file actions
3113 lines (2603 loc) · 127 KB
/
Copy pathsim.py
File metadata and controls
3113 lines (2603 loc) · 127 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
import random
import math
import numpy as np
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, Set, List, Tuple, Optional
from collections import defaultdict
import logging
# Import decision logic module (can be swapped for different strategies)
#import decide_optimized as decide_module
import decide_cython as decide_module
TWOPI = 2 * math.pi
@dataclass
class Agent:
world_id: int
id: int
sex: int = 0 # 0 = male, 1 = female
born: int = 0 # Tick when agent was spawned
parent: List[int] = field(default_factory=lambda: [-1, -1]) # IDs of parents ([-1,-1] for founders)
offspring: List[int] = field(default_factory=list) # IDs of offspring
kinship: Dict[int, float] = field(default_factory=dict) # {agent_id: relatedness coefficient}
pregnant: bool = False # True if carrying unborn offspring (females only)
# State parameters
x: int = 0
y: int = 0
energy: float = 0.0
hap: float = 0.5
trust: float = 0.5
# Genetic parameters - phenotypes (inherited with mutation, diploid)
o: float = 0.5 # Openness
c: float = 0.5 # Conscientiousness
e: float = 0.5 # Extraversion
a: float = 0.5 # Agreeableness
n: float = 0.5 # Neuroticism
kin: float = 0.5 # Kin altruism tendency (trait, not to confuse with kinship dict)
xeno: float = 0.5 # Xenophilia/xenophobia tendency
# Diploid variances (|allele1 - allele2|, used only at procreation)
vo: float = 0.0
vc: float = 0.0
ve: float = 0.0
va: float = 0.0
vn: float = 0.0
vkin: float = 0.0
vxeno: float = 0.0
# Speciation genes [0-10] - haploid (averaged over many loci)
genes: List[float] = field(default_factory=lambda: [5.0, 5.0, 5.0])
# Social bonds
spouse: int = -1 # ID of spouse (-1 = unmarried), set on first mating with unmarried partner
# Cultural traits [0-10] - inherited from mother, updated via cooperation and spousal assimilation
culture: List[float] = field(default_factory=lambda: [5.0, 5.0, 5.0])
@property
def cell(self) -> Tuple[int, int]:
"""Current cell for food/interactions (floor of position)"""
return (int(self.x), int(self.y))
@property
def position(self) -> tuple:
"""
Agent's position in the simulation's coordinate system.
Returns an opaque position tuple - the server should not
interpret the contents, only pass them through.
For this 2D simulation, returns (x, y).
"""
return (self.x, self.y)
def to_display_dict(self) -> dict:
"""
Minimal data for visualization - streamed continuously.
Only includes phenotype fields for efficient bandwidth.
Note: world_id is added by World.get_entity_display(), not here.
"""
return {
'id': self.id,
'sex': self.sex,
'x': self.x,
'y': self.y,
}
def to_viewport_dict(self) -> dict:
"""
Intermediate data for agents in viewport.
"""
return {
'id': self.id,
'sex': self.sex,
'born': self.born,
'x': self.x,
'y': self.y,
'parent': self.parent,
'spouse': self.spouse,
'energy': round(self.energy, 2),
'o': round(self.o, 2),
'c': round(self.c, 2),
'e': round(self.e, 2),
'a': round(self.a, 2),
'n': round(self.n, 2),
'hap': round(self.hap, 2),
'genes': [round(g, 2) for g in self.genes],
'culture': [round(c, 2) for c in self.culture],
}
def to_full_dict(self) -> dict:
"""
Complete state - only sent on inspect request.
Includes phenotype + internal state + genetics.
currently unused (and not sending diploid variations or full kinship dict, 'pregnant' boolean):
'hap': round(self.hap, 2),
'trust': round(self.trust, 2),
'kinship': {k: round(v, 3) for k, v in self.kinship.items()},
'vo': round(self.vo, 2),
'vc': round(self.vc, 2),
've': round(self.ve, 2),
'va': round(self.va, 2),
'vn': round(self.vn, 2),
'vkin': round(self.vkin, 2),
'vxeno': round(self.vxeno, 2),
"""
return {
'id': self.id,
'sex': self.sex,
'born': self.born,
'x': self.x,
'y': self.y,
'parent': self.parent,
'offspring': self.offspring,
'spouse': self.spouse,
'energy': round(self.energy, 2),
'o': round(self.o, 2),
'c': round(self.c, 2),
'e': round(self.e, 2),
'a': round(self.a, 2),
'n': round(self.n, 2),
'kin': round(self.kin, 2),
'xeno': round(self.xeno, 2),
'hap': round(self.hap, 2),
'trust': round(self.trust, 2),
'genes': [round(g, 2) for g in self.genes],
'culture': [round(c, 2) for c in self.culture],
'n_kin': len(self.kinship),
}
@dataclass
class Map:
world_id: int
x: int
y: int
pd: List[int]
food: float
@property
def position(self) -> tuple:
"""Map cell position for viewport filtering."""
return (self.x, self.y)
def to_display_dict(self) -> dict:
"""
Minimal data for visualization - streamed continuously.
"""
return {
'map': 1, # Marker so client knows this is a cell, not an agent
'x': self.x,
'y': self.y,
'pd': list(self.pd), # Copy to avoid mutation issues
}
def to_viewport_dict(self) -> dict:
"""
Data for cells in viewport (same as display for now).
"""
return {
'map': 1,
'x': self.x,
'y': self.y,
'pd': list(self.pd),
}
def to_full_dict(self) -> dict:
return {
'map': 1,
'x': self.x,
'y': self.y,
'pd': list(self.pd),
'food': round(self.food, 2),
}
@dataclass
class NeighborhoodCache:
"""Pre-computed neighborhood data, built once per tick."""
tick: int
cell_fertile_females: Dict[Tuple[int,int], List[int]] = field(default_factory=lambda: defaultdict(list))
cell_fertile_males: Dict[Tuple[int,int], List[int]] = field(default_factory=lambda: defaultdict(list))
cell_adult_males: Dict[Tuple[int,int], List[int]] = field(default_factory=lambda: defaultdict(list))
cell_adults: Dict[Tuple[int,int], List[int]] = field(default_factory=lambda: defaultdict(list))
moore_fertile_females: Dict[Tuple[int,int], List[int]] = field(default_factory=dict)
moore_fertile_males: Dict[Tuple[int,int], List[int]] = field(default_factory=dict)
moore_adult_males: Dict[Tuple[int,int], List[int]] = field(default_factory=dict)
fertile_female_ids: Set[int] = field(default_factory=set)
class SpatialGrid:
"""
Spatial index for O(1) queries of "which agents are in cell (x,y)?"
Critical for scalability: without this, finding nearby agents is O(n).
With this, it's O(agents_in_cell).
Accepts float positions - converts to int cell coordinates internally.
"""
def __init__(self, width: int, height: int):
self.width = width
self.height = height
# cell -> set of agent IDs in that cell
self._grid: Dict[Tuple[int, int], Set[int]] = defaultdict(set)
def add(self, agent_id: int, x: int, y: int):
cell = (int(x), int(y))
self._grid[cell].add(agent_id)
def remove(self, agent_id: int, x: int, y: int):
cell = (int(x), int(y))
self._grid[cell].discard(agent_id)
def move(self, agent_id: int, old_x: int, old_y: int, new_x: int, new_y: int):
"""Update agent's cell assignment. Only modifies grid if cell changed."""
old_cell = (int(old_x), int(old_y))
new_cell = (int(new_x), int(new_y))
if old_cell != new_cell:
self._grid[old_cell].discard(agent_id)
self._grid[new_cell].add(agent_id)
def agents_at(self, x: int, y: int) -> Set[int]:
return self._grid[(x, y)]
def agents_in_region(self, x1: int, y1: int, x2: int, y2: int) -> Set[int]:
"""Get all agent IDs in a rectangular region (for AOI queries)"""
result = set()
for x in range(x1, x2 + 1):
for y in range(y1, y2 + 1):
result.update(self._grid[(x, y)])
return result
class World:
# Simulation parameters
TICK_YEARS = 0.25 # one simulation tick in human years
FOOD_REGEN_PER_TURN = 3.0
FOOD_CEILING = 3.0
SEASON_STRENGTH = 0.7
INITIAL_ENERGY = 0.8
METABOLISM_COST = 0.06
MAX_ENERGY = 10.0
REPRODUCTION_THRESHOLD = 1.6
REPRODUCTION_COST = 0.8
MALE_INVESTMENT = 0.05
# EAT_RATE = 1.0 # DEPRECATED - food distribution now handled via PD game
INFANCY = 3
CHILDHOOD = 7
ADOLESCENCE = 14
ADULTHOOD = 21
MENOPAUSE = 44
SENESCENCE = 60
GESTATION_TICKS = int(0.75 / TICK_YEARS) # 9 months gestation
# Accident/death parameters (children under ADOLESCENCE are exempt)
ACCIDENT_BASE_RATE = 0.002 # Base per-tick accident rate for adult females (~0.8%/year)
ACCIDENT_MALE_MULT = 1.5 # Males have 1.5x accident rate
ACCIDENT_YOUNG_MALE_MULT = 2.0 # Young males (ADOLESCENCE-ADULTHOOD) have additional 2x multiplier
ACCIDENT_OPENNESS_FACTOR = 0.002 # Additional rate per unit openness (max +0.002 at o=1.0)
ACCIDENT_SENESCENCE_RATE = 0.005 # Additional per-tick rate = (age - SENESCENCE) * this
# Twin probabilities
P_ID_TWINS = 0.003 # Identical twins chance
P_FR_TWINS = 0.014 # Fraternal twins (only if not id_twins, we don't do triplets)
# Mutation rates for genetic parameters
GENE_MUTATION_SD = 1.0 # range [0,10]
TRAIT_MUTATION_SD = 0.05 # range [0,1]
# Kinship tracking threshold (cousin-tier = 0.125, half-cousin = 0.0625)
RELATEDNESS_THRESHOLD = 0.0625
# Mate selection: incest taboo, strong suppression above this kinship (cousin = 0.125)
CONSANGUINITY_TOLERANCE = 0.15
# Culture assimilation rate (how much culture shifts per cooperative interaction or spousal tick)
CULTURE_ASSIMILATION_RATE = 0.05
# Female cultural malleability multiplier (females more responsive to cultural pressure)
FEMALE_CULTURE_MULT = 2.0
# Extraversion dampening (extroverts comfortable with diversity, don't need alignment)
CULTURE_EXTRAVERSION_DAMP = 0.8 # high E (1.0) → 0.7x rate
# Neuroticism culture shock threshold and dampening
CULTURE_SHOCK_THRESHOLD = 2.5 # Euclidean distance where neuroticism resistance kicks in
CULTURE_NEUROTICISM_DAMP = 0.5 # high N (1.0) past threshold → 0.5x rate
# Conscientiousness spousal assimilation bonus
CULTURE_SPOUSAL_C_BONUS = 0.5 # high C (1.0) in spousal → 1.5x rate
# Maximum assimilation step per interaction (Euclidean distance)
CULTURE_MAX_STEP = 0.05
# Cultural tt: random exploration weighted by Openness
CULTURE_DRIFT_RATE = 0.2 # baseline random drift per tick per dimension
# Cultural repulsion: CD outcome pushes wronged agent away, weighted by Neuroticism
#this was probably a stupid idea, disabled for now.
CULTURE_REPULSION_RATE = 0.00 # Max repulsion step per CD interaction
# Migration parameters
P_MIGRATION = 0.1 # Probability of migration from overpopulated cell
FEM_MIGRATION_RATIO = 0.3 # Female migration probability multiplier
P_MATE_SEEKING_MIGRATION = 0.20 # Base probability for unmarried males seeking mates
# Default board size and founder populations
DEFAULT_WIDTH = 10
DEFAULT_HEIGHT = 10
# Statistics logging
STATS_LOG_INTERVAL = 100 # Print stats every N ticks (0 to disable)
HIST_BINS = 10 # number of bins in histograms
def __init__(self, width: int, height: int, seed: Optional[int] = None):
self.width = width
self.height = height
self.tick = 0
if seed is not None:
random.seed(seed)
self.food: Dict[Tuple[int, int], float] = {}
for x in range(width):
for y in range(height):
self.food[(x, y)] = self.FOOD_CEILING
# Agent management
self._next_id = 0
self.agents: Dict[int, Agent] = {}
self.spatial_grid = SpatialGrid(width, height)
# Population counters: [male_count, female_count]
self._population = [0, 0]
# Per-cell PD outcome tracking: [cc, cd, dd] counts per tick
self.pd_games: Dict[Tuple[int, int], List[int]] = {}
for x in range(width):
for y in range(height):
self.pd_games[(x, y)] = [0, 0, 0]
# Dead agents storage for genealogical reconstruction
# Flat array of integers: [id, born, death_tick, parent0, parent1, ...]
# 5 integers per agent, optimized for memory in long simulations
self.dead_agents: List[int] = []
# Delta tracking: which entities have changed since last "mark_clean()"
self._next_world_id = 0
self._dirty_entities: Set[int] = set() # world_ids of modified entities
self._spawned_entities: Set[int] = set() # world_ids of new entities
self._despawn_notices: List[dict] = [] # death notices for removed entities
self._by_world_id: Dict[int, Any] = {} # world_id → entity lookup
# Map cells - created once, never despawn
self._cells: Dict[Tuple[int, int], Map] = {}
for x in range(width):
for y in range(height):
cell_world_id = self._allocate_world_id()
cell = Map(
world_id=cell_world_id,
x=x,
y=y,
pd=[0, 0, 0],
food=self.FOOD_CEILING
)
self._cells[(x, y)] = cell
self._by_world_id[cell_world_id] = cell
self._spawned_entities.add(cell_world_id)
# Prisoner's dilemma interaction history
# Key: (id1, id2) with id1 < id2 (normalized)
# Value: [recent1, recent2, n_pre, sum1_pre, sum2_pre]
# recent1/2: last 3 actions (oldest first), lists of up to 3 elements
# n_pre: count of turns before the last 3
# sum1/2_pre: cooperation sums for pre-history (avg = sum/n_pre)
self._interaction_history: Dict[Tuple[int, int], List] = {}
# Reverse index: agent_id -> set of (id1, id2) keys they participate in
self._interaction_index: Dict[int, Set[Tuple[int, int]]] = {}
# Per-tick statistics (reset each tick, accumulated for logging)
self._stats = {
'births': 0,
'deaths': 0,
'deaths_starvation': 0,
'deaths_accident': 0,
'matings_spousal': 0, # between existing spouses
'matings_unm': 0, # both unmarried (creates marriage)
'matings_adulterous': 0, # at least one already married to another
'matings_incestuous': 0, # kinship > 0.15
}
# Statistics histograms, set default maxima
self._hist_max = {
'age': 60, # initial defaults
'energy': self.MAX_ENERGY,
'kin': 20, # number of tracked kin relations
# Personality traits (OCEAN) - all 0-1 range
'o': 1.0, # Openness
'c': 1.0, # Conscientiousness
'e': 1.0, # Extraversion
'a': 1.0, # Agreeableness
'n': 1.0, # Neuroticism
# Other agent traits - all 0-1 range
'kin_trait': 1.0, # Kin altruism tendency
'xeno': 1.0, # Xenophilia/xenophobia
'hap': 1.0, # Happiness
'trust': 1.0, # Trust
# PD game scores (dynamic max)
'score': 30, # Initial estimate, will auto-adjust
}
self._histograms = {} # filled by _update_histograms
self._hist_tick = 0
self._tick_agent_scores = {} # Per-tick PD scores, reset each step
# How to report each property as histogram value
self.hist_value_getters = {
'age': lambda a: max(0, self._age_years(a)), # Clamp negative (unborn) to 0
'energy': lambda a: a.energy,
'kin': lambda a: len(a.kinship),
# Personality traits
'o': lambda a: a.o,
'c': lambda a: a.c,
'e': lambda a: a.e,
'a': lambda a: a.a,
'n': lambda a: a.n,
# Other traits
'kin_trait': lambda a: a.kin,
'xeno': lambda a: a.xeno,
'hap': lambda a: a.hap,
'trust': lambda a: a.trust,
# PD score (0 if not played this tick)
'score': lambda a: self._tick_agent_scores.get(a.id, 0),
}
# Simulation state
self.halted = False # Set to True when termination condition is met
self.halt_reason: Optional[str] = None # Why simulation halted
# Deferred command execution (for commands received during step())
self._stepping = False # True while inside step()
self._deferred_commands: List[Tuple[str, any]] = [] # Queue of (name, value) to execute after step
def _age_years(self, agent: Agent) -> float:
"""Calculate agent's age in years."""
return self.TICK_YEARS * (self.tick - agent.born)
def _metabolism_multiplier(self, agent: Agent) -> float:
"""
Calculate metabolism/eating rate multiplier based on age, sex, and pregnancy.
Returns 0 for unborn agents (their consumption is in mother's pregnancy multiplier).
Multipliers (cumulative):
- Age 0 to ADULTHOOD: 0.5 to 1.0 (linear)
- Age > SENESCENCE: 0.8
- Male: 1.3
- Pregnant: 1.2
"""
age = self._age_years(agent)
# Unborn agents don't consume
if age < 0:
return 0.0
# Base age multiplier
if age < self.ADULTHOOD:
# Linear interpolation from 0.5 at age 0 to 1.0 at ADULTHOOD
age_mult = 0.5 + 0.5 * (age / self.ADULTHOOD)
elif age > self.SENESCENCE:
age_mult = 0.8
else:
age_mult = 1.0
# Sex multiplier (male = 1.3)
sex_mult = 1.3 if agent.sex == 0 else 1.0
# Pregnancy multiplier
preg_mult = 1.2 if agent.pregnant else 1.0
return age_mult * sex_mult * preg_mult
# =========================================================================
# PRISONER'S DILEMMA GAME
# =========================================================================
def _decide(self, own: Agent, opp: Agent, history: List, n_pre: int, kinship: float, distance: float, cultural_distance: float) -> int:
"""
Decide whether to cooperate (1) or defect (0) in prisoner's dilemma.
Delegates to decide_module.decide() which computes cooperation probability
based on personality traits, history, kinship, and genetic distance.
Args:
own: The agent making the decision
opp: The opponent agent
history: [
[own_t-1, own_t-2, own_t-3], # own recent actions (most recent first)
[opp_t-1, opp_t-2, opp_t-3], # opponent recent actions (most recent first)
[own_avg, opp_avg] # pre-history averages, or []
]
n_pre: Number of interactions before the last 3 (relationship duration)
kinship: Relatedness coefficient between agents
distance: Squared Euclidean genetic distance
cultural_distance: Squared Euclidean cultural distance
Returns:
1 for cooperate, 0 for defect
"""
return decide_module.decide(own, opp, history, n_pre, kinship, distance)
#optimized version
def _decide_fast(self, own: Agent, opp: Agent, history: List, n_pre: int, kinship: float, distance: float, cultural_distance: float) -> int:
flat = decide_module.agent_to_flat(own, history, n_pre)
return 1 if random.random() < decide_module.compute_coop_prob_fast(*flat, kinship, distance) else 0
def _decide_cython(self, own: Agent, opp: Agent, history: List, n_pre: int, kinship: float, distance: float, cultural_distance: float) -> int:
own_history = history[0] if len(history) > 0 else []
opp_history = history[1] if len(history) > 1 else []
pre_history = history[2] if len(history) > 2 else []
own_h0 = own_history[0] if len(own_history) > 0 else -1
own_h1 = own_history[1] if len(own_history) > 1 else -1
own_h2 = own_history[2] if len(own_history) > 2 else -1
opp_h0 = opp_history[0] if len(opp_history) > 0 else -1
opp_h1 = opp_history[1] if len(opp_history) > 1 else -1
opp_h2 = opp_history[2] if len(opp_history) > 2 else -1
own_avg = pre_history[0] if len(pre_history) > 0 else -1.0
opp_avg = pre_history[1] if len(pre_history) > 1 else -1.0
#update to iclude own.sex, opp.sex !
return decide_module.decide_cython(
own.o, own.c, own.e, own.a, own.n,
own.kin, own.xeno,
own.hap, own.trust,
own_h0, own_h1, own_h2,
opp_h0, opp_h1, opp_h2,
own_avg, opp_avg,
n_pre,
kinship, distance, cultural_distance,
own.sex, opp.sex,
self._age_years(own), self._age_years(opp),
random.random(),
sigmoid_mode=0
)
def _genetic_distance(self, a1: Agent, a2: Agent) -> float:
"""Squared Euclidean distance between agents' genes arrays."""
return sum((g1 - g2) ** 2 for g1, g2 in zip(a1.genes, a2.genes))
def _cultural_distance(self, a1: Agent, a2: Agent) -> float:
"""Squared Euclidean cultural distance between agents' culture arrays."""
return sum((g1 - g2) ** 2 for g1, g2 in zip(a1.culture, a2.culture))
def _assimilate_culture(self, agent: Agent, other: Agent, rate_mult: float = 1.0):
"""
Move agent's culture toward other's culture.
Args:
agent: The agent whose culture is being modified
other: The agent whose culture is being assimilated toward
rate_mult: External multiplier for assimilation rate
Trait effects:
- Agreeableness: increases rate (accommodating)
- Female sex: 2x multiplier (cultural enforcers/transmitters)
- Age: younger = more malleable; no assimilation toward children
- Extraversion: decreases rate (comfortable with diversity)
- Neuroticism: decreases rate past distance threshold (culture shock)
- Conscientiousness: increases rate for spousal interaction only
Constraints:
- Culture values clamped to [0, 10]
- Maximum step capped at CULTURE_MAX_STEP Euclidean distance
"""
agent_age = self._age_years(agent)
other_age = self._age_years(other)
# No assimilation toward children - adults don't learn culture from kids
if other_age < self.ADOLESCENCE:
return
# Calculate cultural distance for neuroticism threshold
cultural_dist_sq = self._cultural_distance(agent, other)
# Base rate
rate = self.CULTURE_ASSIMILATION_RATE * rate_mult
# Agreeableness: increases rate
rate *= agent.a
# Female multiplier
if agent.sex == 1:
rate *= self.FEMALE_CULTURE_MULT
# Age-based malleability: full until ADULTHOOD, then linear decay to 0.3 at SENESCENCE
if agent_age < self.ADULTHOOD:
age_mult = 1.0
elif agent_age < self.SENESCENCE:
decay = 0.7 * (agent_age - self.ADULTHOOD) / (self.SENESCENCE - self.ADULTHOOD)
age_mult = 1.0 - decay
else:
age_mult = 0.3 # Floor for elderly
rate *= age_mult
#Teenage subcultures:
if agent_age < self.ADULTHOOD and other_age < self.ADULTHOOD:
rate *= 2.0
else:
# Age difference: younger learns more from older (+2% per year, capped)
age_diff = other_age - agent_age
diff_mult = max(0.5, min(1.5, 1.0 + 0.02 * age_diff))
rate *= diff_mult
# Extraversion dampening: extroverts don't need cultural alignment
rate *= (1.0 - agent.e * self.CULTURE_EXTRAVERSION_DAMP)
# Neuroticism culture shock: resistance past threshold
if cultural_dist_sq > self.CULTURE_SHOCK_THRESHOLD:
rate *= (1.0 - agent.n * self.CULTURE_NEUROTICISM_DAMP)
# Conscientiousness bonus for spousal assimilation only
if agent.spouse == other.id:
rate *= (1.0 + agent.c * self.CULTURE_SPOUSAL_C_BONUS)
# Calculate proposed deltas
deltas = [rate * (other.culture[i] - agent.culture[i]) for i in range(len(agent.culture))]
# Cap step at CULTURE_MAX_STEP Euclidean distance
step_dist = math.sqrt(sum(d * d for d in deltas))
if step_dist > self.CULTURE_MAX_STEP:
scale = self.CULTURE_MAX_STEP / step_dist
deltas = [d * scale for d in deltas]
# Apply deltas and clamp to [0, 10]
for i in range(len(agent.culture)):
agent.culture[i] = max(0.0, min(10.0, agent.culture[i] + deltas[i]))
def _repel_culture(self, agent: Agent, betrayer: Agent):
"""
Move agent's culture away from betrayer's culture after being wronged in CD outcome.
Repulsion is weighted by agent's neuroticism (resentful, holds grudges).
Only applies to adults (children don't develop cultural grudges).
Args:
agent: The agent who cooperated but was betrayed
betrayer: The agent who defected
"""
agent_age = self._age_years(agent)
if agent_age < self.ADOLESCENCE:
return
# Repulsion rate scaled by neuroticism (disabled)
rate = self.CULTURE_REPULSION_RATE * agent.n
# Move away from betrayer (negative direction)
for i in range(len(agent.culture)):
delta = agent.culture[i] - betrayer.culture[i] # Direction away
# Normalize: if delta is 0, no movement; otherwise scale to rate
if abs(delta) > 0.001:
step = rate * (delta / abs(delta)) # ±rate based on direction
else:
# Cultures identical on this dimension - random direction
step = rate * (1 if random.random() > 0.5 else -1)
agent.culture[i] = max(0.0, min(10.0, agent.culture[i] + step))
def _drift_culture(self, agent: Agent):
"""
Apply random cultural drift, weighted by agent's openness.
Open agents are more exploratory and creative, leading to cultural innovation.
Only applies to adults (children's culture is shaped by others, not self-generated).
"""
agent_age = self._age_years(agent)
if agent_age < self.ADOLESCENCE:
return
# cultural drift triggered by openness
if random.random() < agent.o:
rate = self.CULTURE_DRIFT_RATE
#Teenagers drive cultural innovation
if agent_age < self.ADULTHOOD:
rate *= 2.5
for i in range(len(agent.culture)):
drift = random.gauss(0, rate)
agent.culture[i] = max(0.0, min(10.0, agent.culture[i] + drift))
def _get_history_for_decide(self, own_id: int, opp_id: int) -> Tuple[List, int]:
"""
Get interaction history formatted for decide() from own's perspective.
Returns:
(history, n_pre) where history is:
[
[own_t-1, own_t-2, own_t-3], # own's last 3 actions (most recent first)
[opp_t-1, opp_t-2, opp_t-3], # opponent's last 3 actions (most recent first)
[own_avg, opp_avg] # averages for turns before last 3, or []
]
and n_pre is the count of pre-history turns (relationship duration beyond last 3)
"""
key = (min(own_id, opp_id), max(own_id, opp_id))
if key not in self._interaction_history:
return [[], [], []], 0
# Storage format: [recent1, recent2, n_pre, sum1_pre, sum2_pre]
recent1, recent2, n_pre, sum1, sum2 = self._interaction_history[key]
# Determine which is own vs opp based on key ordering
if own_id < opp_id:
own_recent, opp_recent = recent1, recent2
own_sum, opp_sum = sum1, sum2
else:
own_recent, opp_recent = recent2, recent1
own_sum, opp_sum = sum2, sum1
if not own_recent:
return [[], [], []], 0
# Recent actions (reversed: most recent first)
own_recent_out = list(reversed(own_recent))
opp_recent_out = list(reversed(opp_recent))
# Pre-history averages
if n_pre > 0:
pre_avg = [own_sum / n_pre, opp_sum / n_pre]
else:
pre_avg = []
return [own_recent_out, opp_recent_out, pre_avg], n_pre
def _record_interaction(self, id1: int, id2: int, action1: int, action2: int):
"""
Record one turn of prisoner's dilemma interaction.
Storage format: [recent1, recent2, n_pre, sum1_pre, sum2_pre]
- recent1/2: last 3 actions (oldest first), lists of up to 3 elements
- n_pre: count of turns before the last 3
- sum1/2_pre: cooperation sums for pre-history (avg = sum/n_pre)
Args:
id1, id2: Agent IDs (order doesn't matter, will be normalized)
action1: id1's action (0=defect, 1=cooperate)
action2: id2's action
"""
# Normalize key so id1 < id2
if id1 > id2:
id1, id2 = id2, id1
action1, action2 = action2, action1
key = (id1, id2)
if key not in self._interaction_history:
# [recent1, recent2, n_pre, sum1_pre, sum2_pre]
self._interaction_history[key] = [[], [], 0, 0, 0]
# Update reverse index
self._interaction_index.setdefault(id1, set()).add(key)
self._interaction_index.setdefault(id2, set()).add(key)
entry = self._interaction_history[key]
recent1, recent2, n_pre, sum1, sum2 = entry
# If recent buffer is full, move oldest to pre-history
if len(recent1) == 3:
oldest1 = recent1.pop(0)
oldest2 = recent2.pop(0)
n_pre += 1
sum1 += oldest1
sum2 += oldest2
entry[2] = n_pre
entry[3] = sum1
entry[4] = sum2
# Append new actions
recent1.append(action1)
recent2.append(action2)
def _cleanup_interaction_history(self, agent_id: int):
"""Remove all interaction history entries for a dead agent."""
if agent_id not in self._interaction_index:
return
for key in list(self._interaction_index[agent_id]):
# Remove from main history
if key in self._interaction_history:
del self._interaction_history[key]
# Remove from other agent's index
other_id = key[0] if key[1] == agent_id else key[1]
if other_id in self._interaction_index:
self._interaction_index[other_id].discard(key)
del self._interaction_index[agent_id]
@classmethod
def create(cls, **kwargs) -> 'World':
"""
Create and initialize a world with agents.
This is the main entry point for creating a simulation world.
The server passes an opaque config dict - only this method knows
what parameters are valid and what they mean.
Arguments (all optional, with defaults):
width: World width in cells (default: 10)
height: World height in cells (default: 10)
initial_pairs: Number of breeding pairs to spawn (default: 1)
seed: Random seed for reproducibility (default: None)
needs to become versatile (specify not only number of breeding pairs, but also positions, properties, ...)
Returns:
Initialized World with agents spawned and dirty state cleared
"""
# Extract or use defaults
width = kwargs.get('width', cls.DEFAULT_WIDTH)
height = kwargs.get('height', cls.DEFAULT_HEIGHT)
seed = kwargs.get('seed', None)
initial_pairs = kwargs.get('initial_pairs', 1)
# Create the world
world = cls(width, height, seed=seed)
#for now ignore initial_pairs and set defaults here
male = world.spawn_agent(1, 1, 2, sex=0)
male = world.spawn_agent(1, 1, 2, sex=0)
female = world.spawn_agent(1, 1, 2, sex=1)
female = world.spawn_agent(1, 1, 2, sex=1)
female = world.spawn_agent(1, 1, 2, sex=1)
male = world.spawn_agent(8, 8, 2, sex=0)
male = world.spawn_agent(8, 8, 2, sex=0)
female = world.spawn_agent(8, 8, 2, sex=1)
female = world.spawn_agent(8, 8, 2, sex=1)
female = world.spawn_agent(8, 8, 2, sex=1)
# Clear dirty state so first delta is clean
world.mark_clean()
return world
def _allocate_id(self) -> int:
"""Get a unique agent ID. IDs are never reused (important for client sync)."""
agent_id = self._next_id
self._next_id += 1
return agent_id
def _allocate_world_id(self) -> int:
world_id = self._next_world_id
self._next_world_id +=1
return world_id
def spawn_agent(self, x: int, y: int, energy: float,
parent_ids: Tuple[int, int] = (-1, -1),
born_tick: int = -20,
_twin_of: Agent = None,
sex: Optional[int] = None) -> Agent:
"""
Create a new agent in the world.
Args:
x, y: Position (cell coordinates, integers)
energy: Initial energy
parent_ids: Tuple of parent IDs ((-1, -1) for founders)
born_tick: Tick when agent is "born" (default: current tick)
Set to future tick for gestation (agent exists but age < 0)
_twin_of: Internal - if set, this is a fraternal twin of the given agent
sex: Optional sex (0=male, 1=female). Random if not specified.
Returns:
The created Agent (primary twin if twins spawned)
Genetic inheritance (diploid for personality traits):
- Founders get homozygous defaults (variance = 0)
- Offspring inherit one allele from each parent (randomly chosen)
- Mutation applied to each inherited allele
- Phenotype = mean of two alleles
- Speciation genes remain haploid (simple averaging)
Sex is assigned randomly (50/50) unless specified.
Twins:
- P_ID_TWINS chance of identical twins (same genetics, kinship=1.0)
- P_FR_TWINS chance of fraternal twins (independent genetics, kinship=0.5)
"""
if born_tick is None:
born_tick = self.tick
agent_id = self._allocate_id()
world_id = self._allocate_world_id()
# Determine genetic parameters
parent1_id, parent2_id = parent_ids
parent1 = self.agents.get(parent1_id) if parent1_id >= 0 else None
parent2 = self.agents.get(parent2_id) if parent2_id >= 0 else None
if parent1 and parent2:
# Sexual reproduction with diploid inheritance
trait_sd = self.TRAIT_MUTATION_SD
gene_sd = self.GENE_MUTATION_SD
# Big Five personality traits (diploid)
o, vo = self._inherit_diploid(parent1.o, parent1.vo, parent2.o, parent2.vo, trait_sd)
c, vc = self._inherit_diploid(parent1.c, parent1.vc, parent2.c, parent2.vc, trait_sd)
e, ve = self._inherit_diploid(parent1.e, parent1.ve, parent2.e, parent2.ve, trait_sd)
a, va = self._inherit_diploid(parent1.a, parent1.va, parent2.a, parent2.va, trait_sd)
n, vn = self._inherit_diploid(parent1.n, parent1.vn, parent2.n, parent2.vn, trait_sd)
# Social traits (diploid)
kin_trait, vkin = self._inherit_diploid(parent1.kin, parent1.vkin, parent2.kin, parent2.vkin, trait_sd)
xeno, vxeno = self._inherit_diploid(parent1.xeno, parent1.vxeno, parent2.xeno, parent2.vxeno, trait_sd)
# Speciation genes: haploid (simple averaging + mutation)
genes = []
for i in range(3):
avg_gene = (parent1.genes[i] + parent2.genes[i]) / 2
genes.append(max(0.0, min(10.0, avg_gene + random.gauss(0, gene_sd))))
# Culture: cloned from mother (parent2)
culture = list(parent2.culture)
else:
# Founder defaults (homozygous: variance = 0)
genes = [5.0 + 3 * (1 if x < 5 else -1),
5.0 + 3 * (1 if y < 5 else -1),
5.0]
o = c = e = a = n = 0.5
vo = vc = ve = va = vn = 0.1
kin_trait = 0.6
xeno = 0.6
vkin = vxeno = 0.05
# Founder culture: same pattern as genes
culture = [5.0 + 3 * (1 if x < 5 else -1),
5.0 + 3 * (1 if y < 5 else -1),
5.0]
if sex is None:
sex = random.randint(0, 1) # 0 = male, 1 = female
agent = Agent(
world_id=world_id,
id=agent_id,
x=int(x),
y=int(y),
energy=energy,
sex=sex,
born=born_tick,
parent=list(parent_ids),
offspring=[],
o=o, vo=vo,
c=c, vc=vc,
e=e, ve=ve,
a=a, va=va,
n=n, vn=vn,
kin=kin_trait, vkin=vkin,
xeno=xeno, vxeno=vxeno,
genes=genes,
culture=culture,
)
self.agents[agent_id] = agent
self._by_world_id[agent.world_id] = agent
self.spatial_grid.add(agent_id, x, y)
self._spawned_entities.add(world_id)
self._dirty_entities.add(world_id)
self._population[sex] += 1
# Record this agent as offspring of both parents and establish kinship
if parent1 and parent2:
parent1.offspring.append(agent_id)
parent2.offspring.append(agent_id)
self._establish_kinship(agent, parent1, parent2)
# Handle fraternal twin kinship (sibling relationship already established)
if _twin_of is not None:
# Fraternal twin - kinship 0.5 (full sibling)
agent.kinship[_twin_of.id] = 0.5
_twin_of.kinship[agent.id] = 0.5
# Check for twins (only for non-founders and not already a twin spawn)
if parent1 and parent2 and _twin_of is None:
twin_roll = random.random()
if twin_roll < self.P_ID_TWINS:
# Identical twin - clone with same genetics
twin_id = self._allocate_id()