-
Notifications
You must be signed in to change notification settings - Fork 12
/
sugarscape.py
1469 lines (1347 loc) · 77.2 KB
/
sugarscape.py
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
#! /usr/bin/python
import agent
import cell
import disease
import environment
import ethics
import getopt
import hashlib
import json
import math
import random
import sys
class Sugarscape:
def __init__(self, configuration):
self.agentConfigHashes = None
self.diseaseConfigHashes = None
self.configuration = configuration
self.maxTimestep = configuration["timesteps"]
self.timestep = 0
self.nextAgentID = 0
self.nextDiseaseID = 0
environmentConfiguration = {"equator": configuration["environmentEquator"],
"globalMaxSpice": configuration["environmentMaxSpice"],
"globalMaxSugar": configuration["environmentMaxSugar"],
"maxCombatLoot": configuration["environmentMaxCombatLoot"],
"neighborhoodMode": configuration["neighborhoodMode"],
"pollutionDiffusionDelay": configuration["environmentPollutionDiffusionDelay"],
"pollutionDiffusionTimeframe": configuration["environmentPollutionDiffusionTimeframe"],
"pollutionTimeframe": configuration["environmentPollutionTimeframe"],
"seasonalGrowbackDelay": configuration["environmentSeasonalGrowbackDelay"],
"seasonInterval": configuration["environmentSeasonInterval"],
"spiceConsumptionPollutionFactor": configuration["environmentSpiceConsumptionPollutionFactor"],
"spiceProductionPollutionFactor": configuration["environmentSpiceProductionPollutionFactor"],
"spiceRegrowRate": configuration["environmentSpiceRegrowRate"],
"sugarConsumptionPollutionFactor": configuration["environmentSugarConsumptionPollutionFactor"],
"sugarProductionPollutionFactor": configuration["environmentSugarProductionPollutionFactor"],
"sugarRegrowRate": configuration["environmentSugarRegrowRate"],
"sugarscapeSeed": configuration["seed"],
"universalSpiceIncomeInterval": configuration["environmentUniversalSpiceIncomeInterval"],
"universalSugarIncomeInterval": configuration["environmentUniversalSugarIncomeInterval"],
"wraparound": configuration["environmentWraparound"]}
self.seed = configuration["seed"]
self.environment = environment.Environment(configuration["environmentHeight"], configuration["environmentWidth"], self, environmentConfiguration)
self.environmentHeight = configuration["environmentHeight"]
self.environmentWidth = configuration["environmentWidth"]
self.configureEnvironment(configuration["environmentMaxSugar"], configuration["environmentMaxSpice"], configuration["environmentSugarPeaks"], configuration["environmentSpicePeaks"])
self.debug = configuration["debugMode"]
self.keepAlive = configuration["keepAlivePostExtinction"]
self.agents = []
self.replacedAgents = []
self.bornAgents = []
self.deadAgents = []
self.diseases = []
self.activeQuadrants = self.findActiveQuadrants()
self.configureAgents(configuration["startingAgents"])
self.configureDiseases(configuration["startingDiseases"])
self.gui = gui.GUI(self, self.configuration["interfaceHeight"], self.configuration["interfaceWidth"]) if configuration["headlessMode"] == False else None
self.run = False # Simulation start flag
self.end = False # Simulation end flag
# TODO: Remove redundant metrics
# TODO: Streamline naming
self.runtimeStats = {"timestep": 0, "population": 0, "meanMetabolism": 0, "meanMovement": 0, "meanVision": 0, "meanWealth": 0, "meanAge": 0, "giniCoefficient": 0,
"meanTradePrice": 0, "tradeVolume": 0, "maxWealth": 0, "minWealth": 0, "meanHappiness": 0, "meanWealthHappiness": 0, "meanHealthHappiness": 0,
"meanSocialHappiness": 0, "meanFamilyHappiness": 0, "meanConflictHappiness": 0, "meanAgeAtDeath": 0, "seed": self.seed, "agentsReplaced": 0,
"agentsBorn": 0, "agentStarvationDeaths": 0, "agentDiseaseDeaths": 0, "environmentWealthCreated": 0, "agentWealthTotal": 0,
"environmentWealthTotal": 0, "agentWealthCollected": 0, "agentWealthBurnRate": 0, "agentMeanTimeToLive": 0, "agentTotalMetabolism": 0,
"agentCombatDeaths": 0, "agentAgingDeaths": 0, "agentDeaths": 0, "largestTribe": 0, "largestTribeSize": 0,
"remainingTribes": self.configuration["environmentMaxTribes"], "sickAgents": 0, "carryingCapacity": 0}
self.graphStats = {"ageBins": [], "sugarBins": [], "spiceBins": [], "lorenzCurvePoints": [], "meanTribeTags": [],
"maxSugar": 0, "maxSpice": 0, "maxWealth": 0}
self.log = open(configuration["logfile"], 'a') if configuration["logfile"] != None else None
self.logFormat = configuration["logfileFormat"]
self.experimentalGroup = configuration["experimentalGroup"]
if self.experimentalGroup != None:
# Convert keys to Pythonic case scheme and initialize values
groupRuntimeStats = {}
for key in self.runtimeStats.keys():
controlGroupKey = "control" + key[0].upper() + key[1:]
experimentalGroupKey = self.experimentalGroup + key[0].upper() + key[1:]
groupRuntimeStats[controlGroupKey] = 0
groupRuntimeStats[experimentalGroupKey] = 0
self.runtimeStats.update(groupRuntimeStats)
def addAgent(self, agent):
self.bornAgents.append(agent)
self.agents.append(agent)
def addSpicePeak(self, startX, startY, radius, maxSpice):
height = self.environment.height
width = self.environment.width
radialDispersion = math.sqrt(max(startX, width - startX)**2 + max(startY, height - startY)**2) * (radius / width)
for i in range(width):
for j in range(height):
euclideanDistanceToStart = math.sqrt((startX - i)**2 + (startY - j)**2)
currDispersion = 1 + maxSpice * (1 - euclideanDistanceToStart / radialDispersion)
cellMaxCapacity = min(currDispersion, maxSpice)
cellMaxCapacity = math.ceil(cellMaxCapacity)
if cellMaxCapacity > self.environment.findCell(i, j).maxSpice:
self.environment.findCell(i, j).maxSpice = cellMaxCapacity
self.environment.findCell(i, j).spice = cellMaxCapacity
def addSugarPeak(self, startX, startY, radius, maxSugar):
height = self.environment.height
width = self.environment.width
radialDispersion = math.sqrt(max(startX, width - startX)**2 + max(startY, height - startY)**2) * (radius / width)
for i in range(width):
for j in range(height):
euclideanDistanceToStart = math.sqrt((startX - i)**2 + (startY - j)**2)
currDispersion = 1 + maxSugar * (1 - euclideanDistanceToStart / radialDispersion)
cellMaxCapacity = min(currDispersion, maxSugar)
cellMaxCapacity = math.ceil(cellMaxCapacity)
if cellMaxCapacity > self.environment.findCell(i, j).maxSugar:
self.environment.findCell(i, j).maxSugar = cellMaxCapacity
self.environment.findCell(i, j).sugar = cellMaxCapacity
def configureAgents(self, numAgents):
if self.environment == None:
return
emptyCells = [[cell for cell in quadrant if cell.agent == None] for quadrant in self.activeQuadrants]
totalCells = sum(len(quadrant) for quadrant in emptyCells)
quadrants = len(emptyCells)
if totalCells == 0:
return
if numAgents > totalCells:
if "all" in self.debug or "sugarscape" in self.debug:
print(f"Could not allocate {numAgents} agents. Allocating maximum of {totalCells}.")
numAgents = totalCells
# Ensure agent endowments are randomized across initial agent count to make replacements follow same distributions
agentEndowments = self.randomizeAgentEndowments(numAgents)
for quadrant in emptyCells:
random.shuffle(quadrant)
quadrantIndices = [i for i in range(quadrants)]
random.shuffle(quadrantIndices)
for i in range(numAgents):
quadrantIndex = quadrantIndices[i % quadrants]
randomCell = emptyCells[quadrantIndex].pop()
agentConfiguration = agentEndowments[i]
agentID = self.generateAgentID()
a = agent.Agent(agentID, self.timestep, randomCell, agentConfiguration)
# If using a different decision model, replace new agent with instance of child class
if "altruist" in agentConfiguration["decisionModel"]:
a = ethics.Bentham(agentID, self.timestep, randomCell, agentConfiguration)
a.selfishnessFactor = 0
elif "bentham" in agentConfiguration["decisionModel"]:
a = ethics.Bentham(agentID, self.timestep, randomCell, agentConfiguration)
if agentConfiguration["selfishnessFactor"] < 0:
a.selfishnessFactor = 0.5
elif "egoist" in agentConfiguration["decisionModel"]:
a = ethics.Bentham(agentID, self.timestep, randomCell, agentConfiguration)
a.selfishnessFactor = 1
elif "negativeBentham" in agentConfiguration["decisionModel"]:
a = ethics.Bentham(agentID, self.timestep, randomCell, agentConfiguration)
a.selfishnessFactor = -1
if "NoLookahead" in agentConfiguration["decisionModel"]:
a.decisionModelLookaheadFactor = 0
elif "HalfLookahead" in agentConfiguration["decisionModel"]:
a.decisionModelLookaheadFactor = 0.5
if self.configuration["environmentTribePerQuadrant"] == True:
tribe = quadrantIndex
tags = self.generateTribeTags(tribe)
a.tags = tags
a.tribe = a.findTribe()
randomCell.agent = a
self.agents.append(a)
if self.timestep > 0:
self.replacedAgents.append(a)
for a in self.agents:
a.findCellsInRange()
a.findNeighborhood()
def configureDiseases(self, numDiseases):
numAgents = len(self.agents)
if numAgents == 0:
return
elif numAgents < numDiseases:
numDiseases = numAgents
diseaseEndowments = self.randomizeDiseaseEndowments(numDiseases)
random.shuffle(self.agents)
diseases = []
for i in range(numDiseases):
diseaseID = self.generateDiseaseID()
diseaseConfiguration = diseaseEndowments[i]
newDisease = disease.Disease(diseaseID, diseaseConfiguration)
diseases.append(newDisease)
startingDiseases = self.configuration["startingDiseasesPerAgent"]
minStartingDiseases = startingDiseases[0]
maxStartingDiseases = startingDiseases[1]
currStartingDiseases = minStartingDiseases
for agent in self.agents:
random.shuffle(diseases)
for newDisease in diseases:
if len(agent.diseases) >= currStartingDiseases and startingDiseases != [0, 0]:
currStartingDiseases += 1
break
hammingDistance = agent.findNearestHammingDistanceInDisease(newDisease)["distance"]
if hammingDistance == 0:
continue
agent.catchDisease(newDisease)
self.diseases.append(newDisease)
if startingDiseases == [0, 0]:
diseases.remove(newDisease)
break
if currStartingDiseases > maxStartingDiseases:
currStartingDiseases = minStartingDiseases
if startingDiseases == [0, 0] and len(diseases) > 0 and ("all" in self.debug or "sugarscape" in self.debug):
print(f"Could not place {len(diseases)} diseases.")
def configureEnvironment(self, maxSugar, maxSpice, sugarPeaks, spicePeaks):
height = self.environment.height
width = self.environment.width
for i in range(width):
for j in range(height):
newCell = cell.Cell(i, j, self.environment)
self.environment.setCell(newCell, i, j)
sugarRadiusScale = 2
radius = math.ceil(math.sqrt(sugarRadiusScale * (height + width)))
for peak in sugarPeaks:
self.addSugarPeak(peak[0], peak[1], radius, maxSugar)
spiceRadiusScale = 2
radius = math.ceil(math.sqrt(spiceRadiusScale * (height + width)))
for peak in spicePeaks:
self.addSpicePeak(peak[0], peak[1], radius, maxSpice)
self.environment.findCellNeighbors()
self.environment.findCellRanges()
def doTimestep(self):
if self.timestep >= self.maxTimestep:
self.toggleEnd()
return
if "all" in self.debug or "sugarscape" in self.debug:
print(f"Timestep: {self.timestep}\nLiving Agents: {len(self.agents)}")
self.timestep += 1
if self.end == True or (len(self.agents) == 0 and self.keepAlive == False):
self.toggleEnd()
else:
self.environment.doTimestep(self.timestep)
random.shuffle(self.agents)
for agent in self.agents:
agent.doTimestep(self.timestep)
self.removeDeadAgents()
self.replaceDeadAgents()
self.updateRuntimeStats()
if self.gui != None:
self.updateGraphStats()
self.gui.doTimestep()
# If final timestep, do not write to log to cleanly close JSON array log structure
if self.timestep != self.maxTimestep and len(self.agents) > 0:
self.writeToLog()
def endLog(self):
if self.log == None:
return
# Update total wealth accumulation to include still living agents at simulation end
environmentWealthCreated = 0
environmentWealthTotal = 0
for i in range(self.environment.width):
for j in range(self.environment.height):
environmentWealthCreated += self.environment.grid[i][j].sugarLastProduced + self.environment.grid[i][j].spiceLastProduced
environmentWealthTotal += self.environment.grid[i][j].sugar + self.environment.grid[i][j].spice
self.runtimeStats["environmentWealthCreated"] = environmentWealthCreated
self.runtimeStats["environmentWealthTotal"] = environmentWealthTotal
logString = '\t' + json.dumps(self.runtimeStats) + "\n]"
if self.logFormat == "csv":
logString = ""
# Ensure consistent ordering for CSV format
for stat in sorted(self.runtimeStats):
if logString == "":
logString += f"{self.runtimeStats[stat]}"
else:
logString += f",{self.runtimeStats[stat]}"
logString += "\n"
self.log.write(logString)
self.log.flush()
self.log.close()
def endSimulation(self):
self.removeDeadAgents()
self.endLog()
if "all" in self.debug or "sugarscape" in self.debug:
print(str(self))
exit(0)
def findActiveQuadrants(self):
quadrants = self.configuration["environmentStartingQuadrants"]
cellRange = []
quadrantWidth = math.floor(self.environmentWidth / 2 * self.configuration["environmentQuadrantSizeFactor"])
quadrantHeight = math.floor(self.environmentHeight / 2 * self.configuration["environmentQuadrantSizeFactor"])
quadrantIndex = 0
# Quadrant I at origin in top left corner, other quadrants in clockwise order
if 1 in quadrants:
quadrantOne = [self.environment.grid[i][j] for j in range(quadrantHeight) for i in range(quadrantWidth)]
cellRange.append(quadrantOne)
quadrantIndex += 1
if 2 in quadrants:
quadrantTwo = [self.environment.grid[i][j] for j in range(quadrantHeight) for i in range(self.environmentWidth - quadrantWidth, self.environmentWidth)]
cellRange.append(quadrantTwo)
quadrantIndex += 1
if 3 in quadrants:
quadrantThree = [self.environment.grid[i][j] for j in range(self.environmentHeight - quadrantHeight, self.environmentHeight) for i in range(self.environmentWidth - quadrantWidth, self.environmentWidth)]
cellRange.append(quadrantThree)
quadrantIndex += 1
if 4 in quadrants:
quadrantFour = [self.environment.grid[i][j] for j in range(self.environmentHeight - quadrantHeight, self.environmentHeight) for i in range(quadrantWidth)]
cellRange.append(quadrantFour)
return cellRange
def generateAgentID(self):
agentID = self.nextAgentID
self.nextAgentID += 1
return agentID
def generateAgentTags(self, numAgents):
configs = self.configuration
if configs["agentTagStringLength"] == 0 or configs["environmentMaxTribes"] == 0 or self.configuration["environmentTribePerQuadrant"] == True:
return [None for i in range(numAgents)]
numTribes = configs["environmentMaxTribes"]
tagsEndowments = []
for i in range(numAgents):
currTribe = i % numTribes
tags = self.generateTribeTags(currTribe)
tagsEndowments.append(tags)
random.shuffle(tagsEndowments)
return tagsEndowments
def generateDiseaseID(self):
diseaseID = self.nextDiseaseID
self.nextDiseaseID += 1
return diseaseID
def generateTribeTags(self, tribe):
tagStringLength = self.configuration["agentTagStringLength"]
numTribes = self.configuration["environmentMaxTribes"]
tribeSize = (tagStringLength + 1) / numTribes
minZeroes = math.floor(tribe * tribeSize)
maxZeroes = math.floor((tribe + 1) * tribeSize) - 1
maxZeroes = min(maxZeroes, tagStringLength)
zeroes = random.randint(minZeroes, maxZeroes)
ones = tagStringLength - zeroes
tags = [0 for i in range(zeroes)] + [1 for i in range(ones)]
random.shuffle(tags)
return tags
def pauseSimulation(self):
while self.run == False:
if self.gui != None and self.end == False:
self.gui.window.update()
if self.end == True:
self.endSimulation()
def randomizeDiseaseEndowments(self, numDiseases):
configs = self.configuration
aggressionPenalty = configs["diseaseAggressionPenalty"]
fertilityPenalty = configs["diseaseFertilityPenalty"]
movementPenalty = configs["diseaseMovementPenalty"]
spiceMetabolismPenalty = configs["diseaseSpiceMetabolismPenalty"]
sugarMetabolismPenalty = configs["diseaseSugarMetabolismPenalty"]
tagLengths = configs["diseaseTagStringLength"]
visionPenalty = configs["diseaseVisionPenalty"]
minAggressionPenalty = aggressionPenalty[0]
minFertilityPenalty = fertilityPenalty[0]
minMovementPenalty = movementPenalty[0]
minSpiceMetabolismPenalty = spiceMetabolismPenalty[0]
minSugarMetabolismPenalty = sugarMetabolismPenalty[0]
minTagLength = tagLengths[0]
minVisionPenalty = visionPenalty[0]
maxAggressionPenalty = aggressionPenalty[1]
maxFertilityPenalty = fertilityPenalty[1]
maxMovementPenalty = movementPenalty[1]
maxSpiceMetabolismPenalty = spiceMetabolismPenalty[1]
maxSugarMetabolismPenalty = sugarMetabolismPenalty[1]
maxTagLength = tagLengths[1]
maxVisionPenalty = visionPenalty[1]
aggressionPenalties = []
diseaseTags = []
endowments = []
fertilityPenalties = []
movementPenalties = []
spiceMetabolismPenalties = []
sugarMetabolismPenalties = []
visionPenalties = []
currAggressionPenalty = minAggressionPenalty
currFertilityPenalty = minFertilityPenalty
currMovementPenalty = minMovementPenalty
currSugarMetabolismPenalty = minSugarMetabolismPenalty
currSpiceMetabolismPenalty = minSpiceMetabolismPenalty
currTagLength = minTagLength
currVisionPenalty = minVisionPenalty
for i in range(numDiseases):
aggressionPenalties.append(currAggressionPenalty)
diseaseTags.append([random.randrange(2) for i in range(currTagLength)])
fertilityPenalties.append(currFertilityPenalty)
movementPenalties.append(currMovementPenalty)
spiceMetabolismPenalties.append(currSpiceMetabolismPenalty)
sugarMetabolismPenalties.append(currSugarMetabolismPenalty)
visionPenalties.append(currVisionPenalty)
currAggressionPenalty += 1
currFertilityPenalty += 1
currMovementPenalty += 1
currSpiceMetabolismPenalty += 1
currSugarMetabolismPenalty += 1
currTagLength += 1
currVisionPenalty += 1
if currAggressionPenalty > maxAggressionPenalty:
currAggressionPenalty = minAggressionPenalty
if currFertilityPenalty > maxFertilityPenalty:
currFertilityPenalty = minFertilityPenalty
if currMovementPenalty > maxMovementPenalty:
currMovementPenalty = minMovementPenalty
if currSpiceMetabolismPenalty > maxSpiceMetabolismPenalty:
currSpiceMetabolismPenalty = minSpiceMetabolismPenalty
if currSugarMetabolismPenalty > maxSugarMetabolismPenalty:
currSugarMetabolismPenalty = minSugarMetabolismPenalty
if currTagLength > maxTagLength:
currTagLength = minTagLength
if currVisionPenalty > maxVisionPenalty:
currVisionPenalty = minVisionPenalty
randomDiseaseEndowment = {"aggressionPenalties": aggressionPenalties,
"diseaseTags": diseaseTags,
"fertilityPenalties": fertilityPenalties,
"movementPenalties": movementPenalties,
"spiceMetabolismPenalties": spiceMetabolismPenalties,
"sugarMetabolismPenalties": sugarMetabolismPenalties,
"visionPenalties": visionPenalties}
# Map configuration to a random number via hash to make random number generation independent of iteration order
if (self.diseaseConfigHashes == None):
self.diseaseConfigHashes = {}
for penalty in randomDiseaseEndowment:
hashed = hashlib.md5(penalty.encode())
self.diseaseConfigHashes[penalty] = int(hashed.hexdigest(), 16)
# Keep state of random numbers to allow extending agent endowments without altering original random object state
randomNumberReset = random.getstate()
for endowment in randomDiseaseEndowment.keys():
random.seed(self.diseaseConfigHashes[endowment] + self.timestep)
random.shuffle(randomDiseaseEndowment[endowment])
random.setstate(randomNumberReset)
for i in range(numDiseases):
diseaseEndowment = {"aggressionPenalty": aggressionPenalties.pop(),
"fertilityPenalty": fertilityPenalties.pop(),
"movementPenalty": movementPenalties.pop(),
"spiceMetabolismPenalty": spiceMetabolismPenalties.pop(),
"sugarMetabolismPenalty": sugarMetabolismPenalties.pop(),
"tags": diseaseTags.pop(),
"visionPenalty": visionPenalties.pop()}
endowments.append(diseaseEndowment)
return endowments
def randomizeAgentEndowments(self, numAgents):
configs = self.configuration
aggressionFactor = configs["agentAggressionFactor"]
baseInterestRate = configs["agentBaseInterestRate"]
decisionModelFactor = configs["agentDecisionModelFactor"]
decisionModelLookaheadDiscount = configs["agentDecisionModelLookaheadDiscount"]
decisionModelLookaheadFactor = configs["agentDecisionModelLookaheadFactor"]
decisionModelTribalFactor = configs["agentDecisionModelTribalFactor"]
femaleFertilityAge = configs["agentFemaleFertilityAge"]
femaleInfertilityAge = configs["agentFemaleInfertilityAge"]
fertilityFactor = configs["agentFertilityFactor"]
immuneSystemLength = configs["agentImmuneSystemLength"]
inheritancePolicy = configs["agentInheritancePolicy"]
lendingFactor = configs["agentLendingFactor"]
loanDuration = configs["agentLoanDuration"]
lookaheadFactor = configs["agentLookaheadFactor"]
maleFertilityAge = configs["agentMaleFertilityAge"]
maleInfertilityAge = configs["agentMaleInfertilityAge"]
maleToFemaleRatio = configs["agentMaleToFemaleRatio"]
maxAge = configs["agentMaxAge"]
maxFriends = configs["agentMaxFriends"]
movement = configs["agentMovement"]
movementMode = configs["agentMovementMode"]
neighborhoodMode = configs["neighborhoodMode"]
selfishnessFactor = configs["agentSelfishnessFactor"]
spiceMetabolism = configs["agentSpiceMetabolism"]
startingSpice = configs["agentStartingSpice"]
startingSugar = configs["agentStartingSugar"]
sugarMetabolism = configs["agentSugarMetabolism"]
tagPreferences = configs["agentTagPreferences"]
tagging = configs["agentTagging"]
tradeFactor = configs["agentTradeFactor"]
tagging = configs["agentTagging"]
universalSpice = configs["agentUniversalSpice"]
universalSugar = configs["agentUniversalSugar"]
vision = configs["agentVision"]
visionMode = configs["agentVisionMode"]
numDepressedAgents = int(math.ceil(numAgents * configs["agentDepressionPercentage"]))
depressionFactors = [1 for i in range(numDepressedAgents)] + [0 for i in range(numAgents - numDepressedAgents)]
random.shuffle(depressionFactors)
configurations = {"aggressionFactor": {"endowments": [], "curr": aggressionFactor[0], "min": aggressionFactor[0], "max": aggressionFactor[1]},
"baseInterestRate": {"endowments": [], "curr": baseInterestRate[0], "min": baseInterestRate[0], "max": baseInterestRate[1]},
"decisionModelFactor": {"endowments": [], "curr": decisionModelFactor[0], "min": decisionModelFactor[0], "max": decisionModelFactor[1]},
"decisionModelLookaheadDiscount": {"endowments": [], "curr": decisionModelLookaheadDiscount[0], "min": decisionModelLookaheadDiscount[0], "max": decisionModelLookaheadDiscount[1]},
"decisionModelTribalFactor": {"endowments": [], "curr": decisionModelTribalFactor[0], "min": decisionModelTribalFactor[0], "max": decisionModelTribalFactor[1]},
"femaleFertilityAge": {"endowments": [], "curr": femaleFertilityAge[0], "min": femaleFertilityAge[0], "max": femaleFertilityAge[1]},
"femaleInfertilityAge": {"endowments": [], "curr": femaleInfertilityAge[0], "min": femaleInfertilityAge[0], "max": femaleInfertilityAge[1]},
"fertilityFactor": {"endowments": [], "curr": fertilityFactor[0], "min": fertilityFactor[0], "max": fertilityFactor[1]},
"lendingFactor": {"endowments": [], "curr": lendingFactor[0], "min": lendingFactor[0], "max": lendingFactor[1]},
"loanDuration": {"endowments": [], "curr": loanDuration[0], "min": loanDuration[0], "max": loanDuration[1]},
"lookaheadFactor": {"endowments": [], "curr": lookaheadFactor[0], "min": lookaheadFactor[0], "max": lookaheadFactor[1]},
"maleFertilityAge": {"endowments": [], "curr": maleFertilityAge[0], "min": maleFertilityAge[0], "max": maleFertilityAge[1]},
"maleInfertilityAge": {"endowments": [], "curr": maleInfertilityAge[0], "min": maleInfertilityAge[0], "max": maleInfertilityAge[1]},
"maxAge": {"endowments": [], "curr": maxAge[0], "min": maxAge[0], "max": maxAge[1]},
"maxFriends": {"endowments": [], "curr": maxFriends[0], "min": maxFriends[0], "max": maxFriends[1]},
"movement": {"endowments": [], "curr": movement[0], "min": movement[0], "max": movement[1]},
"selfishnessFactor": {"endowments": [], "curr": selfishnessFactor[0], "min": selfishnessFactor[0], "max": selfishnessFactor[1]},
"spice": {"endowments": [], "curr": startingSpice[0], "min": startingSpice[0], "max": startingSpice[1]},
"spiceMetabolism": {"endowments": [], "curr": spiceMetabolism[0], "min": spiceMetabolism[0], "max": spiceMetabolism[1]},
"sugar": {"endowments": [], "curr": startingSugar[0], "min": startingSugar[0], "max": startingSugar[1]},
"sugarMetabolism": {"endowments": [], "curr": sugarMetabolism[0], "min": sugarMetabolism[0], "max": sugarMetabolism[1]},
"tradeFactor": {"endowments": [], "curr": tradeFactor[0], "min": tradeFactor[0], "max": tradeFactor[1]},
"universalSpice": {"endowments": [], "curr": universalSpice[0], "min": universalSpice[0], "max": universalSugar[1]},
"universalSugar": {"endowments": [], "curr": universalSugar[0], "min": universalSugar[0], "max": universalSugar[1]},
"vision": {"endowments": [], "curr": vision[0], "min": vision[0], "max": vision[1]}
}
if self.agentConfigHashes == None:
self.agentConfigHashes = {}
# Map configuration to a random number via hash to make random number generation independent of iteration order
for config in configurations.keys():
hashed = hashlib.md5(config.encode())
hashNum = int(hashed.hexdigest(), 16)
self.agentConfigHashes[config] = hashNum
for config in configurations:
configMin = configurations[config]["min"]
configMax = configurations[config]["max"]
configMinDecimals = str(configMin).split('.')
configMaxDecimals = str(configMax).split('.')
decimalRange = []
if len(configMinDecimals) == 2:
configMinDecimals = len(configMinDecimals[1])
decimalRange.append(configMinDecimals)
if len(configMaxDecimals) == 2:
configMaxDecimals = len(configMaxDecimals[1])
decimalRange.append(configMaxDecimals)
# If no fractional component to configuration item, assume increment of 1
decimals = max(decimalRange) if len(decimalRange) > 0 else 0
increment = 10 ** (-1 * decimals)
configurations[config]["inc"] = increment
configurations[config]["decimals"] = decimals
decisionModels = []
endowments = []
immuneSystems = []
sexes = []
tags = self.generateAgentTags(numAgents)
sexDistributionCountdown = numAgents
# Determine count of male agents and set as switch for agent generation
if maleToFemaleRatio != None and maleToFemaleRatio != 0:
sexDistributionCountdown = math.floor(sexDistributionCountdown / (maleToFemaleRatio + 1)) * maleToFemaleRatio
for i in range(numAgents):
for config in configurations.values():
config["endowments"].append(config["curr"])
config["curr"] += config["inc"]
config["curr"] = round(config["curr"], config["decimals"])
if config["curr"] > config["max"]:
config["curr"] = config["min"]
if immuneSystemLength > 0:
immuneSystems.append([random.randrange(2) for i in range(immuneSystemLength)])
else:
immuneSystems.append(None)
if maleToFemaleRatio != None and maleToFemaleRatio != 0:
if sexDistributionCountdown == 0:
sexes.append("female")
else:
sexes.append("male")
sexDistributionCountdown -= 1
else:
sexes.append(None)
decisionModel = configs["agentDecisionModels"][i % len(configs["agentDecisionModels"])]
# Convert clever name for default behavior
if decisionModel == "rawSugarscape":
decisionModel = "none"
decisionModels.append(decisionModel)
# Keep state of random numbers to allow extending agent endowments without altering original random object state
randomNumberReset = random.getstate()
for config in configurations:
random.seed(self.agentConfigHashes[config] + self.timestep)
random.shuffle(configurations[config]["endowments"])
random.setstate(randomNumberReset)
random.shuffle(sexes)
random.shuffle(decisionModels)
for i in range(numAgents):
agentEndowment = {"seed": self.seed, "sex": sexes[i], "tags": tags.pop(), "tagPreferences": tagPreferences, "tagging": tagging,
"immuneSystem": immuneSystems.pop(), "inheritancePolicy": inheritancePolicy,
"decisionModel": decisionModels.pop(), "decisionModelLookaheadFactor": decisionModelLookaheadFactor,
"movementMode": movementMode, "neighborhoodMode": neighborhoodMode, "visionMode": visionMode,
"depressionFactor": depressionFactors[i]}
for config in configurations:
# If sexes are enabled, ensure proper fertility and infertility ages are set
if sexes[i] == "female" and config == "femaleFertilityAge":
agentEndowment["fertilityAge"] = configurations["femaleFertilityAge"]["endowments"].pop()
elif sexes[i] == "female" and config == "femaleInfertilityAge":
agentEndowment["infertilityAge"] = configurations["femaleInfertilityAge"]["endowments"].pop()
elif sexes[i] == "male" and config == "maleFertilityAge":
agentEndowment["fertilityAge"] = configurations["maleFertilityAge"]["endowments"].pop()
elif sexes[i] == "male" and config == "maleInfertilityAge":
agentEndowment["infertilityAge"] = configurations["maleInfertilityAge"]["endowments"].pop()
elif sexes[i] == None and (config == "femaleInfertilityAge" or config == "femaleFertilityAge" or
config == "maleInfertilityAge" or config == "maleFertilityAge"):
continue
else:
agentEndowment[config] = configurations[config]["endowments"].pop()
if sexes[i] == None:
agentEndowment["fertilityAge"] = 0
agentEndowment["infertilityAge"] = 0
endowments.append(agentEndowment)
return endowments
def randomizeDiseaseEndowments(self, numDiseases):
configs = self.configuration
sugarMetabolismPenalty = configs["diseaseSugarMetabolismPenalty"]
spiceMetabolismPenalty = configs["diseaseSpiceMetabolismPenalty"]
movementPenalty = configs["diseaseMovementPenalty"]
visionPenalty = configs["diseaseVisionPenalty"]
fertilityPenalty = configs["diseaseFertilityPenalty"]
aggressionPenalty = configs["diseaseAggressionPenalty"]
tagLengths = configs["diseaseTagStringLength"]
minSugarMetabolismPenalty = sugarMetabolismPenalty[0]
minSpiceMetabolismPenalty = spiceMetabolismPenalty[0]
minMovementPenalty = movementPenalty[0]
minVisionPenalty = visionPenalty[0]
minFertilityPenalty = fertilityPenalty[0]
minAggressionPenalty = aggressionPenalty[0]
minTagLength = tagLengths[0]
maxSugarMetabolismPenalty = sugarMetabolismPenalty[1]
maxSpiceMetabolismPenalty = spiceMetabolismPenalty[1]
maxMovementPenalty = movementPenalty[1]
maxVisionPenalty = visionPenalty[1]
maxFertilityPenalty = fertilityPenalty[1]
maxAggressionPenalty = aggressionPenalty[1]
maxTagLength = tagLengths[1]
endowments = []
sugarMetabolismPenalties = []
spiceMetabolismPenalties = []
movementPenalties = []
visionPenalties = []
fertilityPenalties = []
aggressionPenalties = []
diseaseTags = []
currSugarMetabolismPenalty = minSugarMetabolismPenalty
currSpiceMetabolismPenalty = minSpiceMetabolismPenalty
currMovementPenalty = minMovementPenalty
currVisionPenalty = minVisionPenalty
currFertilityPenalty = minFertilityPenalty
currAggressionPenalty = minAggressionPenalty
currTagLength = minTagLength
for i in range(numDiseases):
sugarMetabolismPenalties.append(currSugarMetabolismPenalty)
spiceMetabolismPenalties.append(currSpiceMetabolismPenalty)
movementPenalties.append(currMovementPenalty)
visionPenalties.append(currVisionPenalty)
fertilityPenalties.append(currFertilityPenalty)
aggressionPenalties.append(currAggressionPenalty)
diseaseTags.append([random.randrange(2) for i in range(currTagLength)])
currSugarMetabolismPenalty += 1
currSpiceMetabolismPenalty += 1
currMovementPenalty += 1
currVisionPenalty += 1
currFertilityPenalty += 1
currAggressionPenalty += 1
currTagLength += 1
if currSugarMetabolismPenalty > maxSugarMetabolismPenalty:
currSugarMetabolismPenalty = minSugarMetabolismPenalty
if currSpiceMetabolismPenalty > maxSpiceMetabolismPenalty:
currSpiceMetabolismPenalty = minSpiceMetabolismPenalty
if currMovementPenalty > maxMovementPenalty:
currMovementPenalty = minMovementPenalty
if currVisionPenalty > maxVisionPenalty:
currVisionPenalty = minVisionPenalty
if currFertilityPenalty > maxFertilityPenalty:
currFertilityPenalty = minFertilityPenalty
if currAggressionPenalty > maxAggressionPenalty:
currAggressionPenalty = minAggressionPenalty
if currTagLength > maxTagLength:
currTagLength = minTagLength
randomDiseaseEndowment = {"sugarMetabolismPenalties": sugarMetabolismPenalties,
"spiceMetabolismPenalties": spiceMetabolismPenalties,
"movementPenalties": movementPenalties,
"visionPenalties": visionPenalties,
"fertilityPenalties": fertilityPenalties,
"aggressionPenalties": aggressionPenalties,
"diseaseTags": diseaseTags}
# Map configuration to a random number via hash to make random number generation independent of iteration order
if (self.diseaseConfigHashes == None):
self.diseaseConfigHashes = {}
for penalty in randomDiseaseEndowment:
hashed = hashlib.md5(penalty.encode())
self.diseaseConfigHashes[penalty] = int(hashed.hexdigest(), 16)
# Keep state of random numbers to allow extending agent endowments without altering original random object state
randomNumberReset = random.getstate()
for endowment in randomDiseaseEndowment.keys():
random.seed(self.diseaseConfigHashes[endowment] + self.timestep)
random.shuffle(randomDiseaseEndowment[endowment])
random.setstate(randomNumberReset)
for i in range(numDiseases):
diseaseEndowment = {"aggressionPenalty": aggressionPenalties.pop(),
"fertilityPenalty": fertilityPenalties.pop(),
"movementPenalty": movementPenalties.pop(),
"sugarMetabolismPenalty": sugarMetabolismPenalties.pop(),
"spiceMetabolismPenalty": spiceMetabolismPenalties.pop(),
"tags": diseaseTags.pop(),
"visionPenalty": visionPenalties.pop()}
endowments.append(diseaseEndowment)
return endowments
def removeDeadAgents(self):
deadAgents = []
for agent in self.agents:
if agent.isAlive() == False:
deadAgents.append(agent)
elif agent.cell == None:
deadAgents.append(agent)
self.deadAgents += deadAgents
for agent in deadAgents:
self.agents.remove(agent)
def replaceDeadAgents(self):
numAgents = len(self.agents)
if numAgents < self.configuration["agentReplacements"]:
numReplacements = self.configuration["agentReplacements"] - numAgents
self.configureAgents(numReplacements)
def runSimulation(self, timesteps=5):
self.startLog()
if self.log == None:
self.updateRuntimeStats()
if self.gui != None:
# Simulation begins paused until start button in GUI pressed
self.gui.updateLabels()
self.pauseSimulation()
t = 1
timesteps = timesteps - self.timestep
screenshots = 0
while t <= timesteps:
if len(self.agents) == 0 and self.keepAlive == False:
break
if self.configuration["screenshots"] == True and self.configuration["headlessMode"] == False:
self.gui.canvas.postscript(file=f"screenshot{screenshots}.ps", colormode="color")
screenshots += 1
self.doTimestep()
t += 1
if self.gui != None and self.run == False:
self.pauseSimulation()
self.endSimulation()
def startLog(self):
if self.log == None:
return
if self.logFormat == "csv":
header = ""
# Ensure consistent ordering for CSV format
for stat in sorted(self.runtimeStats):
if header == "":
header += f"{stat}"
else:
header += f",{stat}"
header += "\n"
self.log.write(header)
else:
self.log.write("[\n")
self.updateRuntimeStats()
self.writeToLog()
def toggleEnd(self):
self.end = True
def toggleRun(self):
self.run = not self.run
def updateGiniCoefficient(self):
if len(self.agents) == 0:
return 0
agentWealths = sorted([agent.sugar + agent.spice for agent in self.agents])
# Calculate normalized area of Lorenz curve of agent wealths
numAgents = len(agentWealths)
totalWealth = sum(agentWealths)
if totalWealth == 0:
return 1
cumulativeWealth = 0
lorenzCurveArea = 0
for i in range(numAgents - 1):
cumulativeWealth += agentWealths[i]
lorenzCurveArea += cumulativeWealth / totalWealth
# Use trapezoidal area to maintain accuracy with smaller populations
cumulativeWealth += agentWealths[-1]
lorenzCurveArea += (cumulativeWealth / 2) / totalWealth
lorenzCurveArea /= numAgents
# The total area under the equality line will be 0.5
equalityLineArea = 0.5
giniCoefficient = round((equalityLineArea - lorenzCurveArea) / equalityLineArea, 3)
return giniCoefficient
def updateGraphStats(self):
histogramBins = self.gui.xTicks
maxAge = self.configuration["agentMaxAge"][1]
ageBins = [0] * histogramBins
if maxAge != -1:
for agent in self.agents:
ageBins[math.floor(agent.age / (maxAge + 1) * histogramBins)] += 1
maxSpice = 0
maxSugar = 0
maxWealth = 0
for agent in self.agents:
if agent.spice > maxSpice:
maxSpice = agent.spice
if agent.sugar > maxSugar:
maxSugar = agent.sugar
if agent.sugar + agent.spice > maxWealth:
maxWealth = agent.sugar + agent.spice
self.graphStats["maxSpice"] = maxSpice
self.graphStats["maxSugar"] = maxSugar
self.graphStats["maxWealth"] = maxWealth
sugarBins = [0] * histogramBins
spiceBins = [0] * histogramBins
agentWealths = []
for agent in self.agents:
spiceBins[math.floor(agent.spice / (maxSpice + 1) * histogramBins)] += 1
sugarBins[math.floor(agent.sugar / (maxSugar + 1) * histogramBins)] += 1
agentWealths.append(agent.sugar + agent.spice)
meanTribeTags = [0] * self.configuration["agentTagStringLength"]
totalPopulation = len(self.agents)
if self.configuration["agentTagStringLength"] > 0 and totalPopulation > 0:
for agent in self.agents:
meanTribeTags = [i + j for i, j in zip(meanTribeTags, agent.tags)]
meanTribeTags = [round(tag / totalPopulation, 2) * 100 for tag in meanTribeTags]
agentWealths.sort()
totalWealth = sum(agentWealths)
cumulativeWealth = 0
if totalWealth > 0 and len(agentWealths) > 0:
lorenzCurvePoints = [(0, 0)]
for i, wealth in enumerate(agentWealths):
cumulativePopulation = (i + 1)
cumulativeWealth += wealth
lorenzCurvePoints.append((cumulativePopulation / totalPopulation, cumulativeWealth / totalWealth))
if lorenzCurvePoints[-1] != (1, 1):
lorenzCurvePoints.append((1, 1))
else:
lorenzCurvePoints = [(0, 0), (1, 1)]
self.graphStats["ageBins"] = ageBins
self.graphStats["lorenzCurvePoints"] = lorenzCurvePoints
self.graphStats["meanTribeTags"] = meanTribeTags
self.graphStats["spiceBins"] = spiceBins
self.graphStats["sugarBins"] = sugarBins
def updateRuntimeStats(self):
# Log separate stats for experimental and control groups
if self.experimentalGroup != None:
self.updateRuntimeStatsPerGroup(self.experimentalGroup)
self.updateRuntimeStatsPerGroup(self.experimentalGroup, True)
self.updateRuntimeStatsPerGroup()
def updateRuntimeStatsPerGroup(self, group=None, notInGroup=False):
maxTribe = 0
maxTribeSize = 0
maxWealth = 0
meanAge = 0
meanConflictHappiness = 0
meanFamilyHappiness = 0
meanHappiness = 0
meanHealthHappiness = 0
meanMetabolism = 0
meanMovement = 0
meanSocialHappiness = 0
meanSpiceMetabolism = 0
meanSugarMetabolism = 0
meanTradePrice = 0
meanVision = 0
meanWealth = 0
meanWealthHappiness = 0
minWealth = sys.maxsize
numAgents = 0
numTraders = 0
numTribes = 0
sickAgents = 0
tradeVolume = 0
carryingCapacityWeight = 0.05
carryingCapacity = math.ceil((carryingCapacityWeight * len(self.agents)) + ((1 - carryingCapacityWeight) * self.runtimeStats["carryingCapacity"]))
if self.timestep == 0:
carryingCapacity = len(self.agents)
environmentWealthCreated = 0
environmentWealthTotal = 0
for i in range(self.environment.width):
for j in range(self.environment.height):
environmentWealthCreated += self.environment.grid[i][j].sugarLastProduced + self.environment.grid[i][j].spiceLastProduced
environmentWealthTotal += self.environment.grid[i][j].sugar + self.environment.grid[i][j].spice
if self.timestep == 1:
environmentWealthCreated += self.environment.grid[i][j].maxSugar + self.environment.grid[i][j].maxSpice
agentAgingDeaths = 0
agentCombatDeaths = 0
agentDiseaseDeaths = 0
agentMeanTimeToLive = 0
agentStarvationDeaths = 0
agentTotalMetabolism = 0
agentWealthBurnRate = 0
agentWealthCollected = 0
agentWealthTotal = 0
agentsBorn = 0
agentsReplaced = 0
tribes = {}
for agent in self.agents:
if group != None and agent.isInGroup(group, notInGroup) == False:
continue
agentTimeToLive = agent.findTimeToLive()
agentTimeToLiveAgeLimited = agent.findTimeToLive(True)
agentWealth = agent.sugar + agent.spice
meanSugarMetabolism += agent.sugarMetabolism
meanSpiceMetabolism += agent.spiceMetabolism
meanMovement += agent.movement
meanVision += agent.vision
meanAge += agent.age
meanWealth += agentWealth
meanHappiness += agent.happiness
meanWealthHappiness += agent.wealthHappiness
meanHealthHappiness += agent.healthHappiness
meanFamilyHappiness += agent.familyHappiness
meanSocialHappiness += agent.socialHappiness
meanConflictHappiness += agent.conflictHappiness
if agent.tradeVolume > 0:
meanTradePrice += max(agent.spicePrice, agent.sugarPrice)
tradeVolume += agent.tradeVolume
numTraders += 1
agentWealthTotal += agentWealth
agentWealthCollected += agentWealth - (agent.lastSugar + agent.lastSpice)
agentWealthBurnRate += agentTimeToLive
agentMeanTimeToLive += agentTimeToLiveAgeLimited
agentTotalMetabolism += agent.sugarMetabolism + agent.spiceMetabolism
if agent.isSick():
sickAgents += 1
if agentWealth < minWealth:
minWealth = agentWealth
if agentWealth > maxWealth:
maxWealth = agentWealth
if agent.tribe not in tribes:
tribes[agent.tribe] = 1
else:
tribes[agent.tribe] += 1
numAgents += 1
if numAgents > 0:
agentMeanTimeToLive = round(agentMeanTimeToLive / numAgents, 2)
agentWealthBurnRate = round(agentWealthBurnRate / numAgents, 2)
agentWealthTotal = round(agentWealthTotal, 2)
maxTribe = max(tribes, key=tribes.get)
maxTribeSize = tribes[maxTribe]
maxWealth = round(maxWealth, 2)
meanAge = round(meanAge / numAgents, 2)
meanConflictHappiness = round(meanConflictHappiness / numAgents, 2)
meanFamilyHappiness = round(meanFamilyHappiness / numAgents, 2)