-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpysimultaneous.py
2719 lines (2483 loc) · 121 KB
/
pysimultaneous.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
# pysimultaneous.py
# Author: Andrew W. Lounsbury
# Date: 3/24/24
# Description: a class for handling simultaneous games with n players, n >= 2
from itertools import chain
from itertools import combinations
import numpy as np
import sympy
from sympy import solve
from sympy import simplify
import warnings
from pprint import pprint
import colorama
from colorama import init, Fore, Style
init()
def checkIfFloats(myList):
allFloats = True
t = ""
for i in range(len(myList)):
if not isinstance(myList[i], float):
t = type(myList[i]).__name__
if t != "float" or "int":
allFloats = False
break
if t == "int":
myList[i] = float(myList[i])
return (allFloats, t, myList)
class ListNode:
head = None
payoff = -1
bestResponse = True
next = None
def __init__(self, payoff = 0, bestResponse = True):
self.head = self
self.payoff = payoff
self.bestResponse = False
self.next = None
return
def append(self, payoff, bestResponse):
"""Appends a new node to the end of the linked list
Args:
payoff (float): the payoff
bestResponse (bool): whether the payoff is a best response or not
"""
newNode = ListNode(payoff, bestResponse)
if self.head is None:
self.head = newNode
return
curNode = self.head
while curNode.next:
curNode = curNode.next
curNode.next = newNode
return
def checkIfFloats(self):
allFloats = True
curNode = self.head
t = ""
while curNode:
if not isinstance(curNode.payoff, float):
t = type(curNode.payoff).__name__
if t != "float" or "int":
allFloats = False
break
if t == "int":
curNode.payoff = float(curNode.payoff)
return (allFloats, t, self)
def decapitate(self):
"""Removes the head ListNode
"""
if self.head == None:
return
self.head = self.head.next
return
def getListNode(self, index):
"""Gets the index-th node in the linked list
Args:
index (int): the desired index
Returns:
ListNode: the desired node
"""
if self.head == None:
return
curNode = self.head
pos = 0
if pos == index:
return curNode
else:
while(curNode != None and pos != index):
pos = pos + 1
curNode = curNode.next
if curNode != None:
return curNode
else:
print("Index not present")
return
def insertAtBeginning(self, payoff, bestResponse):
newNode = ListNode(payoff, bestResponse)
if self.head is None:
self.head = newNode
return
else:
newNode.next = self.head
self.head = newNode
return
def insertAtIndex(self, data, index):
newNode = ListNode(data)
curNode = self.head
pos = 0
if pos == index:
self.insertAtBeginning(data)
else:
while curNode != None and pos != index:
pos = pos + 1
curNode = curNode.next
if curNode != None:
newNode.next = curNode.next
curNode.next = newNode
else:
print("Index not present")
return
def load(self, payoffs):
self = ListNode(payoffs[0], False)
for payoff in payoffs[1:]:
self.append(payoff, False)
return self
def pop(self):
"""Removes the last node from the linked list
"""
if self.head is None:
return
curNode = self.head
while(curNode.next.next):
curNode = curNode.next
curNode.next = None
return
def print(self):
curNode = self.head
size = self.size()
x = 0
while curNode:
if x < size - 1:
print(curNode.payoff, end=", ")
else:
print(curNode.payoff, end=" ")
curNode = curNode.next
x += 1
return
def printBestResponse(self):
curNode = self.head
size = self.size()
x = 0
while(curNode):
if x < size - 1:
print(int(curNode.bestResponse), end=", ")
else:
print(int(curNode.bestResponse), end=" ")
curNode = curNode.next
x += 1
return
def printListNode(self, end=""):
print(self.payoff, end="")
return
def removeAtIndex(self, index):
if self.head == None:
return
curNode = self.head
pos = 0
if pos == index:
self.remove_first_node()
else:
while(curNode != None and pos != index):
pos = pos + 1
curNode = curNode.next
if curNode != None:
curNode.next = curNode.next.next
else:
print("Index not present")
return
def size(self):
size = 0
if(self.head):
current_node = self.head
while(current_node):
size = size + 1
current_node = current_node.next
return size
else:
return 0
def updateListNode(self, val, index):
curNode = self.head
pos = 0
if pos == index:
curNode.payoff = val
else:
while curNode != None and pos != index:
pos = pos + 1
curNode = curNode.next
if curNode != None:
curNode.payoff = val
else:
print("Index not present")
return
class Player:
kChoice = -1
numStrats = -1
rationality = -1
def __init__(self,numStrats = 2, rationality = 0):
self.kChoice = -1
self.numStrats = numStrats
self.rationality = rationality
class SimGame:
kMatrix = []
kOutcomes = [] # n-tuples that appear in kMatrix; won't be all of them
kStrategies = [[] for r in range(4)] # 2D matrix containing the strategies each player would play for k-levels 0, 1, 2, 3
maxRationality = 4
mixedEquilibria = []
numIESDSSteps = 0
numPlayers = -1
originalNumPlayers = -1
originalNumStrats = []
originalPayoffMatrix = []
outcomeProbabilities = [] # probability of each outcome in kMatrix stored in kOutcomes; P(i, j)
payoffMatrix = []
players = []
pureEquilibria = []
rationalityProbabilities = [0.0 for i in range(4)] # probability a player is L_i, i = 0, 1, 2, 3
removedCols = []
removedMatrices = []
removedRows = []
removedStrategies = []
strategyNames = []
def __init__(self, numPlayers = 2):
numStrats = [2 for i in range(numPlayers)]
rationalities = [0 for i in range(numPlayers)]
self.players = [Player(numStrats[i], rationalities[0]) for i in range(numPlayers)]
# Creating kStrategies' 4 arrays of lists of size numPlayers and setting rationalityProbabilities
for r in range(4):
# resizing self.kStrategies[r]
if numPlayers > len(self.kStrategies[r]):
self.kStrategies[r] += [None] * (numPlayers - len(self.kStrategies[r]))
else:
self.kStrategies[r] = self.kStrategies[r][:numPlayers]
self.rationalityProbabilities[r] = 0.0
# maximum rationality is 3, meaning there are 4 rationality levels
numMatrices = 1
if numPlayers > 2:
numMatrices = 4 ** self.numPlayers
for m in range(numMatrices):
self.kMatrix.append([])
for i in range(4):
self.kMatrix[m].append([])
for j in range(4):
ell = [-1 for x in range(self.numPlayers)]
self.kMatrix[m][i].append(ell)
# Initializing strategy names
if self.players[0].numStrats < 3:
self.strategyNames.append(["U", "D"])
else:
if self.players[0].numStrats == 3:
middle = ["M"]
else: # [0].numStrats > 3
middle = ["M" + str(i) for i in range(1, self.players[0].numStrats - 1)]
self.strategyNames.append(["U"] + middle + ["D"])
if self.players[1].numStrats < 3:
self.strategyNames.append(["L", "R"])
else:
if self.players[1].numStrats == 3:
center = ["C"]
else: # [1].numStrats > 3
center = ["C" + str(j) for j in range(1, self.players[1].numStrats - 1)]
self.strategyNames.append(["L"] + center + ["R"])
if self.numPlayers > 2:
for x in range(2, self.numPlayers):
center = []
if self.players[x].numStrats < 3:
center = []
elif self.players[x].numStrats == 3:
center = ["C(" + str(x + 1) + ")"]
else:
center = ["C(" + str(x + 1) + ", " + str(s) + ")" for s in range(1, self.players[x].numStrats - 1)]
self.strategyNames.append(["L(" + str(x + 1) + ")"] + center + ["R(" + str(x + 1) + ")"])
self.numPlayers = numPlayers
# Creating the payoff matrix
self.payoffMatrix = []
if self.numPlayers < 3:
matrix = []
for i in range(self.players[0].numStrats):
row = []
for j in range(self.players[1].numStrats):
outcome = ListNode()
outcome.append(0, True)
row.append(outcome)
matrix.append(row)
self.payoffMatrix.append(matrix)
else:
numMatrices = 1
for x in range(2, self.numPlayers):
numMatrices *= self.players[x].numStrats
for m in range(numMatrices):
matrix = []
for i in range(self.players[0].numStrats):
row = []
for j in range(self.players[1].numStrats):
outcome = ListNode()
for x in range(1, self.numPlayers):
outcome.append(0, True)
row.append(outcome)
matrix.append(row)
self.payoffMatrix.append(matrix)
self.originalNumPlayers = self.numPlayers
self.originalNumStrats = [self.players[x].numStrats for x in range(self.numPlayers)]
self.originalPayoffMatrix = self.payoffMatrix
return
def appendStrategy(self, x, payoffs):
"""Appends a strategy to player x + 1's list of strategies
Args:
x (int): the index of the player
payoffs (list of lists of ListNodes or list of lists of lists of ListNodes): the payoffs of the strategy to be appended, lists of outcomes
"""
if not isinstance(x, int):
print(Fore.RED + f"appendStrategy: invalid input. Expected an integer player index, but received {x} instead." + Style.RESET_ALL)
return
#################################################################
if x == 0: # add a new row to every matrix
# if list of list of lists, convert to list of list of ListNodes
if isinstance(payoffs[0][0], list):
newPayoffs = []
for row in payoffs:
newRow = []
for ell in row:
if isinstance(ell, list):
outcome = ListNode()
outcome = outcome.load(ell)
newRow.append(outcome)
elif isinstance(ell, ListNode):
newRow.append(ell)
else:
print(Fore.RED + f"appendStrategy: invalid input. The outcomes must be either lists or ListNodes. Received {type(ell).__name__} instead." + Style.RESET_ALL)
return
newPayoffs.append(newRow)
payoffs = newPayoffs
# payoffs will be a list of list of ListNodes that should be numPlayers-long.
inputValid = True
numMatrices = 1
for y in range(2, self.numPlayers):
numMatrices *= self.players[y].numStrats
correctNumRows = True
if len(payoffs) != numMatrices:
correctNumRows = False
correctNumOutcomes = True
for row in payoffs:
if len(row) != self.players[x].numStrats:
wrongNumOutcomes = len(row)
correctNumOutcomes = False
break
correctNumPayoffs = True
for row in payoffs:
for outcome in row:
if outcome.size() != self.numPlayers:
wrongSize = outcome.size()
correctNumPayoffs = False
allFloats = True
broke = False
wrongType = ""
for row in payoffs:
for outcome in row:
triple = outcome.checkIfFloats()
if not triple[0]:
wrongType = triple[1]
# if wrongType is integer, we can simply convert it to a float
if wrongType == "int":
outcome = triple[2]
else:
allFloats = False
broke = True
break
if broke:
break
if correctNumRows and correctNumOutcomes and correctNumPayoffs and isinstance(x, int) and x > -1 and x < self.numPlayers and isinstance(payoffs, list) and len(payoffs) > 0 and allFloats:
inputValid = True
else:
inputValid = False
if inputValid:
self.players[x].numStrats += 1
for m in range(numMatrices):
self.payoffMatrix[m].append(payoffs[m])
elif not correctNumRows:
if numMatrices == 1:
if len(payoffs) == 1:
print(Fore.RED + f"appendStrategy: invalid input. Expected {numMatrices} row, but {len(payoffs)} was provided." + Style.RESET_ALL)
else:
print(Fore.RED + f"appendStrategy: invalid input. Expected {numMatrices} row, but {len(payoffs)} were provided." + Style.RESET_ALL)
else:
if len(payoffs) == 1:
print(Fore.RED + f"appendStrategy: invalid input. Expected {numMatrices} rows, but {len(payoffs)} was provided." + Style.RESET_ALL)
else:
print(Fore.RED + f"appendStrategy: invalid input. Expected {numMatrices} rows, but {len(payoffs)} were provided." + Style.RESET_ALL)
elif not correctNumOutcomes:
if wrongNumOutcomes == 1:
print(Fore.RED + f"appendStrategy: invalid input. Expected {self.players[x].numStrats} outcomes. Received a row with {wrongNumOutcomes} outcome." + Style.RESET_ALL)
else:
print(Fore.RED + f"appendStrategy: invalid input. Expected {self.players[x].numStrats} outcomes. Received a row with {wrongNumOutcomes} outcomes." + Style.RESET_ALL)
elif not correctNumPayoffs:
if wrongSize == 1:
print(Fore.RED + f"appendStrategy: invalid input. expected outcomes with {self.numPlayers} payoffs. An outcome with {wrongSize} payoff was provided." + Style.RESET_ALL)
else:
print(Fore.RED + f"appendStrategy: invalid input. expected outcomes with {self.numPlayers} payoffs. An outcome with {wrongSize} payoffs was provided." + Style.RESET_ALL)
elif not isinstance(x, int):
print(Fore.RED + f"appendStrategy: invalid input. Expected an integer player index, but received {x} instead." + Style.RESET_ALL)
elif x < 0 or x >= self.numPlayers:
print(Fore.RED + f"appendStrategy: invalid input. Expected a player index between 0 and {self.numPlayers - 1}, but received {x} instead." + Style.RESET_ALL)
elif not isinstance(payoffs, list):
print(Fore.RED + f"appendStrategy: invalid input. Expected a list of payoffs, but received a {type(payoffs).__name__} instead" + Style.RESET_ALL)
elif len(payoffs) == 0:
print(Fore.RED + f"appendStrategy: invalid input. The payoffs parameter must be a nonempty list." + Style.RESET_ALL)
elif not allFloats:
print(Fore.RED + f"appendStrategy: invalid input. The payoffs must be floats. Received {wrongType} instead." + Style.RESET_ALL)
#################################################################
elif x == 1: # add a new column to every matrix
# if list of list of lists, convert to list of list of ListNodes
if isinstance(payoffs[0][0], list):
newPayoffs = []
for col in payoffs:
newCol = []
for ell in col:
if isinstance(ell, list):
outcome = ListNode()
outcome = outcome.load(ell)
newCol.append(outcome)
elif isinstance(ell, ListNode):
newCol.append(ell)
else:
print(Fore.RED + f"appendStrategy: invalid input. The outcomes must be either lists or ListNodes. Received {type(ell).__name__} instead." + Style.RESET_ALL)
return
newPayoffs.append(newCol)
payoffs = newPayoffs
inputValid = True
numMatrices = 1
for y in range(2, self.numPlayers):
numMatrices *= self.players[y].numStrats
correctNumCols = True
if len(payoffs) != numMatrices:
correctNumRows = False
correctNumOutcomes = True
for col in payoffs:
if len(col) != self.players[x].numStrats:
wrongNumOutcomes = len(col)
correctNumOutcomes = False
break
correctNumPayoffs = True
for row in payoffs:
for outcome in row:
if isinstance(outcome, ListNode):
if outcome.size() != self.numPlayers:
wrongSize = outcome.size()
correctNumPayoffs = False
elif isinstance(outcome, list):
if len(outcome) != self.numPlayers:
wrongSize = outcome.size()
correctNumPayoffs = False
else:
print(Fore.RED + f"appendStrategy: invalid input. Outcomes must be either lists or ListNodes. Received {type(outcome).__name__} instead." + Style.RESET_ALL)
allFloats = True
broke = False
wrongType = ""
for row in payoffs:
for outcome in row:
if isinstance(outcome, ListNode):
triple = outcome.checkIfFloats()
if not triple[0]:
wrongType = triple[1]
if wrongType == "int":
outcome = triple[2]
else:
allFloats = False
broke = True
break
elif isinstance(outcome, list):
triple = checkIfFloats(outcome)
if not triple[0]:
wrongType = triple[1]
if wrongType == "int":
outcome = triple[2]
else:
allFloats = False
broke = True
break
if broke:
break
if correctNumCols and correctNumOutcomes and correctNumPayoffs and isinstance(x, int) and x > -1 and x < self.numPlayers and isinstance(payoffs, list) and len(payoffs) > 0 and allFloats:
inputValid = True
else:
inputValid = False
if inputValid:
self.players[x].numStrats += 1
for m in range(numMatrices):
# FIXME
print("len 1: ", len(self.payoffMatrix[m]))
print("len 2: ", len(payoffs[m]))
for j in range(len(payoffs[0])):
print("\tj: ", j)
self.payoffMatrix[m][j].append(payoffs[m][j])
elif not correctNumCols:
if numMatrices == 1:
if len(payoffs) == 1:
print(Fore.RED + f"appendStrategy: invalid input. Expected {numMatrices} column, but {len(payoffs)} was provided." + Style.RESET_ALL)
else:
print(Fore.RED + f"appendStrategy: invalid input. Expected {numMatrices} column, but {len(payoffs)} were provided." + Style.RESET_ALL)
else:
if len(payoffs) == 1:
print(Fore.RED + f"appendStrategy: invalid input. Expected {numMatrices} columns, but {len(payoffs)} was provided." + Style.RESET_ALL)
else:
print(Fore.RED + f"appendStrategy: invalid input. Expected {numMatrices} columns, but {len(payoffs)} were provided." + Style.RESET_ALL)
elif not correctNumOutcomes:
if wrongNumOutcomes == 1:
print(Fore.RED + f"appendStrategy: invalid input. Expected {self.players[x].numStrats} outcomes. Received a column with {wrongNumOutcomes} outcome." + Style.RESET_ALL)
else:
print(Fore.RED + f"appendStrategy: invalid input. Expected {self.players[x].numStrats} outcomes. Received a column with {wrongNumOutcomes} outcomes." + Style.RESET_ALL)
elif not correctNumPayoffs:
if wrongSize == 1:
print(Fore.RED + f"appendStrategy: invalid input. expected outcomes with {self.numPlayers} payoffs. An outcome with {wrongSize} payoff was provided." + Style.RESET_ALL)
else:
print(Fore.RED + f"appendStrategy: invalid input. expected outcomes with {self.numPlayers} payoffs. An outcome with {wrongSize} payoffs was provided." + Style.RESET_ALL)
elif not isinstance(x, int):
print(Fore.RED + f"appendStrategy: invalid input. Expected an integer player index, but received {x} instead." + Style.RESET_ALL)
elif x < 0 or x >= self.numPlayers:
print(Fore.RED + f"appendStrategy: invalid input. Expected a player index between 0 and {self.numPlayers - 1}, but received {x} instead." + Style.RESET_ALL)
elif not isinstance(payoffs, list):
print(Fore.RED + f"appendStrategy: invalid input. Expected a list of payoffs, but received a {type(payoffs).__name__} instead" + Style.RESET_ALL)
elif len(payoffs) == 0:
print(Fore.RED + f"appendStrategy: invalid input. The payoffs parameter must be a nonempty list." + Style.RESET_ALL)
elif not allFloats:
print(Fore.RED + f"appendStrategy: invalid input. The payoffs must be floats. Received {wrongType} instead." + Style.RESET_ALL)
#################################################################
else: # x > 1 add new matrices
# if list of list of lists, convert to list of list of ListNodes
if isinstance(payoffs[0][0][0], list):
newPayoffs = []
for matrix in payoffs:
newMatrix = []
for col in matrix:
newCol = []
for ell in col:
if isinstance(ell, list):
outcome = ListNode()
outcome = outcome.load(ell)
newCol.append(outcome)
elif isinstance(ell, ListNode):
newCol.append(ell)
else:
print(Fore.RED + f"appendStrategy: invalid input. The outcomes must be either lists or ListNodes. Received {type(ell).__name__} instead." + Style.RESET_ALL)
return
newMatrix.append(newCol)
newPayoffs.append(newMatrix)
payoffs = newPayoffs
# We want to insert after the product of numStrats *below* player x + 1 for each number 1, 2,...,prodNumStratsAboveX, *plus* the number of matrices we've added
inputValid = True
numMatricesToAdd = 1
for y in range(2, self.numPlayers):
if y != x:
numMatricesToAdd *= self.players[y].numStrats
correctNumMatrices = True
if len(payoffs) != numMatricesToAdd:
correctNumMatrices = False
# Ensuring the arrays have the correct dimensions
correctNumRows = True
correctNumCols = True
broke = False
for matrix in payoffs:
if len(matrix) != self.players[0].numStrats:
wrongNumRows = len(matrix)
correctNumRows = False
for row in matrix:
if len(row) != self.players[1].numStrats:
wrongNumCols = len(row)
correctNumCols = False
broke = True
break
if broke:
break
correctNumPayoffs = True
for matrix in payoffs:
for row in matrix:
for outcome in row:
if outcome.size() != self.numPlayers:
wrongSize = outcome.size()
correctNumPayoffs = False
# Ensuring all the payoffs are floats
allFloats = True
broke = False
wrongType = ""
for matrix in payoffs:
for row in matrix:
for outcome in row:
triple = outcome.checkIfFloats()
if not triple[0]:
wrongType = triple[1]
if wrongType == "int":
outcome = triple[2]
else:
allFloats = False
broke = True
break
if broke:
if not broke:
broke = True
break
if broke:
break
# Input validation
if correctNumMatrices and correctNumRows and correctNumCols and correctNumPayoffs and isinstance(x, int) and x > -1 and x < self.numPlayers and isinstance(payoffs, list) and len(payoffs) > 0 and allFloats:
inputValid = True
else:
inputValid = False
if inputValid:
numMatricesBeforeX = 1
for y in range(2, x):
numMatricesBeforeX *= self.players[y].numStrats
numMatricesUpToX = 1
for y in range(2, x + 1):
numMatricesUpToX *= self.players[y].numStrats
productNumStratsAboveX = 1
for y in range(x + 1, self.numPlayers):
productNumStratsAboveX *= self.players[y].numStrats
numMatricesAdded = 0
multiplicand = 1
while len(payoffs) > 0:
# Inserting the new matrix
self.payoffMatrix.insert(numMatricesUpToX * multiplicand + numMatricesAdded, payoffs[0])
payoffs.pop(0)
numMatricesAdded += 1
if numMatricesAdded % numMatricesBeforeX == 0:
multiplicand += 1
self.players[x].numStrats += 1
elif not correctNumMatrices:
if numMatricesToAdd == 1:
if len(payoffs) == 1:
print(Fore.RED + f"appendStrategy: invalid input. Expected {numMatricesToAdd} array. Payoffs with {len(payoffs)} array were provided." + Style.RESET_ALL)
else:
print(Fore.RED + f"appendStrategy: invalid input. Expected {numMatricesToAdd} array. Payoffs with {len(payoffs)} arrays were provided." + Style.RESET_ALL)
else:
print(Fore.RED + f"appendStrategy: invalid input. Expected {numMatricesToAdd} arrays. Payoffs with {len(payoffs)} arrays were provided." + Style.RESET_ALL)
elif not correctNumRows and not correctNumCols:
print(Fore.RED + f"appendStrategy: invalid input. Expected arrays with {self.players[0].numStrats} rows and {self.players[1].numStrats} columns. An array with {wrongNumRows} rows and {wrongNumCols} columns was provided." + Style.RESET_ALL)
elif not correctNumRows and correctNumCols:
print(Fore.RED + f"appendStrategy: invalid input. Expected arrays with {self.players[0].numStrats} rows and {self.players[1].numStrats} columns. An array with {wrongNumRows} rows was provided." + Style.RESET_ALL)
elif correctNumRows and not correctNumCols:
print(Fore.RED + f"appendStrategy: invalid input. Expected arrays with {self.players[0].numStrats} rows and {self.players[1].numStrats} columns. An array with {wrongNumCols} columns was provided." + Style.RESET_ALL)
elif not correctNumRows:
if wrongNumRows == 1:
print(Fore.RED + f"appendStrategy: invalid input. Expected arrays with {self.players[0].numStrats} rows. Received a matrix with {wrongNumRows} row.")
else:
print(Fore.RED + f"appendStrategy: invalid input. Expected arrays with {self.players[0].numStrats} rows. Received a matrix with {wrongNumRows} rows.")
elif not correctNumCols:
if wrongNumRows == 1:
print(Fore.RED + f"appendStrategy: invalid input. Expected arrays with {self.players[0].numStrats} columns. Received a matrix with {wrongNumCols} colum.")
else:
print(Fore.RED + f"appendStrategy: invalid input. Expected arrays with {self.players[0].numStrats} rows. Received a matrix with {wrongNumCols} columns.")
elif not correctNumPayoffs:
if wrongSize == 1:
print(Fore.RED + f"appendStrategy: invalid input. expected outcomes with {self.numPlayers} payoffs. An outcome with {wrongSize} payoff was provided." + Style.RESET_ALL)
else:
print(Fore.RED + f"appendStrategy: invalid input. expected outcomes with {self.numPlayers} payoffs. An outcome with {wrongSize} payoffs was provided." + Style.RESET_ALL)
elif not isinstance(x, int):
print(Fore.RED + f"appendStrategy: invalid input. Expected an integer player index, but received {x} instead." + Style.RESET_ALL)
elif x < 0 or x >= self.numPlayers:
print(Fore.RED + f"appendStrategy: invalid input. Expected a player index between 0 and {self.numPlayers - 1}, but received {x} instead." + Style.RESET_ALL)
elif not isinstance(payoffs, list):
print(Fore.RED + f"appendStrategy: invalid input. Expected a list of payoffs, but received a {type(payoffs).__name__} instead" + Style.RESET_ALL)
elif len(payoffs) == 0:
print(Fore.RED + f"appendStrategy: invalid input. The payoffs parameter must be a nonempty list." + Style.RESET_ALL)
elif not allFloats:
print(Fore.RED + f"appendStrategy: invalid input. The payoffs must be floats. Received {wrongType} instead." + Style.RESET_ALL)
return
def computeBestResponses(self):
if self.numPlayers < 3:
for i in range(self.players[0].numStrats):
for j in range(self.players[1].numStrats):
br = self.isBestResponse([i, j])
for x in range(self.numPlayers):
self.payoffMatrix[0][i][j].getListNode(x).bestResponse = br[x]
else:
for m in range(len(self.payoffMatrix)):
for i in range(self.players[0].numStrats):
for j in range(self.players[1].numStrats):
br = self.isBestResponse([i, j] + self.toProfile(m)[2:])
for x in range(self.numPlayers):
self.payoffMatrix[m][i][j].getListNode(x).bestResponse = br[x]
return
def computeEquilibria(self):
equilibria = self.computePureEquilibria() + self.computeMixedEquilibria()
numEquilibria = len(equilibria)
if numEquilibria % 2 == 0:
warnings.warn(f"An even number ({numEquilibria}) of equilibria was returned. This indicates that the game is degenerate. Consider using another algorithm to investigate.", RuntimeWarning)
return equilibria
def computeKChoices(self):
computeKStrategies()
return
def computeKExpectedUtilities(self):
EU = [0.0 for x in range(self.numPlayers)]
for x in range(self.numPlayers):
EU[x] = 0.0
for num in range(len(self.kOutcomes)):
if self.numPlayers < 3:
curList = self.payoffMatrix[0][self.kOutcomes[num][0]][self.kOutcomes[num][1]]
else:
curList = payoffMatrix[self.toIndex(self.kOutcomes[num])][self.kOutcomes[num][0]][self.kOutcomes[num][1]]
EU[x] += curList.getListNode(x).payoff * self.outcomeProbabilities[num]
return EU
def computeKMatrix(self, probabilities):
"""Computes the kMatrix as well as kOutcomes in the process
"""
curEntry = []
temp = []
inOutcomes = False
probability = -1.0
self.kOutcomes = []
self.computeKStrategies()
for m in range(len(self.kMatrix)):
for r1 in range(4):
for r2 in range(4):
temp.append(self.kStrategies[r1][0])
temp.append(self.kStrategies[r2][1])
for x in range(2, self.numPlayers):
temp.append(kStrategies[kToProfile(m)[x]][x])
self.kMatrix[m][r1][r2] = temp
inOutcomes = False
for n in range(len(self.kOutcomes)):
if self.kOutcomes[n] == temp:
inOutcomes = True
if not inOutcomes:
self.kOutcomes.append(temp)
temp = []
self.computeOutcomeProbabilities()
EU = self.computeKExpectedUtilities()
self.probabilizeKChoices()
print()
for x in range(self.numPlayers):
print("EU_" + str(x) + " = " + str(EU[x]))
def computeKOutcomes(self):
"""Computes kOutcomes
"""
curEntry = []
temp = []
inOutcomes = False
probability = -1.0
EU = [0.0 for x in range(self.numPlayers)]
self.kOutcomes = []
self.computeKStrategies()
for m in range(len(self.kMatrix)):
for r1 in range(4):
for r2 in range(4):
temp.append(self.kStrategies[r1][0])
temp.append(self.kStrategies[r2][1])
for x in range(2, self.numPlayers):
temp.append(kStrategies[kToProfile(m)[x]][x])
inOutcomes = False
for n in range(len(self.kOutcomes)):
if self.kOutcomes[n] == temp:
inOutcomes = True
if not inOutcomes:
self.kOutcomes.append(temp)
temp = []
def computeKStrategies(self):
"""Computes the strategies that would be chosen for each rationality level
"""
self.computeBestResponses()
maxStrat = -10000000
num = -1
others = []
for r in range(4):
for x in range(self.numPlayers):
maxStrat = -10000000
if r == 0:
num = self.maxStrat(x) # num is what player x will do at L_0
self.kStrategies[0][x] = num
else:
# FIXME: finish after writing maxStrat function
others = [0 for y in range(self.numPlayers)]
for y in range(self.numPlayers):
if y == x:
others[y] = -1
else:
others[y] = self.kStrategies[r - 1][y]
# Finding the maximum in each row/column/array that has already been chosen
if x == 0:
for i in range(self.players[x].numStrats):
if self.payoffMatrix[self.toIndex(others)][i][others[1]].getListNode(x).bestResponse:
maxStrat = i
elif x == 1:
for j in range(self.players[x].numStrats):
if self.payoffMatrix[self.toIndex(others)][others[0]][j].getListNode(x).bestResponse:
maxStrat = j
else: # x > 1
for m in range(len(self.payoffMatrix)):
for i in range(self.players[0].numStrats):
for j in range(self.players[1].numStrats):
if self.payoffMatrix[m][others[0]][others[1]].getListNode(x).bestResponse:
maxStrat = self.toProfile(m)[x]
self.kStrategies[r][x] = maxStrat
if r == self.players[x].rationality:
self.players[x].kChoice = self.kStrategies[r][x]
return
def computeMixedEquilibria(self):
if self.numPlayers < 3:
pVars = []
for i in range(self.players[0].numStrats - 1):
pVars.append(sympy.symbols('p_' + str(i)))
qVars = []
for j in range(self.players[1].numStrats - 1):
qVars.append(sympy.symbols('q_' + str(j)))
# Getting the coefficients for the polynomials, EU_1_coefs[n] is the set of coefficients for the n-th polynomial
EU_1_coefs = []
EU_2_coefs = []
for i in range(self.players[0].numStrats):
EU_1_coefs.append([self.payoffMatrix[0][i][j].getListNode(0).payoff for j in range(self.players[1].numStrats)])
for j in range(self.players[0].numStrats):
EU_2_coefs.append([self.payoffMatrix[0][i][j].getListNode(1).payoff for i in range(self.players[0].numStrats)])
# Building polynomials for player 1
polynomials1 = []
for i in range(self.players[0].numStrats):
poly = 0
# building all but the last terms in poly
# it's range(nS1 - 1) because there are that many variables for all but he last term
for j in range(self.players[1].numStrats - 1):
poly += EU_1_coefs[i][j] * qVars[j]
# building the last 1 - q0 - q1 - ... - qnS1 term
lastTerm = 1
for j in range(self.players[1].numStrats - 1):
lastTerm -= qVars[j]
poly += EU_1_coefs[i][self.players[1].numStrats - 1] * lastTerm
polynomials1.append(poly)
# Building polynomials for player 2
polynomials2 = []
for j in range(self.players[1].numStrats):
poly = 0
# building all but the last terms in poly
# it's range(nS0 - 1) because there are that many variables for all but he last term
for i in range(self.players[0].numStrats - 1):
poly += EU_2_coefs[j][i] * pVars[i]
# building the last 1 - q0 - q1 - ... - qnS1 term
lastTerm = 1
for i in range(self.players[0].numStrats - 1):
lastTerm -= pVars[i]
poly += EU_2_coefs[j][self.players[0].numStrats - 1] * lastTerm
polynomials2.append(poly)
# Collecting the equations to be solved
equations1 = []
if self.players[0].numStrats % 2 == 0:
for i in range(0, self.players[0].numStrats, 2):
equations1.append(sympy.Eq(polynomials1[i], polynomials1[i + 1]))
else:
for i in range(0, self.players[0].numStrats - 1, 2):
equations1.append(sympy.Eq(polynomials1[i], polynomials1[i + 1]))
# adding an equation that contains the last polynomial
equations1.append(sympy.Eq(polynomials1[0], polynomials1[-1]))
equations2 = []
if self.players[1].numStrats % 2 == 0:
for j in range(0, self.players[1].numStrats, 2):
equations2.append(sympy.Eq(polynomials2[j], polynomials2[j + 1]))
else:
for j in range(0, self.players[1].numStrats - 1, 2):
equations2.append(sympy.Eq(polynomials2[j], polynomials2[j + 1]))
# adding an equation that contains the last polynomial
equations2.append(sympy.Eq(polynomials2[0], polynomials2[-1]))
# solving the equations
dict1 = sympy.solve(tuple(equations1), tuple(qVars), set=True)
dict2 = sympy.solve(tuple(equations2), tuple(pVars), set=True)
if dict1[1] == set() or dict2 == set():
return []
L1 = []
L2 = []
for j in range(1, len(dict1), 2):
L1.append(float(list(list(dict1[j])[0])[0]))
for i in range(1, len(dict2), 2):
L2.append(float(list(list(dict2[i])[0])[0]))
sum1 = sum(L1)
sum2 = sum(L2)
if sum1 == 0 or sum2 == 0:
return []
else:
L1.append(1 - sum1)
L2.append(1 - sum2)
return [[L1] + [L2]]
else: # numPLayers >= 3
if self.numPlayers < 53: # assuming numPlayers <= 26.
alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
alphabetVars = [[] for x in range(self.numPlayers)]
for x in range(self.numPlayers):
for k in range(self.players[x].numStrats - 1):
alphabetVars[x].append(sympy.symbols(alphabet[x] + "_" + str(k)))
# polynomials that are multiplied by the coefficients
polysToMultiply = [[] for x in range(self.numPlayers)]
for x in range(self.numPlayers):
for k in range(self.players[x].numStrats - 1):
polysToMultiply[x].append(alphabetVars[x][k])
lastPoly = 1
for k in range(self.players[x].numStrats - 1):
lastPoly -= polysToMultiply[x][k]
polysToMultiply[x].append(lastPoly)
# Getting the coefficients for the polynomials, EU_coefs[x][k] is the set of coefficients for the k-th polynomial for player x + 1, EU_polynomials[x][k] is the k-th polynomial for player x + 1
EU_coefs = [[] for x in range(self.numPlayers)]
EU_polynomials = [[] for x in range(self.numPlayers)]
# getting for player 1
for i in range(self.players[0].numStrats):
poly_coefs = []
poly = 0
for m in range(len(self.payoffMatrix)):
for j in range(self.players[1].numStrats):
coef = self.payoffMatrix[m][i][j].getListNode(0).payoff
poly_coefs.append(coef)
term = coef
for x in range(1, self.numPlayers):
if x == 1:
term *= polysToMultiply[x][j]