-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathagent.py
1404 lines (1281 loc) · 64.1 KB
/
agent.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
import hashlib
import math
import random
import sys
class Agent:
def __init__(self, agentID, birthday, cell, configuration):
self.ID = agentID
self.born = birthday
self.cell = cell
self.debug = cell.environment.sugarscape.debug
self.aggressionFactor = configuration["aggressionFactor"]
self.baseInterestRate = configuration["baseInterestRate"]
self.decisionModel = configuration["decisionModel"]
self.decisionModelFactor = configuration["decisionModelFactor"]
self.decisionModelLookaheadDiscount = configuration["decisionModelLookaheadDiscount"]
self.decisionModelLookaheadFactor = configuration["decisionModelLookaheadFactor"]
self.decisionModelTribalFactor = configuration["decisionModelTribalFactor"]
self.depressionFactor = configuration["depressionFactor"]
self.fertilityAge = configuration["fertilityAge"]
self.fertilityFactor = configuration["fertilityFactor"]
self.immuneSystem = configuration["immuneSystem"]
self.infertilityAge = configuration["infertilityAge"]
self.inheritancePolicy = configuration["inheritancePolicy"]
self.lendingFactor = configuration["lendingFactor"]
self.loanDuration = configuration["loanDuration"]
self.lookaheadFactor = configuration["lookaheadFactor"]
self.maxAge = configuration["maxAge"]
self.maxFriends = configuration["maxFriends"]
self.movement = configuration["movement"]
self.movementMode = configuration["movementMode"]
self.neighborhoodMode = configuration["neighborhoodMode"]
self.seed = configuration["seed"]
self.selfishnessFactor = configuration["selfishnessFactor"]
self.sex = configuration["sex"]
self.spice = configuration["spice"]
self.spiceMetabolism = configuration["spiceMetabolism"]
self.startingImmuneSystem = configuration["immuneSystem"]
self.startingSpice = configuration["spice"]
self.startingSugar = configuration["sugar"]
self.sugar = configuration["sugar"]
self.sugarMetabolism = configuration["sugarMetabolism"]
self.tagging = configuration["tagging"]
self.tagPreferences = configuration["tagPreferences"]
self.tags = configuration["tags"]
self.tradeFactor = configuration["tradeFactor"]
self.universalSpice = configuration["universalSpice"]
self.universalSugar = configuration["universalSugar"]
self.vision = configuration["vision"]
self.visionMode = configuration["visionMode"]
self.age = 0
self.aggressionFactorModifier = 0
self.alive = True
self.causeOfDeath = None
self.cellsInRange = []
self.childEndowmentHashes = None
self.conflictHappiness = 0
self.depressed = False
self.diseases = []
self.familyHappiness = 0
self.fertile = False
self.fertilityFactorModifier = 0
self.happiness = 0
self.healthHappiness = 0
self.lastDoneCombat = -1
self.lastMoved = -1
self.lastReproduced = -1
self.lastSpice = 0
self.lastSugar = 0
self.lastUniversalSpiceIncomeTimestep = 0
self.lastUniversalSugarIncomeTimestep = 0
self.marginalRateOfSubstitution = 1
self.movementModifier = 0
self.neighborhood = []
self.neighbors = []
self.nice = 0
self.socialHappiness = 0
self.socialNetwork = {"father": None, "mother": None, "children": [], "friends": [], "creditors": [], "debtors": [], "mates": []}
self.spiceMeanIncome = 1
self.spiceMetabolismModifier = 0
self.spicePrice = 0
self.sugarMeanIncome = 1
self.sugarMetabolismModifier = 0
self.sugarPrice = 0
self.tagZeroes = 0
self.timestep = birthday
self.tradeVolume = 0
self.tribe = self.findTribe()
self.visionModifier = 0
self.wealthHappiness = 0
# Change metrics for depressed agents
if self.depressionFactor == 1:
self.depressed = True
# Depressed agents undereat due to eating disorders
# TODO: Current implementation increases metabolism, causing overeating instead
self.sugarMetabolism = math.ceil(self.sugarMetabolism * 1.544)
self.spiceMetabolism = math.ceil(self.spiceMetabolism * 1.544)
# Depressed agents move slower due to fatigue
self.movement = math.ceil(self.movement * 0.429)
# Depressed agents have heightened aggression due to irritability
self.aggressionFactor = math.ceil(self.aggressionFactor * 1.145)
# Social withdrawal: to represent a degree of social withdrawal, the maximum number of friends an agent can have will be lowered
# Depressed agents have a smaller friend network due to social withdrawal
self.maxFriends = math.ceil(self.maxFriends * 0.6333)
def addChildToCell(self, mate, cell, childConfiguration):
sugarscape = self.cell.environment.sugarscape
childID = sugarscape.generateAgentID()
childDecisionModel = childConfiguration["decisionModel"]
child = None
if childDecisionModel == self.decisionModel:
child = self.spawnChild(childID, self.timestep, cell, childConfiguration)
else:
child = mate.spawnChild(childID, self.timestep, cell, childConfiguration)
child.gotoCell(cell)
sugarscape.addAgent(child)
child.collectResourcesAtCell()
if self.sex == "female":
child.setMother(self)
child.setFather(mate)
else:
child.setFather(self)
child.setMother(mate)
return child
def addAgentToSocialNetwork(self, agent):
agentID = agent.ID
if agentID in self.socialNetwork:
return
self.socialNetwork[agentID] = {"agent": agent, "lastSeen": self.lastMoved, "timesVisited": 1, "timesReproduced": 0,
"timesTraded": 0, "timesLoaned": 0, "marginalRateOfSubstitution": 0}
def addLoanFromAgent(self, agent, timestep, sugarLoan, spiceLoan, duration):
agentID = agent.ID
if agentID not in self.socialNetwork:
self.addAgentToSocialNetwork(agent)
self.socialNetwork[agentID]["timesLoaned"] += 1
loan = {"creditor": agentID, "debtor": self.ID, "sugarLoan": sugarLoan, "spiceLoan": spiceLoan, "loanDuration": duration,
"loanOrigin": timestep}
self.socialNetwork["creditors"].append(loan)
def addLoanToAgent(self, agent, timestep, sugarPrincipal, sugarLoan, spicePrincipal, spiceLoan, duration):
agentID = agent.ID
if agentID not in self.socialNetwork:
self.addAgentToSocialNetwork(agent)
self.socialNetwork[agentID]["timesLoaned"] += 1
agent.addLoanFromAgent(self, timestep, sugarLoan, spiceLoan, duration)
loan = {"creditor": self.ID, "debtor": agentID, "sugarLoan": sugarLoan, "spiceLoan": spiceLoan, "loanDuration": duration,
"loanOrigin": timestep}
self.socialNetwork["debtors"].append(loan)
self.sugar -= sugarPrincipal
self.spice -= spicePrincipal
agent.sugar = agent.sugar + sugarPrincipal
agent.spice = agent.spice + spicePrincipal
def canReachCell(self, cell):
if cell == self.cell or cell in self.cellsInRange:
return True
return False
def canTradeWithNeighbor(self, neighbor):
# If both trying to sell the same commodity, stop trading
if neighbor.marginalRateOfSubstitution >= 1 and self.marginalRateOfSubstitution >= 1:
return False
elif neighbor.marginalRateOfSubstitution < 1 and self.marginalRateOfSubstitution < 1:
return False
elif neighbor.marginalRateOfSubstitution == self.marginalRateOfSubstitution:
return False
def catchDisease(self, disease, infector=None):
diseaseID = disease.ID
for currDisease in self.diseases:
currDiseaseID = currDisease["disease"].ID
# If currently sick with this disease, do not contract it again
if diseaseID == currDiseaseID:
return
diseaseInImmuneSystem = self.findNearestHammingDistanceInDisease(disease)
hammingDistance = diseaseInImmuneSystem["distance"]
# If immune to disease, do not contract it
if hammingDistance == 0:
return
startIndex = diseaseInImmuneSystem["start"]
endIndex = diseaseInImmuneSystem["end"]
caughtDisease = {"disease": disease, "startIndex": startIndex, "endIndex": endIndex}
if infector != None:
caughtDisease["infector"] = infector
self.diseases.append(caughtDisease)
self.updateDiseaseEffects(disease)
self.findCellsInRange()
def collectResourcesAtCell(self):
sugarCollected = self.cell.sugar
spiceCollected = self.cell.spice
self.sugar += sugarCollected
self.spice += spiceCollected
self.updateMeanIncome(sugarCollected, spiceCollected)
if self.cell.environment.pollutionStart <= self.timestep <= self.cell.environment.pollutionEnd:
self.cell.doSugarProductionPollution(sugarCollected)
self.cell.doSpiceProductionPollution(spiceCollected)
self.cell.resetSugar()
self.cell.resetSpice()
def defaultOnLoan(self, loan):
for creditor in self.socialNetwork["creditors"]:
continue
return
def doAging(self):
if self.isAlive() == False:
return
self.age += 1
# Die if reached max age and if not infinitely-lived
if self.age >= self.maxAge and self.maxAge != -1:
self.doDeath("aging")
def doCombat(self, cell):
prey = cell.agent
if prey != None and prey != self:
maxCombatLoot = self.cell.environment.maxCombatLoot
preySugar = prey.sugar
preySpice = prey.spice
sugarLoot = min(maxCombatLoot, preySugar)
spiceLoot = min(maxCombatLoot, preySpice)
self.sugar += sugarLoot
self.spice += spiceLoot
self.lastDoneCombat = self.cell.environment.sugarscape.timestep
prey.sugar -= sugarLoot
prey.spice -= spiceLoot
prey.doDeath("combat")
self.gotoCell(cell)
def doDeath(self, causeOfDeath):
self.alive = False
self.causeOfDeath = causeOfDeath
self.resetCell()
self.doInheritance()
# Keep only debtors and children in social network to handle outstanding loans
self.socialNetwork = {"debtors": self.socialNetwork["debtors"], "children": self.socialNetwork["children"]}
self.neighbors = []
self.neighborhood = []
self.diseases = []
def doDisease(self):
random.shuffle(self.diseases)
for diseaseRecord in self.diseases:
diseaseTags = diseaseRecord["disease"].tags
immuneResponseStart = diseaseRecord["startIndex"]
immuneResponseEnd = min(diseaseRecord["endIndex"] + 1, len(self.immuneSystem))
immuneResponse = self.immuneSystem[immuneResponseStart:immuneResponseEnd]
for i in range(len(immuneResponse)):
if immuneResponse[i] != diseaseTags[i]:
self.immuneSystem[immuneResponseStart + i] = diseaseTags[i]
break
if diseaseTags == immuneResponse:
self.diseases.remove(diseaseRecord)
self.updateDiseaseEffects(diseaseRecord["disease"])
diseaseCount = len(self.diseases)
if diseaseCount == 0:
return
neighborCells = self.cell.neighbors.values()
neighbors = []
for neighborCell in neighborCells:
neighbor = neighborCell.agent
if neighbor != None and neighbor.isAlive() == True:
neighbors.append(neighbor)
random.shuffle(neighbors)
for neighbor in neighbors:
neighbor.catchDisease(self.diseases[random.randrange(diseaseCount)]["disease"], self)
def doInheritance(self):
if self.inheritancePolicy == "none":
return
# Prevent negative inheritance
if self.sugar < 0:
self.sugar = 0
if self.spice < 0:
self.spice = 0
# Provide inheritance for living children/sons/daughters/friends
livingChildren = []
livingSons = []
livingDaughters = []
livingFriends = []
for child in self.socialNetwork["children"]:
if child.isAlive() == True:
livingChildren.append(child)
childSex = child.sex
if childSex == "male":
livingSons.append(child)
elif childSex == "female":
livingDaughters.append(child)
for friend in self.socialNetwork["friends"]:
if friend["friend"].isAlive() == True:
livingFriends.append(friend["friend"])
if self.inheritancePolicy == "children" and len(livingChildren) > 0:
sugarInheritance = self.sugar / len(livingChildren)
spiceInheritance = self.spice / len(livingChildren)
for child in livingChildren:
child.sugar = child.sugar + sugarInheritance
child.spice = child.spice + spiceInheritance
self.sugar -= sugarInheritance
self.spice -= spiceInheritance
elif self.inheritancePolicy == "sons" and len(livingSons) > 0:
sugarInheritance = self.sugar / len(livingSons)
spiceInheritance = self.spice / len(livingSons)
for son in livingSons:
son.sugar = son.sugar + sugarInheritance
son.spice = son.spice + spiceInheritance
self.sugar -= sugarInheritance
self.spice -= spiceInheritance
elif self.inheritancePolicy == "daughters" and len(livingDaughters) > 0:
sugarInheritance = self.sugar / len(livingDaughters)
spiceInheritance = self.spice / len(livingDaughters)
for daughter in livingDaughters:
daughter.sugar = daughter.sugar + sugarInheritance
daughter.spice = daughter.spice + spiceInheritance
self.sugar -= sugarInheritance
self.spice -= spiceInheritance
elif self.inheritancePolicy == "friends" and len(livingFriends) > 0:
sugarInheritance = self.sugar / len(livingFriends)
spiceInheritance = self.spice / len(livingFriends)
for friend in livingFriends:
friend.sugar = friend.sugar + sugarInheritance
friend.spice = friend.spice + spiceInheritance
self.sugar -= sugarInheritance
self.spice -= spiceInheritance
def doLending(self):
self.updateLoans()
# If not a lender, skip lending
if self.isLender() == False:
return
# Maximum interest rate of 100%
interestRate = min(1, self.lendingFactor * self.baseInterestRate)
neighbors = self.cell.findNeighborAgents()
borrowers = []
for neighbor in neighbors:
if neighbor.isAlive() == False:
continue
elif neighbor.isBorrower() == True:
borrowers.append(neighbor)
random.shuffle(borrowers)
spiceMetabolism = self.findSpiceMetabolism()
sugarMetabolism = self.findSugarMetabolism()
for borrower in borrowers:
maxSugarLoan = self.sugar / 2
maxSpiceLoan = self.spice / 2
if self.isFertile() == True:
maxSugarLoan = max(0, self.sugar - self.startingSugar)
maxSpiceLoan = max(0, self.spice - self.startingSpice)
# If not enough excess wealth to lend, stop lending
if maxSugarLoan == 0 and maxSpiceLoan == 0:
return
sugarLoanNeed = max(0, borrower.startingSugar - borrower.sugar)
spiceLoanNeed = max(0, borrower.startingSpice - borrower.spice)
# Find sugar and spice loans
sugarLoanPrincipal = min(maxSugarLoan, sugarLoanNeed)
spiceLoanPrincipal = min(maxSpiceLoan, spiceLoanNeed)
sugarLoanAmount = sugarLoanPrincipal + (sugarLoanPrincipal * interestRate)
spiceLoanAmount = spiceLoanPrincipal + (spiceLoanPrincipal * interestRate)
# If no loan needed within significant figures or lender excess resources exhausted
if (sugarLoanNeed == 0 and spiceLoanNeed == 0) or (sugarLoanAmount == 0 and spiceLoanAmount == 0):
continue
# If lending would cause lender to starve, skip lending to potential borrower
elif self.sugar - sugarLoanPrincipal <= sugarMetabolism or self.spice - spiceLoanPrincipal <= spiceMetabolism:
continue
elif borrower.isCreditWorthy(sugarLoanAmount, spiceLoanAmount, self.loanDuration) == True:
if "all" in self.debug or "agent" in self.debug:
print(f"Agent {self.ID} lending [{sugarLoanAmount},{spiceLoanAmount}]")
self.addLoanToAgent(borrower, self.lastMoved, sugarLoanPrincipal, sugarLoanAmount, spiceLoanPrincipal, spiceLoanAmount, self.loanDuration)
def doMetabolism(self):
if self.isAlive() == False:
return
spiceMetabolism = self.findSpiceMetabolism()
sugarMetabolism = self.findSugarMetabolism()
self.sugar -= sugarMetabolism
self.spice -= spiceMetabolism
if self.cell.environment.pollutionStart <= self.timestep <= self.cell.environment.pollutionEnd:
self.cell.doSugarConsumptionPollution(sugarMetabolism)
self.cell.doSpiceConsumptionPollution(spiceMetabolism)
if self.sugar < 0 or self.spice < 0:
self.doDeath("starvation")
elif (self.sugar <= 0 and sugarMetabolism > 0) or (self.spice <= 0 and spiceMetabolism > 0):
self.doDeath("starvation")
def doReproduction(self):
# Agent marked for removal or not interested in reproduction should not reproduce
if self.isAlive() == False or self.isFertile() == False:
return
neighborCells = list(self.cell.neighbors.values())
random.shuffle(neighborCells)
emptyCells = self.findEmptyNeighborCells()
for neighborCell in neighborCells:
neighbor = neighborCell.agent
if neighbor != None and neighbor.isAlive() == True:
neighborCompatibility = self.isNeighborReproductionCompatible(neighbor)
emptyCellsWithNeighbor = emptyCells + neighbor.findEmptyNeighborCells()
random.shuffle(emptyCellsWithNeighbor)
if self.isFertile() == True and neighborCompatibility == True and len(emptyCellsWithNeighbor) != 0:
emptyCell = emptyCellsWithNeighbor.pop()
while emptyCell.agent != None and len(emptyCellsWithNeighbor) != 0:
emptyCell = emptyCellsWithNeighbor.pop()
# If no adjacent empty cell is found, skip reproduction with this neighbor
if emptyCell.agent != None:
continue
if neighbor not in self.socialNetwork["mates"]:
self.socialNetwork["mates"].append(neighbor)
childEndowment = self.findChildEndowment(neighbor)
child = self.addChildToCell(neighbor, emptyCell, childEndowment)
child.findCellsInRange()
child.findNeighborhood()
self.socialNetwork["children"].append(child)
childID = child.ID
neighborID = neighbor.ID
self.addAgentToSocialNetwork(child)
neighbor.addAgentToSocialNetwork(child)
neighbor.updateTimesVisitedWithAgent(self, self.lastMoved)
neighbor.updateTimesReproducedWithAgent(self, self.lastMoved)
self.updateTimesReproducedWithAgent(neighbor, self.lastMoved)
self.lastReproduced += 1
sugarCost = self.startingSugar / (self.fertilityFactor * 2)
spiceCost = self.startingSpice / (self.fertilityFactor * 2)
mateSugarCost = neighbor.startingSugar / (neighbor.fertilityFactor * 2)
mateSpiceCost = neighbor.startingSpice / (neighbor.fertilityFactor * 2)
self.sugar -= sugarCost
self.spice -= spiceCost
neighbor.sugar = neighbor.sugar - mateSugarCost
neighbor.spice = neighbor.spice - mateSpiceCost
self.lastReproduced = self.cell.environment.sugarscape.timestep
if "all" in self.debug or "agent" in self.debug:
print(f"Agent {self.ID} reproduced with agent {str(neighbor)} at cell ({emptyCell.x},{emptyCell.y})")
def doTagging(self):
if self.tags == None or self.isAlive() == False or self.tagging == False:
return
neighborCells = list(self.cell.neighbors.values())
random.shuffle(neighborCells)
for neighborCell in neighborCells:
neighbor = neighborCell.agent
if neighbor != None:
position = random.randrange(len(self.tags))
neighbor.flipTag(position, self.tags[position])
neighbor.tribe = neighbor.findTribe()
def doTimestep(self, timestep):
self.timestep = timestep
# Prevent dead or already moved agent from moving
if self.isAlive() == True and self.lastMoved != self.timestep:
self.lastSugar = self.sugar
self.lastSpice = self.spice
self.lastMoved = self.timestep
self.moveToBestCell()
self.updateNeighbors()
self.collectResourcesAtCell()
self.doUniversalIncome()
self.doMetabolism()
# If dead from metabolism, skip remainder of timestep
if self.alive == False:
return
self.doTagging()
self.doTrading()
self.doReproduction()
self.doLending()
self.doDisease()
self.doAging()
# If dead from aging, skip remainder of timestep
if self.alive == False:
return
self.findCellsInRange()
self.updateHappiness()
def doTrading(self):
# If not a trader, skip trading
if self.tradeFactor == 0:
return
self.tradeVolume = 0
self.sugarPrice = 0
self.spicePrice = 0
self.findMarginalRateOfSubstitution()
neighborCells = self.cell.neighbors.values()
traders = []
for neighborCell in neighborCells:
neighbor = neighborCell.agent
if neighbor != None and neighbor.isAlive() == True:
neighborMRS = neighbor.marginalRateOfSubstitution
if neighborMRS != self.marginalRateOfSubstitution:
traders.append(neighbor)
random.shuffle(traders)
for trader in traders:
spiceSeller = None
sugarSeller = None
tradeFlag = True
transactions = 0
while tradeFlag == True:
traderMRS = trader.marginalRateOfSubstitution
# If both trying to sell the same commodity, stop trading
if self.canTradeWithNeighbor(trader) == False:
tradeFlag = False
continue
# MRS > 1 indicates the agent has less need of spice and should become the spice seller
if traderMRS > self.marginalRateOfSubstitution:
spiceSeller = trader
sugarSeller = self
else:
spiceSeller = self
sugarSeller = trader
spiceSellerMRS = spiceSeller.marginalRateOfSubstitution
sugarSellerMRS = sugarSeller.marginalRateOfSubstitution
# TODO: Fix bug where a spice or sugar seller has a negative MRS
if spiceSellerMRS < 0 or sugarSellerMRS < 0:
spiceSeller = None
sugarSeller = None
break
# Find geometric mean of spice and sugar seller MRS for trade price
tradePrice = math.sqrt(spiceSellerMRS * sugarSellerMRS)
sugarPrice = 0
spicePrice = 0
# Set proper highest value commodity based on trade price
if tradePrice < 1:
spicePrice = 1
sugarPrice = tradePrice
else:
spicePrice = tradePrice
sugarPrice = 1
# If trade would be lethal, skip it
if spiceSeller.spice - spicePrice < spiceSeller.spiceMetabolism or sugarSeller.sugar - sugarPrice < sugarSeller.sugarMetabolism:
tradeFlag = False
continue
spiceSellerNewMRS = spiceSeller.findNewMarginalRateOfSubstitution(spiceSeller.sugar + sugarPrice, spiceSeller.spice - spicePrice)
sugarSellerNewMRS = sugarSeller.findNewMarginalRateOfSubstitution(sugarSeller.sugar - sugarPrice, sugarSeller.spice + spicePrice)
# Calculate absolute difference from perfect spice/sugar parity in MRS and change in agent welfare
betterSpiceSellerMRS = abs(1 - spiceSellerMRS) > abs(1 - spiceSellerNewMRS)
betterSugarSellerMRS = abs(1 - sugarSellerMRS) > abs(1 - sugarSellerNewMRS)
betterSpiceSellerWelfare = spiceSeller.findWelfare(sugarPrice, (-1 * spicePrice)) >= spiceSeller.findWelfare(0, 0)
betterSugarSellerWelfare = sugarSeller.findWelfare((-1 * sugarPrice), spicePrice) >= sugarSeller.findWelfare(0, 0)
# If either MRS or welfare is improved, mark the trade as better for agent
betterForSpiceSeller = betterSpiceSellerMRS or betterSpiceSellerWelfare
betterForSugarSeller = betterSugarSellerMRS or betterSugarSellerWelfare
# Check that spice seller's new MRS does not cross over sugar seller's new MRS
# Evaluates to False for successful trades
checkForMRSCrossing = spiceSellerNewMRS < sugarSellerNewMRS
if betterForSpiceSeller == True and betterForSugarSeller == True and checkForMRSCrossing == False:
if "all" in self.debug or "agent" in self.debug:
print(f"Agent {self.ID} trading [{sugarPrice}, {spicePrice}]")
spiceSeller.sugar += sugarPrice
spiceSeller.spice -= spicePrice
sugarSeller.sugar -= sugarPrice
sugarSeller.spice += spicePrice
spiceSeller.findMarginalRateOfSubstitution()
sugarSeller.findMarginalRateOfSubstitution()
transactions += 1
else:
tradeFlag = False
continue
# If a trade occurred, log it
if spiceSeller != None and sugarSeller != None:
self.tradeVolume += 1
self.sugarPrice += sugarPrice
self.spicePrice += spicePrice
trader.updateTimesTradedWithAgent(self, self.lastMoved, transactions)
self.updateTimesTradedWithAgent(trader, self.lastMoved, transactions)
def doUniversalIncome(self):
if (self.timestep - self.lastUniversalSpiceIncomeTimestep) >= self.cell.environment.universalSpiceIncomeInterval:
self.spice += self.universalSpice
self.lastUniversalSpiceIncomeTimestep = self.timestep
if (self.timestep - self.lastUniversalSugarIncomeTimestep) >= self.cell.environment.universalSugarIncomeInterval:
self.sugar += self.universalSugar
self.lastUniversalSugarIncomeTimestep = self.timestep
def findAggression(self):
return max(0, self.aggressionFactor + self.aggressionFactorModifier)
def findBestCell(self):
self.findNeighborhood()
if len(self.cellsInRange) == 0:
return self.cell
cellsInRange = list(self.cellsInRange.items())
random.shuffle(cellsInRange)
retaliators = self.findRetaliatorsInVision()
combatMaxLoot = self.cell.environment.maxCombatLoot
aggression = self.findAggression()
bestCell = None
bestWealth = 0
bestRange = max(self.cell.environment.height, self.cell.environment.width)
potentialCells = []
for cell, travelDistance in cellsInRange:
# Avoid attacking agents ineligible to attack
prey = cell.agent
if cell.isOccupied() and self.isNeighborValidPrey(prey) == False:
continue
preyTribe = prey.tribe if prey != None else "empty"
preySugar = prey.sugar if prey != None else 0
preySpice = prey.spice if prey != None else 0
# Aggression factor may lead agent to see more reward than possible meaning combat itself is a reward
welfarePreySugar = aggression * min(combatMaxLoot, preySugar)
welfarePreySpice = aggression * min(combatMaxLoot, preySpice)
# Modify value of cell relative to the metabolism needs of the agent
welfare = self.findWelfare(((cell.sugar + welfarePreySugar) / (1 + cell.pollution)), ((cell.spice + welfarePreySpice) / (1 + cell.pollution)))
# Avoid attacking agents protected via retaliation
if prey != None and retaliators[preyTribe] > self.sugar + self.spice + welfare:
continue
# Select closest cell with the most resources
if welfare > bestWealth or (welfare == bestWealth and travelDistance < bestRange):
bestCell = cell
bestWealth = welfare
bestRange = travelDistance
cellRecord = {"cell": cell, "wealth": welfare, "range": travelDistance}
potentialCells.append(cellRecord)
if self.decisionModelFactor > 0:
bestCell = self.findBestEthicalCell(potentialCells, bestCell)
if bestCell == None:
bestCell = self.cell
return bestCell
def findBestEthicalCell(self, cells, greedyBestCell=None):
if len(cells) == 0:
return None
bestCell = None
cells = self.sortCellsByWealth(cells)
if "all" in self.debug or "agent" in self.debug:
self.printCellScores(cells)
# If not an ethical agent, return top selfish choice
if self.decisionModel == "none":
return greedyBestCell
for cell in cells:
cell["wealth"] = self.findEthicalValueOfCell(cell["cell"])
if self.selfishnessFactor >= 0:
for cell in cells:
if cell["wealth"] > 0:
bestCell = cell["cell"]
break
else:
# Negative utilitarian model uses positive and negative utility to find minimum harm
cells.sort(key = lambda cell: (cell["wealth"]["unhappiness"], cell["wealth"]["happiness"]), reverse = True)
bestCell = cells[0]["cell"]
# If additional ordering consideration, select new best cell
if "Top" in self.decisionModel:
cells = self.sortCellsByWealth(cells)
if "all" in self.debug or "agent" in self.debug:
self.printEthicalCellScores(cells)
bestCell = cells[0]["cell"]
if bestCell == None:
if greedyBestCell == None:
bestCell = cells[0]["cell"]
else:
bestCell = greedyBestCell
if "all" in self.debug or "agent" in self.debug:
print(f"Agent {self.ID} could not find an ethical cell")
return bestCell
def findBestFriend(self):
if self.tags == None:
return None
minHammingDistance = len(self.tags)
bestFriend = None
for friend in self.socialNetwork["friends"]:
# If already a friend, update Hamming Distance
if friend["hammingDistance"] < minHammingDistance:
bestFriend = friend
minHammingDistance = friend["hammingDistance"]
return bestFriend
def findCellsInRange(self, newCell=None):
cell = self.cell if newCell == None else newCell
vision = self.findVision()
movement = self.findMovement()
cellRange = min(min(vision, movement), self.cell.environment.maxCellDistance)
allCells = {}
if cellRange <= 0:
self.cellsInRange = allCells
return allCells
for i in range(1, cellRange + 1):
allCells.update(cell.ranges[i])
if newCell == None:
self.cellsInRange = allCells
return allCells
def findChildEndowment(self, mate):
parentEndowments = {
"aggressionFactor": [self.aggressionFactor, mate.aggressionFactor],
"baseInterestRate": [self.baseInterestRate, mate.baseInterestRate],
"depressionFactor": [self.depressionFactor, mate.depressionFactor],
"fertilityAge": [self.fertilityAge, mate.fertilityAge],
"fertilityFactor": [self.fertilityFactor, mate.fertilityFactor],
"infertilityAge": [self.infertilityAge, mate.infertilityAge],
"inheritancePolicy": [self.inheritancePolicy, mate.inheritancePolicy],
"lendingFactor": [self.lendingFactor, mate.lendingFactor],
"loanDuration": [self.loanDuration, mate.loanDuration],
"lookaheadFactor": [self.lookaheadFactor, mate.lookaheadFactor],
"maxAge": [self.maxAge, mate.maxAge],
"maxFriends": [self.maxFriends, mate.maxFriends],
"movement": [self.movement, mate.movement],
"movementMode": [self.movementMode, mate.movementMode],
"spiceMetabolism": [self.spiceMetabolism, mate.spiceMetabolism],
"sugarMetabolism": [self.sugarMetabolism, mate.sugarMetabolism],
"sex": [self.sex, mate.sex],
"tradeFactor": [self.tradeFactor, mate.tradeFactor],
"vision": [self.vision, mate.vision],
"visionMode": [self.visionMode, mate.visionMode],
"universalSpice": [self.universalSpice, mate.universalSpice],
"universalSugar": [self.universalSugar, mate.universalSugar],
"neighborhoodMode": [self.neighborhoodMode, mate.neighborhoodMode]
}
# These endowments should always come from the same parent for sensible outcomes
pairedEndowments = {
"decisionModel": [self.decisionModel, mate.decisionModel],
"decisionModelFactor": [self.decisionModelFactor, mate.decisionModelFactor],
"decisionModelLookaheadDiscount": [self.decisionModelLookaheadDiscount, mate.decisionModelLookaheadDiscount],
"decisionModelLookaheadFactor": [self.decisionModelLookaheadFactor, mate.decisionModelLookaheadFactor],
"decisionModelTribalFactor": [self.decisionModelTribalFactor, mate.decisionModelTribalFactor],
"selfishnessFactor" : [self.selfishnessFactor, mate.selfishnessFactor]
}
childEndowment = {"seed": self.seed}
randomNumberReset = random.getstate()
# Map configuration to a random number via hash to make random number generation independent of iteration order
if self.childEndowmentHashes == None:
self.childEndowmentHashes = {}
for config in parentEndowments:
hashed = hashlib.md5(config.encode())
hashNum = int(hashed.hexdigest(), 16)
self.childEndowmentHashes[config] = hashNum
for config in pairedEndowments:
hashed = hashlib.md5(config.encode())
hashNum = int(hashed.hexdigest(), 16)
self.childEndowmentHashes[config] = hashNum
for endowment in parentEndowments:
random.seed(self.childEndowmentHashes[endowment] + self.timestep)
index = random.randrange(2)
endowmentValue = parentEndowments[endowment][index]
childEndowment[endowment] = endowmentValue
pairedEndowmentIndex = -1
for endowment in pairedEndowments:
if pairedEndowmentIndex == -1:
random.seed(self.childEndowmentHashes[endowment] + self.timestep)
pairedEndowmentIndex = random.randrange(2)
endowmentValue = pairedEndowments[endowment][pairedEndowmentIndex]
childEndowment[endowment] = endowmentValue
# Each parent gives a portion of their starting endowment for child endowment
childStartingSugar = (self.startingSugar / (self.fertilityFactor * 2)) + (mate.startingSugar / (mate.fertilityFactor * 2))
childStartingSpice = (self.startingSpice / (self.fertilityFactor * 2)) + (mate.startingSpice / (mate.fertilityFactor * 2))
childEndowment["sugar"] = childStartingSugar
childEndowment["spice"] = childStartingSpice
hashed = hashlib.md5("tags".encode())
hashNum = int(hashed.hexdigest(), 16)
random.seed(hashNum + self.timestep)
childTags = []
childImmuneSystem = []
mateTags = mate.tags
mismatchBits = [0, 1]
if self.tags == None:
childTags = None
else:
for i in range(len(self.tags)):
if self.tags[i] == mateTags[i]:
childTags.append(self.tags[i])
else:
childTags.append(mismatchBits[random.randrange(2)])
childEndowment["tags"] = childTags
childEndowment["tagPreferences"] = self.tagPreferences
childEndowment["tagging"] = self.tagging
# Current implementation randomly assigns depressed state at agent birth
depressionPercentage = self.cell.environment.sugarscape.configuration["agentDepressionPercentage"]
depression = random.random()
if depression <= depressionPercentage:
childEndowment["depressionFactor"] = 1
else:
childEndowment["depressionFactor"] = 0
hashed = hashlib.md5("immuneSystem".encode())
hashNum = int(hashed.hexdigest(), 16)
random.seed(hashNum + self.timestep)
if self.startingImmuneSystem == None:
childImmuneSystem = None
else:
for i in range(len(self.immuneSystem)):
if self.startingImmuneSystem[i] == mate.startingImmuneSystem[i]:
childImmuneSystem.append(self.startingImmuneSystem[i])
else:
childImmuneSystem.append(mismatchBits[random.randrange(2)])
childEndowment["immuneSystem"] = childImmuneSystem
random.setstate(randomNumberReset)
return childEndowment
def findConflictHappiness(self):
if self.lastDoneCombat == self.cell.environment.sugarscape.timestep:
if self.findAggression() > 1:
if self.depressed == True:
return 0.5763
return 1
else:
return -1
return 0
def findCurrentSpiceDebt(self):
spiceDebt = 0
for creditor in self.socialNetwork["creditors"]:
spiceDebt += creditor["spiceLoan"] / creditor["loanDuration"]
return spiceDebt
def findCurrentSugarDebt(self):
sugarDebt = 0
for creditor in self.socialNetwork["creditors"]:
sugarDebt += creditor["sugarLoan"] / creditor["loanDuration"]
return sugarDebt
def findEmptyNeighborCells(self):
emptyCells = []
neighborCells = self.cell.neighbors.values()
for neighborCell in neighborCells:
if neighborCell.agent == None:
emptyCells.append(neighborCell)
return emptyCells
def findFamilyHappiness(self):
familyHappiness = 0
for child in self.socialNetwork["children"]:
if child.isAlive() == True:
if self.depressed == True:
familyHappiness += 0.5763
else:
familyHappiness += 1
if child.isSick() == True:
familyHappiness -= 0.5
if child.born == self.timestep:
if self.depressed == True:
familyHappiness += 0.5763
else:
familyHappiness += 1
else:
familyHappiness -= 1
for mate in self.socialNetwork["mates"]:
if mate.isAlive() == True:
familyHappiness += 1
if mate.isSick() == True:
familyHappiness -= 0.5
else:
familyHappiness -= 1
return math.erf(familyHappiness)
def findHammingDistanceInTags(self, neighbor):
if self.tags == None:
return 0
neighborTags = neighbor.tags
hammingDistance = 0
for i in range(len(self.tags)):
if self.tags[i] != neighborTags[i]:
hammingDistance += 1
return hammingDistance
def findHappiness(self):
return self.conflictHappiness + self.familyHappiness + self.healthHappiness + self.socialHappiness + self.wealthHappiness
def findHealthHappiness(self):
if self.isSick():
return -1
else:
if self.depressed == True:
return 0.5763
return 1
def findMarginalRateOfSubstitution(self):
spiceMetabolism = self.findSpiceMetabolism()
sugarMetabolism = self.findSugarMetabolism()
spiceNeed = self.spice / spiceMetabolism if spiceMetabolism > 0 else 1
sugarNeed = self.sugar / sugarMetabolism if sugarMetabolism > 0 else 1
# Trade factor may increase amount of spice traded for sugar in a transaction
self.marginalRateOfSubstitution = self.tradeFactor * (spiceNeed / sugarNeed)
def findMovement(self):
return max(0, self.movement + self.movementModifier)
def findNearestHammingDistanceInDisease(self, disease):
if self.immuneSystem == None:
return 0
diseaseTags = disease.tags
diseaseLength = len(diseaseTags)
bestHammingDistance = diseaseLength
bestRange = [0, diseaseLength - 1]
for i in range(len(self.immuneSystem) - diseaseLength):
hammingDistance = 0
for j in range(diseaseLength):
if self.immuneSystem[i + j] != diseaseTags[j]:
hammingDistance += 1
if hammingDistance < bestHammingDistance:
bestHammingDistance = hammingDistance
bestRange = [i, i + (diseaseLength - 1)]
diseaseStats = {"distance": bestHammingDistance, "start": bestRange[0], "end": bestRange[1]}
return diseaseStats
def findNeighborhood(self, newCell=None):
if newCell == None:
newNeighborhood = self.cellsInRange
else:
newNeighborhood = self.findCellsInRange(newCell)
neighborhood = []
for neighborCell in newNeighborhood.keys():
neighbor = neighborCell.agent
if neighbor != None and neighbor.isAlive() == True:
neighborhood.append(neighbor)
neighborhood.append(self)
if newCell == None:
self.neighborhood = neighborhood
return neighborhood
def findNewMarginalRateOfSubstitution(self, sugar, spice):
spiceMetabolism = self.findSpiceMetabolism()
sugarMetabolism = self.findSugarMetabolism()
spiceNeed = spice / spiceMetabolism if spiceMetabolism > 0 else 1
sugarNeed = sugar / sugarMetabolism if sugarMetabolism > 0 else 1
# If zero metabolism, do not try to trade
if spiceNeed == 1 and sugarNeed == 1:
return 1
# If no sugar or no spice, make missing resource the maximum need in MRS
elif spiceNeed == 0:
return spiceMetabolism
elif sugarNeed == 0:
return 1 / sugarMetabolism
return spiceNeed / sugarNeed
# TODO: Tally factors of hedons/dolors for given cell
def findPotentialNiceOfCell(self, cell):
potentialMates = []
# TODO: Trading nice capped at max number of resources traded to achieve MRS of 1
potentialTraders = []
# TODO: Lending nice capped at max amount of wealth agent can lend
potentialBorrowers = []
# TODO: Combat nice capped at wealth agent can score for tribe/neighborhood/etc.
potentialPrey = []
cellNeighborAgents = cell.findNeighborAgents()
aggression = self.findAggression()
for agent in cellNeighborAgents:
if agent.isAlive() == False:
continue
if self.isFertile() == True:
neighborCompatibility = self.isNeighborReproductionCompatible(agent)
emptyNeighborCells = agent.findEmptyNeighborCells()
if neighborCompatibility == True and len(emptyNeighborCells) != 0:
potentialMates.append(agent)
if self.isLender() == True and agent.isBorrower() == True:
potentialBorrowers.append(agent)
if self.tradeFactor > 0 and agent.tradeFactor > 0 and self.canTradeWithNeighbor(agent) == True:
potentialTraders.append(agent)
if aggression > 0 and self.tribe != agent.tribe and self.sugar + self.spice >= agent.sugar + agent.spice:
potentialPrey.append(agent)
# TODO: Make nice calculation more fine-grained than just potentialities
reproductionSugarCost = self.startingSugar / (self.fertilityFactor * 2) if self.fertilityFactor > 0 else 0
reproductionSpiceCost = self.startingSpice / (self.fertilityFactor * 2) if self.fertilityFactor > 0 else 0
maxReproductionAttemptsByResources = min(reproductionSugarCost, reproductionSpiceCost)
potentialMates = min(len(potentialMates), maxReproductionAttemptsByResources)
potentialNice = potentialMates + len(potentialTraders + potentialBorrowers + potentialPrey)
return potentialNice
def findRetaliatorsInVision(self):
retaliators = {}
for cell in self.cellsInRange.keys():
agent = cell.agent
if agent != None:
agentWealth = agent.sugar + agent.spice
if agent.tribe not in retaliators:
retaliators[agent.tribe] = agentWealth
elif retaliators[agent.tribe] < agentWealth:
retaliators[agent.tribe] = agentWealth
return retaliators
def findSocialHappiness(self):
if self.maxFriends == 0:
return 0