-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsim_debug.py
More file actions
2060 lines (1720 loc) · 82.8 KB
/
Copy pathsim_debug.py
File metadata and controls
2060 lines (1720 loc) · 82.8 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 as decide_module
TWOPI = 2 * math.pi
@dataclass
class Agent:
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
valence: float = 0.0
arousal: float = 0.0
trust: float = 0.0
# 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])
@property
def cell(self) -> Tuple[int, int]:
"""Current cell for food/interactions (floor of position)"""
return (int(self.x), int(self.y))
# Class-level definition of phenotype fields (sent in streaming)
# Everything else is "internal" (only sent on inspect)
PHENOTYPE_FIELDS = ('id', 'x', '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.
"""
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,
'x': self.x,
'y': self.y,
'energy': round(self.energy, 2),
'genes': [round(g, 2) for g in self.genes],
}
def to_full_dict(self) -> dict:
"""
Complete state - only sent on inspect request.
Includes phenotype + internal state + genetics.
"""
return {
'id': self.id,
'sex': self.sex,
'born': self.born,
'x': self.x,
'y': self.y,
'energy': round(self.energy, 2),
'valence': round(self.valence, 2),
'arousal': round(self.arousal, 2),
'trust': round(self.trust, 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),
'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),
'genes': [round(g, 2) for g in self.genes],
'kinship': {k: round(v, 3) for k, v in self.kinship.items()},
'n_kin': len(self.kinship),
}
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 = 1.0
FOOD_CEILING = 2.0
SEASON_STRENGTH = 0.7
INITIAL_ENERGY = 2.0
METABOLISM_COST = 0.05
MAX_ENERGY = 10.0
REPRODUCTION_THRESHOLD = 5.0
REPRODUCTION_COST = 2.0
MALE_INVESTMENT = 0.2
EAT_RATE = 1.0 # DEPRECATED - food distribution now handled via PD game
INFANCY = 3
CHILDHOOD = 7
ADOLESCENCE = 14
ADULTHOOD = 21
MENOPAUSE = 44
SENESCENCE = 60
SENESCENCE_DEATH_RATE = 0.005 # Per-tick death probability = (age - SENESCENCE) * this (~2%/year)
GESTATION_TICKS = 3 # int(0.75 / TICK_YEARS) - 9 months gestation
# Twin probabilities
P_ID_TWINS = 0.005 # Identical twins (0.5%)
P_FR_TWINS = 0.015 # Fraternal twins (1.5%)
# Mutation rates for genetic parameters
GENE_MUTATION_SD = 0.1
TRAIT_MUTATION_SD = 0.1
# Kinship tracking threshold (cousin-tier = 0.125, half-cousin = 0.0625)
RELATEDNESS_THRESHOLD = 0.0625
# Mate selection: strong suppression above this kinship (cousin = 0.125)
CONSANGUINITY_TOLERANCE = 0.15
# Migration parameters
P_MIGRATION = 0.1 # Probability of migration from overpopulated cell
FEM_MIGRATION_RATIO = 0.5 # Female migration probability multiplier
# Default board size and founder populations
DEFAULT_WIDTH = 100
DEFAULT_HEIGHT = 100
# Statistics logging
STATS_LOG_INTERVAL = 10 # 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)
# Delta tracking: which agents have changed since last "mark_clean()"
self._dirty_agents: Set[int] = set()
self._spawned_agents: Set[int] = set() # new since last clean
self._despawned_agents: Set[int] = set() # removed since last clean
self._mated_this_tick: Set[int] = set() # agents who have mated this tick
# 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,
}
# Statistics histograms, set default maxima
self._hist_max = {
'age': 60, # initial defaults
'energy': self.MAX_ENERGY,
'kin': 20, # number of tracked kin relations
}
self._histograms = {} # filled by _update_histograms
self._hist_tick = 0
# 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),
}
# 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) -> 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
Returns:
1 for cooperate, 0 for defect
"""
return decide_module.decide(own, opp, history, n_pre, kinship, distance)
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 _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)
Returns:
Initialized World with agents spawned and dirty state cleared
"""
# Extract and apply 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)
# Spawn initial breeding pairs (male + female per cell)
for _ in range(initial_pairs):
# Pick a random cell
cell_x = random.randint(0, width - 1)
cell_y = random.randint(0, height - 1)
# Spawn male in cell
male = world.spawn_agent(cell_x, cell_y, cls.INITIAL_ENERGY)
male.sex = 0
# Spawn female in same cell
female = world.spawn_agent(cell_x, cell_y, cls.INITIAL_ENERGY)
female.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 spawn_agent(self, x: int, y: int, energy: float,
parent_ids: Tuple[int, int] = (-1, -1),
born_tick: int = None,
_twin_of: Agent = 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
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).
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()
# 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))))
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 + 2 * (1 if x < 5 else -1)]
o = c = e = a = n = 0.5
vo = vc = ve = va = vn = 0.0
kin_trait = xeno = 0.5
vkin = vxeno = 0.0
sex = random.randint(0, 1) # 0 = male, 1 = female
agent = Agent(
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,
)
self.agents[agent_id] = agent
self.spatial_grid.add(agent_id, x, y)
self._spawned_agents.add(agent_id)
self._dirty_agents.add(agent_id)
# 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()
twin = Agent(
id=twin_id,
x=int(x),
y=int(y),
energy=energy,
sex=sex, # Same 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=list(genes), # Copy the list
)
self.agents[twin_id] = twin
self.spatial_grid.add(twin_id, x, y)
self._spawned_agents.add(twin_id)
self._dirty_agents.add(twin_id)
parent1.offspring.append(twin_id)
parent2.offspring.append(twin_id)
self._establish_kinship(twin, parent1, parent2)
# Identical twins have kinship 1.0
agent.kinship[twin_id] = 1.0
twin.kinship[agent_id] = 1.0
elif twin_roll < self.P_ID_TWINS + self.P_FR_TWINS:
# Fraternal twin - independent genetics
self.spawn_agent(x, y, energy, parent_ids, born_tick, _twin_of=agent)
return agent
def _inherit_diploid(self, p1_pheno: float, p1_var: float,
p2_pheno: float, p2_var: float,
mutation_sd: float,
min_val: float = 0.0, max_val: float = 1.0) -> Tuple[float, float]:
"""
Diploid inheritance: each parent contributes one randomly-chosen allele.
Args:
p1_pheno, p1_var: Parent 1's phenotype and diploid variance
p2_pheno, p2_var: Parent 2's phenotype and diploid variance
mutation_sd: Standard deviation for mutation noise
min_val, max_val: Bounds for allele values
Returns:
(phenotype, variance) tuple for offspring
The two alleles are reconstructed as pheno ± var/2, then one is
randomly chosen from each parent, mutated, and combined.
"""
# Reconstruct alleles from phenotype ± variance/2
p1_hi, p1_lo = p1_pheno + p1_var / 2, p1_pheno - p1_var / 2
p2_hi, p2_lo = p2_pheno + p2_var / 2, p2_pheno - p2_var / 2
# Each parent contributes one allele (with mutation)
from_p1 = (p1_hi if random.random() < 0.5 else p1_lo) + random.gauss(0, mutation_sd)
from_p2 = (p2_hi if random.random() < 0.5 else p2_lo) + random.gauss(0, mutation_sd)
# Clamp alleles before combining
from_p1 = max(min_val, min(max_val, from_p1))
from_p2 = max(min_val, min(max_val, from_p2))
phenotype = (from_p1 + from_p2) / 2
variance = abs(from_p1 - from_p2)
return phenotype, variance
def _establish_kinship(self, child: Agent, parent1: Agent, parent2: Agent):
"""
Calculate and store kinship relations for a newborn.
Simplified "known kinship" model:
- Parents are always r=0.5 to child
- Full siblings are always r=0.5 to child
- Inherit from parents' kinship at half the value
- Only propagate entries > 2×threshold (so halved value meets threshold)
- For shared relatives: use min(1.2 * max, sum) to recognize some
consanguinity while still enforcing decay over ~3 generations
This gives: parent=0.5, full sibling=0.5, grandparent=0.25, half-sibling≥0.25
Relations are stored bidirectionally and pruned below RELATEDNESS_THRESHOLD.
"""
threshold = self.RELATEDNESS_THRESHOLD
inherit_threshold = 2 * threshold # 0.125 - only propagate if half will meet threshold
new_kin = {}
# Parents always at 0.5
new_kin[parent1.id] = 0.5
new_kin[parent2.id] = 0.5
# Child's parent set for sibling detection
child_parents = {parent1.id, parent2.id}
# Collect contributions from both parents
contributions = {} # x_id -> [r_from_p1/2, r_from_p2/2]
for x_id, r_p1 in parent1.kinship.items():
if x_id == parent2.id:
continue
if r_p1 > inherit_threshold:
contributions[x_id] = [r_p1 / 2, 0]
for x_id, r_p2 in parent2.kinship.items():
if x_id == parent1.id:
continue
if r_p2 > inherit_threshold:
if x_id in contributions:
contributions[x_id][1] = r_p2 / 2
else:
contributions[x_id] = [0, r_p2 / 2]
# Combine contributions: min(1.2 * max, sum) for consanguinity with decay
for x_id, (c1, c2) in contributions.items():
# Check if X is a full sibling (same parents as child)
if x_id in self.agents:
x_agent = self.agents[x_id]
x_parents = {x_agent.parent[0], x_agent.parent[1]}
if x_parents == child_parents:
new_kin[x_id] = 0.5 # Full sibling override
continue
if c1 > 0 and c2 > 0:
# Both parents related to X - use capped formula
new_kin[x_id] = min(1.2 * max(c1, c2), c1 + c2)
else:
# Only one parent related
new_kin[x_id] = c1 + c2
# Store in child and update relatives' records (bidirectional)
for x_id, r in new_kin.items():
if r >= threshold:
child.kinship[x_id] = r
if x_id in self.agents:
self.agents[x_id].kinship[child.id] = r
def remove_agent(self, agent_id: int):
"""Remove an agent from the world and clean up kinship records.
If the agent is a mother, all her dependent children die too:
- Unborn (age < 0): fetus cannot survive without mother
- Infants (0 <= age <= INFANCY): too young to survive independently
"""
if agent_id in self.agents:
agent = self.agents[agent_id]
# If mother dies, kill dependent children (unborn + infants)
if agent.sex == 1: # Female
dependents_to_kill = []
for child_id in agent.offspring:
child = self.agents.get(child_id)
if child:
child_age = self._age_years(child)
if child_age <= self.INFANCY: # Includes unborn (age < 0)
dependents_to_kill.append(child_id)
# Kill dependents (recursively calls remove_agent)
for dependent_id in dependents_to_kill:
if dependent_id in self.agents: # May already be removed
self.remove_agent(dependent_id)
self._stats['deaths'] += 1
# Check agent still exists (may have been removed as infant of another dying mother)
if agent_id not in self.agents:
return
# Remove from relatives' kinship dicts
for relative_id in agent.kinship:
if relative_id in self.agents:
self.agents[relative_id].kinship.pop(agent_id, None)
# Clean up interaction history
self._cleanup_interaction_history(agent_id)
# Remove from spatial grid and tracking
self.spatial_grid.remove(agent_id, agent.x, agent.y)
del self.agents[agent_id]
self._despawned_agents.add(agent_id)
self._dirty_agents.discard(agent_id)
self._spawned_agents.discard(agent_id)
def _mark_dirty(self, agent_id: int):
"""Mark an agent as modified (for delta updates)."""
self._dirty_agents.add(agent_id)
def get_dirty_state(self) -> dict:
"""
Get all changes since last mark_clean().
This is what we'll send to clients as delta updates.
Uses to_display_dict() for phenotype-only data (efficient streaming).
Full agent data is available via inspect command.
"""
return {
'tick': self.tick,
'spawned': [self.agents[aid].to_display_dict() for aid in self._spawned_agents if aid in self.agents],
'updated': [self.agents[aid].to_display_dict() for aid in self._dirty_agents - self._spawned_agents if aid in self.agents],
'despawned': list(self._despawned_agents)
}
def get_dirty_ids(self) -> dict:
"""
Get just the IDs of changed agents (no data copying).
Much more efficient for streaming - actual data fetched lazily at send time.
"""
return {
'tick': self.tick,
'spawned_ids': list(self._spawned_agents),
'updated_ids': list(self._dirty_agents - self._spawned_agents),
'despawned_ids': list(self._despawned_agents)
}
def get_full_state(self) -> dict:
"""
Get complete world state (for initial sync or reconnection).
Map cells are returned as entities alongside agents, with map=1.
This unified approach allows the same streaming infrastructure to handle
both agents and map data.
"""
# Agents as entities (display dict only for streaming efficiency)
agent_entities = [a.to_display_dict() for a in self.agents.values()]
# Map cells as entities (map=1 indicates map cell)
cell_entities = [
{
'id': -(x * self.height + y + 1), # Negative IDs for cells
'map': 1,
'x': x,
'y': y,
'food': round(self.food[(x, y)], 2),
}
for x in range(self.width)
for y in range(self.height)
]
return {
'tick': self.tick,
'width': self.width,
'height': self.height,
'agents': agent_entities,
'cells': cell_entities,
'total_entities': len(agent_entities) + len(cell_entities)
}
def describe_map(self) -> List[List[int]]:
"""
Get static map data for initial transmission to client.
Returns:
List of [x, y, biome] for all cells where biome != 0
-- not implemented, just return empty list
"""
return []
def mark_clean(self):
"""Clear dirty tracking (call after sending delta to clients)."""
self._dirty_agents.clear()
self._spawned_agents.clear()
self._despawned_agents.clear()
def inspect_agent(self, agent_id: int) -> Optional[dict]:
"""
Get full state of a specific agent (for inspect command).
Returns None if agent doesn't exist.
"""
if agent_id in self.agents:
return self.agents[agent_id].to_full_dict()
return None
@staticmethod
def distance(p1, p2) -> float:
"""
Distance between two positions in the simulation's topology.
Args:
p1: First position (tuple/list of coordinates)
p2: Second position (tuple/list of coordinates)
Returns:
Distance as a float
Placeholder, currently unused, just return Chebyshev distance (L∞ norm).
"""
return max(abs(a - b) for a, b in zip(p1, p2))
@staticmethod
def is_in_viewport(position, center, radius) -> bool:
"""
Check if a position is within a viewport.
This is simulation-specific - defines what "within radius" means
for this simulation's topology.
Args:
position: Agent's position (tuple/list)
center: Viewport center (tuple/list)
radius: Viewport radius (float)
Returns:
True if position is within viewport
"""
return World.distance(position, center) <= radius
def get_viewport(self, center, radius) -> dict:
"""
Get all entities (agents and map cells) within a viewport region.
This is the simulation's implementation of viewport queries.
The server calls this without knowing the topology details.
Args:
center: Viewport center position (tuple/list of coordinates)
radius: Viewport radius
Returns:
{
'tick': current tick,
'center': center position as list,
'radius': radius,
'agents': list of entity dicts (agents + cells),
'count': number of entities
}
"Entities" are agents and map cells
"""
entities = []
# Add agents in viewport
for agent in self.agents.values():
if self.is_in_viewport(agent.position, center, radius):
entities.append(agent.to_viewport_dict())
# Add map cells in viewport
for (x, y), food in self.food.items():
if self.is_in_viewport((x, y), center, radius):
entities.append({
'id': -(x * self.height + y + 1), # Negative IDs for cells
'map': 1, # CELL type
'x': x,
'y': y,
'food': round(food, 2)
})
return {
'tick': self.tick,
'center': list(center),
'radius': radius,
'agents': entities, # Named 'agents', as in, we treat cells as generalized "agents"
'count': len(entities)
}
def _move_agent(self, agent: Agent, new_x: int, new_y: int) -> bool:
"""
Move an agent to a new position.
Returns:
True if move succeeded, False if blocked (out of bounds)
"""
if new_x == agent.x and new_y == agent.y:
return True
# Clamp to world bounds
new_x = max(0, min(self.width - 1, new_x))