/
normal_form_game.py
2490 lines (2031 loc) · 95.3 KB
/
normal_form_game.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
r"""
Normal form games with N players.
This module implements a class for normal form games (strategic form games)
[NN2007]_. At present 3 algorithms are implemented to compute equilibria
of these games (``'lrs'`` - interfaced with the 'lrslib' library, ``'LCP'`` interfaced
with the 'gambit' library and support enumeration built in Sage). The architecture
for the class is based on the gambit architecture to ensure an easy transition
between gambit and Sage. At present the algorithms for the computation of equilibria
only solve 2 player games.
A very simple and well known example of normal form game is referred
to as the 'Battle of the Sexes' in which two players Amy and Bob
are modeled. Amy prefers to play video games and Bob prefers to
watch a movie. They both however want to spend their evening together.
This can be modeled using the following two matrices:
.. MATH::
A = \begin{pmatrix}
3&1\\
0&2\\
\end{pmatrix}
B = \begin{pmatrix}
2&1\\
0&3\\
\end{pmatrix}
Matrix `A` represents the utilities of Amy and matrix `B` represents the
utility of Bob. The choices of Amy correspond to the rows of the matrices:
* The first row corresponds to video games.
* The second row corresponds to movies.
Similarly Bob's choices are represented by the columns:
* The first column corresponds to video games.
* The second column corresponds to movies.
Thus, if both Amy and Bob choose to play video games: Amy receives a
utility of 3 and Bob a utility of 2. If Amy is indeed going to stick
with video games Bob has no incentive to deviate (and vice versa).
This situation repeats itself if both Amy and Bob choose to watch a movie:
neither has an incentive to deviate.
This loosely described situation is referred to as a Nash Equilibrium.
We can use Sage to find them, and more importantly, see if there is any
other situation where Amy and Bob have no reason to change their choice
of action:
Here is how we create the game in Sage::
sage: A = matrix([[3, 1], [0, 2]])
sage: B = matrix([[2, 1], [0, 3]])
sage: battle_of_the_sexes = NormalFormGame([A, B])
sage: battle_of_the_sexes
Normal Form Game with the following utilities: {(0, 1): [1, 1], (1, 0): [0, 0], (0, 0): [3, 2], (1, 1): [2, 3]}
To obtain the Nash equilibria we run the ``obtain_nash()`` method. In the
first few examples, we will use the 'support enumeration' algorithm.
A discussion about the different algorithms will be given later::
sage: battle_of_the_sexes.obtain_nash(algorithm='enumeration')
[[(0, 1), (0, 1)], [(3/4, 1/4), (1/4, 3/4)], [(1, 0), (1, 0)]]
If we look a bit closer at our output we see that a list of three
pairs of tuples have been returned. Each of these correspond to a
Nash Equilibrium, represented as a probability distribution over the
available strategies:
* `[(1, 0), (1, 0)]` corresponds to the first player only
playing their first strategy and the second player also only playing
their first strategy. In other words Amy and Bob both play video games.
* `[(0, 1), (0, 1)]` corresponds to the first player only
playing their second strategy and the second player also only playing
their second strategy. In other words Amy and Bob both watch movies.
* `[(3/4, 1/4), (1/4, 3/4)]` corresponds to players `mixing` their
strategies. Amy plays video games 75% of the time and Bob watches
movies 75% of the time. At this equilibrium point Amy and Bob will
only ever do the same activity `3/8` of the time.
We can use Sage to compute the expected utility for any mixed strategy
pair `(\sigma_1, \sigma_2)`. The payoff to player 1 is given by the
vector/matrix multiplication:
.. MATH::
\sigma_1 A \sigma_2
The payoff to player 2 is given by:
.. MATH::
\sigma_1 B \sigma_2
To compute this in Sage we have::
sage: for ne in battle_of_the_sexes.obtain_nash(algorithm='enumeration'):
....: print "Utility for {}: ".format(ne)
....: print vector(ne[0]) * A * vector(ne[1]), vector(ne[0]) * B * vector(ne[1])
Utility for [(0, 1), (0, 1)]:
2 3
Utility for [(3/4, 1/4), (1/4, 3/4)]:
3/2 3/2
Utility for [(1, 0), (1, 0)]:
3 2
Allowing players to play mixed strategies ensures that there will always
be a Nash Equilibrium for a normal form game. This result is called Nash's
Theorem ([N1950]_).
Let us consider the game called 'matching pennies' where two players each
present a coin with either HEADS or TAILS showing. If the coins show the
same side then player 1 wins, otherwise player 2 wins:
.. MATH::
A = \begin{pmatrix}
1&-1\\
-1&1\\
\end{pmatrix}
B = \begin{pmatrix}
-1&1\\
1&-1\\
\end{pmatrix}
It should be relatively straightforward to observe, that there is no
situation, where both players always do the same thing, and have no
incentive to deviate.
We can plot the utility of player 1 when player 2 is playing a mixed
strategy `\sigma_2 = (y, 1-y)` (so that the utility to player 1 for
playing strategy number `i` is given by the matrix/vector multiplication
`(Ay)_i`, ie element in position `i` of the matrix/vector multiplication
`Ay`) ::
sage: y = var('y')
sage: A = matrix([[1, -1], [-1, 1]])
sage: p = plot((A * vector([y, 1 - y]))[0], y, 0, 1, color='blue', legend_label='$u_1(r_1, (y, 1-y))$', axes_labels=['$y$', ''])
sage: p += plot((A * vector([y, 1 - y]))[1], y, 0, 1, color='red', legend_label='$u_1(r_2, (y, 1-y))$'); p
Graphics object consisting of 2 graphics primitives
We see that the only point at which player 1 is indifferent amongst
the available strategies is when `y = 1/2`.
If we compute the Nash equilibria we see that this corresponds to a point
at which both players are indifferent::
sage: A = matrix([[1, -1], [-1, 1]])
sage: B = matrix([[-1, 1], [1, -1]])
sage: matching_pennies = NormalFormGame([A, B])
sage: matching_pennies.obtain_nash(algorithm='enumeration')
[[(1/2, 1/2), (1/2, 1/2)]]
The utilities to both players at this Nash equilibrium
is easily computed::
sage: [vector([1/2, 1/2]) * M * vector([1/2, 1/2])
....: for M in matching_pennies.payoff_matrices()]
[0, 0]
Note that the above uses the ``payoff_matrices`` method
which returns the payoff matrices for a 2 player game::
sage: matching_pennies.payoff_matrices()
(
[ 1 -1] [-1 1]
[-1 1], [ 1 -1]
)
One can also input a single matrix and then a zero sum game is constructed.
Here is an instance of `Rock-Paper-Scissors-Lizard-Spock
<http://www.samkass.com/theories/RPSSL.html>`_::
sage: A = matrix([[0, -1, 1, 1, -1],
....: [1, 0, -1, -1, 1],
....: [-1, 1, 0, 1 , -1],
....: [-1, 1, -1, 0, 1],
....: [1, -1, 1, -1, 0]])
sage: g = NormalFormGame([A])
sage: g.obtain_nash(algorithm='enumeration')
[[(1/5, 1/5, 1/5, 1/5, 1/5), (1/5, 1/5, 1/5, 1/5, 1/5)]]
We can also study games where players aim to minimize their utility.
Here is the Prisoner's Dilemma (where players are aiming to reduce
time spent in prison)::
sage: A = matrix([[2, 5], [0, 4]])
sage: B = matrix([[2, 0], [5, 4]])
sage: prisoners_dilemma = NormalFormGame([A, B])
sage: prisoners_dilemma.obtain_nash(algorithm='enumeration', maximization=False)
[[(0, 1), (0, 1)]]
When obtaining Nash equilibrium there are 3 algorithms currently available:
* ``'lrs'``: Reverse search vertex enumeration for 2 player games. This
algorithm uses the optional 'lrslib' package. To install it type ``sage -i
lrslib`` at the command line. For more information see [A2000]_.
* ``'LCP'``: Linear complementarity program algorithm for 2 player games.
This algorithm uses the open source game theory package:
`Gambit <http://gambit.sourceforge.net/>`_ [MMAT2014]_. At present this is
the only gambit algorithm available in sage but further development will
hope to implement more algorithms
(in particular for games with more than 2 players). To install it
type ``sage -i gambit`` at the command line.
* ``'enumeration'``: Support enumeration for 2 player games. This
algorithm is hard coded in Sage and checks through all potential
supports of a strategy. Supports of a given size with a conditionally
dominated strategy are ignored. Note: this is not the preferred
algorithm. The algorithm implemented is a combination of a basic
algorithm described in [NN2007]_ and a pruning component described
in [SLB2008]_.
Below we show how the three algorithms are called::
sage: matching_pennies.obtain_nash(algorithm='lrs') # optional - lrslib
[[(1/2, 1/2), (1/2, 1/2)]]
sage: matching_pennies.obtain_nash(algorithm='LCP') # optional - gambit
[[(0.5, 0.5), (0.5, 0.5)]]
sage: matching_pennies.obtain_nash(algorithm='enumeration')
[[(1/2, 1/2), (1/2, 1/2)]]
Note that if no algorithm argument is passed then the default will be
selected according to the following order (if the corresponding package is
installed):
1. ``'lrs'`` (requires 'lrslib')
2. ``'enumeration'``
Here is a game being constructed using gambit syntax (note that a
``NormalFormGame`` object acts like a dictionary with pure strategy tuples as
keys and payoffs as their values)::
sage: f = NormalFormGame()
sage: f.add_player(2) # Adding first player with 2 strategies
sage: f.add_player(2) # Adding second player with 2 strategies
sage: f[0,0][0] = 1
sage: f[0,0][1] = 3
sage: f[0,1][0] = 2
sage: f[0,1][1] = 3
sage: f[1,0][0] = 3
sage: f[1,0][1] = 1
sage: f[1,1][0] = 4
sage: f[1,1][1] = 4
sage: f
Normal Form Game with the following utilities: {(0, 1): [2, 3], (1, 0): [3, 1], (0, 0): [1, 3], (1, 1): [4, 4]}
Once this game is constructed we can view the payoff matrices and solve the
game::
sage: f.payoff_matrices()
(
[1 2] [3 3]
[3 4], [1 4]
)
sage: f.obtain_nash(algorithm='enumeration')
[[(0, 1), (0, 1)]]
We can add an extra strategy to the first player::
sage: f.add_strategy(0)
sage: f
Normal Form Game with the following utilities: {(0, 1): [2, 3], (0, 0): [1, 3], (2, 1): [False, False], (2, 0): [False, False], (1, 0): [3, 1], (1, 1): [4, 4]}
If we do this and try and obtain the Nash equilibrium or view the payoff
matrices(without specifying the utilities), an error is returned::
sage: f.obtain_nash()
Traceback (most recent call last):
...
ValueError: utilities have not been populated
sage: f.payoff_matrices()
Traceback (most recent call last):
...
ValueError: utilities have not been populated
Here we populate the missing utilities::
sage: f[2, 1] = [5, 3]
sage: f[2, 0] = [2, 1]
sage: f.payoff_matrices()
(
[1 2] [3 3]
[3 4] [1 4]
[2 5], [1 3]
)
sage: f.obtain_nash()
[[(0, 0, 1), (0, 1)]]
We can use the same syntax as above to create games with
more than 2 players::
sage: threegame = NormalFormGame()
sage: threegame.add_player(2) # Adding first player with 2 strategies
sage: threegame.add_player(2) # Adding second player with 2 strategies
sage: threegame.add_player(2) # Adding third player with 2 strategies
sage: threegame[0, 0, 0][0] = 3
sage: threegame[0, 0, 0][1] = 1
sage: threegame[0, 0, 0][2] = 4
sage: threegame[0, 0, 1][0] = 1
sage: threegame[0, 0, 1][1] = 5
sage: threegame[0, 0, 1][2] = 9
sage: threegame[0, 1, 0][0] = 2
sage: threegame[0, 1, 0][1] = 6
sage: threegame[0, 1, 0][2] = 5
sage: threegame[0, 1, 1][0] = 3
sage: threegame[0, 1, 1][1] = 5
sage: threegame[0, 1, 1][2] = 8
sage: threegame[1, 0, 0][0] = 9
sage: threegame[1, 0, 0][1] = 7
sage: threegame[1, 0, 0][2] = 9
sage: threegame[1, 0, 1][0] = 3
sage: threegame[1, 0, 1][1] = 2
sage: threegame[1, 0, 1][2] = 3
sage: threegame[1, 1, 0][0] = 8
sage: threegame[1, 1, 0][1] = 4
sage: threegame[1, 1, 0][2] = 6
sage: threegame[1, 1, 1][0] = 2
sage: threegame[1, 1, 1][1] = 6
sage: threegame[1, 1, 1][2] = 4
sage: threegame
Normal Form Game with the following utilities: {(0, 1, 1): [3, 5, 8], (1, 1, 0): [8, 4, 6], (1, 0, 0): [9, 7, 9], (0, 0, 1): [1, 5, 9], (1, 0, 1): [3, 2, 3], (0, 0, 0): [3, 1, 4], (0, 1, 0): [2, 6, 5], (1, 1, 1): [2, 6, 4]}
The above requires a lot of input that could be simplified if there is
another data structure with our utilities and/or a structure to the
utilities. The following example creates a game with a relatively strange
utility function::
sage: def utility(strategy_triplet, player):
....: return sum(strategy_triplet) * player
sage: threegame = NormalFormGame()
sage: threegame.add_player(2) # Adding first player with 2 strategies
sage: threegame.add_player(2) # Adding second player with 2 strategies
sage: threegame.add_player(2) # Adding third player with 2 strategies
sage: for i, j, k in [(i, j, k) for i in [0,1] for j in [0,1] for k in [0,1]]:
....: for p in range(3):
....: threegame[i, j, k][p] = utility([i, j, k], p)
sage: threegame
Normal Form Game with the following utilities: {(0, 1, 1): [0, 2, 4], (1, 1, 0): [0, 2, 4], (1, 0, 0): [0, 1, 2], (0, 0, 1): [0, 1, 2], (1, 0, 1): [0, 2, 4], (0, 0, 0): [0, 0, 0], (0, 1, 0): [0, 1, 2], (1, 1, 1): [0, 3, 6]}
At present no algorithm has been implemented in Sage for games with
more than 2 players::
sage: threegame.obtain_nash()
Traceback (most recent call last):
...
NotImplementedError: Nash equilibrium for games with more than 2 players have not been implemented yet. Please see the gambit website (http://gambit.sourceforge.net/) that has a variety of available algorithms
There are however a variety of such algorithms available in gambit,
further compatibility between Sage and gambit is actively being developed:
https://github.com/tturocy/gambit/tree/sage_integration.
Note that the Gambit implementation of ``LCP`` can only handle integer
payoffs. If a non integer payoff is used an error will be raised::
sage: A = matrix([[2, 1], [1, 2.5]])
sage: B = matrix([[-1, 3], [2, 1]])
sage: g = NormalFormGame([A, B])
sage: g.obtain_nash(algorithm='LCP') # optional - gambit
Traceback (most recent call last):
...
ValueError: The Gambit implementation of LCP only allows for integer valued payoffs. Please scale your payoff matrices.
Other algorithms can handle these payoffs::
sage: g.obtain_nash(algorithm='enumeration')
[[(1/5, 4/5), (3/5, 2/5)]]
sage: g.obtain_nash(algorithm='lrs') # optional - lrslib
[[(1/5, 4/5), (3/5, 2/5)]]
It can be shown that linear scaling of the payoff matrices conserves the
equilibrium values::
sage: A = 2 * A
sage: g = NormalFormGame([A, B])
sage: g.obtain_nash(algorithm='LCP') # optional - gambit
[[(0.2, 0.8), (0.6, 0.4)]]
It is also possible to generate a Normal form game from a gambit Game::
sage: from gambit import Game # optional - gambit
sage: gambitgame= Game.new_table([2, 2]) # optional - gambit
sage: gambitgame[int(0), int(0)][int(0)] = int(8) # optional - gambit
sage: gambitgame[int(0), int(0)][int(1)] = int(8) # optional - gambit
sage: gambitgame[int(0), int(1)][int(0)] = int(2) # optional - gambit
sage: gambitgame[int(0), int(1)][int(1)] = int(10) # optional - gambit
sage: gambitgame[int(1), int(0)][int(0)] = int(10) # optional - gambit
sage: gambitgame[int(1), int(0)][int(1)] = int(2) # optional - gambit
sage: gambitgame[int(1), int(1)][int(0)] = int(5) # optional - gambit
sage: gambitgame[int(1), int(1)][int(1)] = int(5) # optional - gambit
sage: g = NormalFormGame(gambitgame) # optional - gambit
sage: g # optional - gambit
Normal Form Game with the following utilities: {(0, 1): [2.0, 10.0], (1, 0): [10.0, 2.0], (0, 0): [8.0, 8.0], (1, 1): [5.0, 5.0]}
For more information on using Gambit in Sage see: :mod:`Using Gambit in
Sage<sage.game_theory.gambit_docs>`. This includes how to access Gambit
directly using the version of iPython shipped with Sage and an explanation
as to why the ``int`` calls are needed to handle the Sage preparser.
Here is a slightly longer game that would take too long to solve with
``'enumeration'``. Consider the following:
An airline loses two suitcases belonging to two different travelers. Both
suitcases happen to be identical and contain identical antiques. An
airline manager tasked to settle the claims of both travelers explains
that the airline is liable for a maximum of 10 per suitcase, and in order
to determine an honest appraised value of the antiques the manager
separates both travelers so they can't confer, and asks them to write down
the amount of their value at no less than 2 and no larger than 10. He
also tells them that if both write down the same number, he will treat
that number as the true dollar value of both suitcases and reimburse both
travelers that amount.
However, if one writes down a smaller number than the other, this smaller
number will be taken as the true dollar value, and both travelers will
receive that amount along with a bonus/malus: 2 extra will be paid to the
traveler who wrote down the lower value and a 2 deduction will be taken
from the person who wrote down the higher amount. The challenge is: what
strategy should both travelers follow to decide the value they should
write down?
In the following we create the game (with a max value of 10) and solve it::
sage: K = 10 # Modifying this value lets us play with games of any size
sage: A = matrix([[min(i,j) + 2 * sign(j-i) for j in range(K, 1, -1)]
....: for i in range(K, 1, -1)])
sage: B = matrix([[min(i,j) + 2 * sign(i-j) for j in range(K, 1, -1)]
....: for i in range(K, 1, -1)])
sage: g = NormalFormGame([A, B])
sage: g.obtain_nash(algorithm='lrs') # optional - lrslib
[[(0, 0, 0, 0, 0, 0, 0, 0, 1), (0, 0, 0, 0, 0, 0, 0, 0, 1)]]
sage: g.obtain_nash(algorithm='LCP') # optional - gambit
[[(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0),
(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0)]]
The output is a pair of vectors (as before) showing the Nash equilibrium.
In particular it here shows that out of the 10 possible strategies both
players should choose the last. Recall that the above considers a reduced
version of the game where individuals can claim integer values from 10
to 2. The equilibrium strategy is thus for both players to state that
the value of their suitcase is 2.
Several standard Normal Form Games have also been implemented.
For more information on how to access these, see:
:mod:`Game Theory Catalog<sage.game_theory.catalog>`.
Included is information on the situation each Game models.
For example::
sage: g = game_theory.normal_form_games.PrisonersDilemma()
sage: g
Prisoners dilemma - Normal Form Game with the following utilities: ...
sage: d = {(0, 1): [-5, 0], (1, 0): [0, -5],
....: (0, 0): [-2, -2], (1, 1): [-4, -4]}
sage: g == d
True
sage: g.obtain_nash()
[[(0, 1), (0, 1)]]
We can easily obtain the best response for a player to a given strategy. In
this example we obtain the best responses for Player 1, when Player 2 uses two
different strategies::
sage: A = matrix([[3, 0], [0, 3], [1.5, 1.5]])
sage: B = matrix([[4, 3], [2, 6], [3, 1]])
sage: g = NormalFormGame([A, B])
sage: g.best_responses((1/2, 1/2), player=0)
[0, 1, 2]
sage: g.best_responses((3/4, 1/4), player=0)
[0]
Here we do the same for player 2::
sage: g.best_responses((4/5, 1/5, 0), player=1)
[0, 1]
We see that for the game `Rock-Paper-Scissors-Lizard-Spock
<http://www.samkass.com/theories/RPSSL.html>`_ any pure strategy has two best
responses::
sage: g = game_theory.normal_form_games.RPSLS()
sage: A, B = g.payoff_matrices()
sage: A, B
(
[ 0 -1 1 1 -1] [ 0 1 -1 -1 1]
[ 1 0 -1 -1 1] [-1 0 1 1 -1]
[-1 1 0 1 -1] [ 1 -1 0 -1 1]
[-1 1 -1 0 1] [ 1 -1 1 0 -1]
[ 1 -1 1 -1 0], [-1 1 -1 1 0]
)
sage: g.best_responses((1, 0, 0, 0, 0), player=0)
[1, 4]
sage: g.best_responses((0, 1, 0, 0, 0), player=0)
[2, 3]
sage: g.best_responses((0, 0, 1, 0, 0), player=0)
[0, 4]
sage: g.best_responses((0, 0, 0, 1, 0), player=0)
[0, 2]
sage: g.best_responses((0, 0, 0, 0, 1), player=0)
[1, 3]
sage: g.best_responses((1, 0, 0, 0, 0), player=1)
[1, 4]
sage: g.best_responses((0, 1, 0, 0, 0), player=1)
[2, 3]
sage: g.best_responses((0, 0, 1, 0, 0), player=1)
[0, 4]
sage: g.best_responses((0, 0, 0, 1, 0), player=1)
[0, 2]
sage: g.best_responses((0, 0, 0, 0, 1), player=1)
[1, 3]
Note that degenerate games can cause problems for most algorithms.
The following example in fact has an infinite quantity of equilibria which
is evidenced by the various algorithms returning different solutions::
sage: A = matrix([[3,3],[2,5],[0,6]])
sage: B = matrix([[3,3],[2,6],[3,1]])
sage: degenerate_game = NormalFormGame([A,B])
sage: degenerate_game.obtain_nash(algorithm='lrs') # optional - lrslib
[[(0, 1/3, 2/3), (1/3, 2/3)], [(1, 0, 0), (2/3, 1/3)], [(1, 0, 0), (1, 0)]]
sage: degenerate_game.obtain_nash(algorithm='LCP') # optional - gambit
[[(0.0, 0.3333333333, 0.6666666667), (0.3333333333, 0.6666666667)],
[(1.0, -0.0, 0.0), (0.6666666667, 0.3333333333)],
[(1.0, 0.0, 0.0), (1.0, 0.0)]]
sage: degenerate_game.obtain_nash(algorithm='enumeration')
[[(0, 1/3, 2/3), (1/3, 2/3)], [(1, 0, 0), (1, 0)]]
We can check the cause of this by using ``is_degenerate()``::
sage: degenerate_game.is_degenerate()
True
Note the 'negative' `-0.0` output by gambit. This is due to the numerical
nature of the algorithm used.
Here is an example with the trivial game where all payoffs are 0::
sage: g = NormalFormGame()
sage: g.add_player(3) # Adding first player with 3 strategies
sage: g.add_player(3) # Adding second player with 3 strategies
sage: for key in g:
....: g[key] = [0, 0]
sage: g.payoff_matrices()
(
[0 0 0] [0 0 0]
[0 0 0] [0 0 0]
[0 0 0], [0 0 0]
)
sage: g.obtain_nash(algorithm='enumeration')
[[(0, 0, 1), (0, 0, 1)], [(0, 0, 1), (0, 1, 0)], [(0, 0, 1), (1, 0, 0)],
[(0, 1, 0), (0, 0, 1)], [(0, 1, 0), (0, 1, 0)], [(0, 1, 0), (1, 0, 0)],
[(1, 0, 0), (0, 0, 1)], [(1, 0, 0), (0, 1, 0)], [(1, 0, 0), (1, 0, 0)]]
A good description of degenerate games can be found in [NN2007]_.
For demonstration and/or research purposes it might be useful to be able to
generate a random game with utilities given over a particular field::
sage: g = random_nfg(ZZ, (3, 3))
sage: g
Normal Form Game with the following utilities: ...
sage: g.payoff_matrices()
(
[ -1 1 -1] [ 2 -95 -2]
[-12 0 -1] [ 0 1 1]
[ -1 -1 -4], [ -2 4 -6]
)
The above takes the ring as the argument and a tuple showing the number of
strategies for each player. By default this game returns games that may be
degenerate however it is possible to specify if this is required::
sage: g = random_nfg(ZZ, (3, 3), degenerate=False)
sage: g.payoff_matrices()
(
[ 2 -1955 -1] [ 3 -22 2]
[ 1 18 0] [ 0 -2 28]
[ 1 -1 -4], [-357 -1 -2]
)
sage: g.is_degenerate()
False
sage: g = random_nfg(ZZ, (3, 3), degenerate=True)
sage: g.payoff_matrices()
(
[ 0 -2 -1] [-1 0 -2]
[ 0 27 1] [ 0 -1 1]
[ 0 -1 -1], [ 2 1 -2]
)
sage: g.is_degenerate()
True
Several standard Normal Form Games have also been implemented.
For more information on how to access these, see:
:mod:`Game Theory Catalog<sage.game_theory.catalog>`.
Included is information on the situation each Game models.
For example::
sage: g = game_theory.normal_form_games.PrisonersDilemma()
sage: g
Prisoners dilemma - Normal Form Game with the following utilities: ...
sage: d = {(0, 1): [-5, 0], (1, 0): [0, -5],
....: (0, 0): [-2, -2], (1, 1): [-4, -4]}
sage: g == d
True
sage: g.obtain_nash()
[[(0, 1), (0, 1)]]
REFERENCES:
.. [N1950] John Nash.
*Equilibrium points in n-person games.*
Proceedings of the National Academy of Sciences 36.1 (1950): 48-49.
.. [NN2007] Nisan, Noam, et al., eds.
*Algorithmic game theory.*
Cambridge University Press, 2007.
.. [A2000] Avis, David.
*A revised implementation of the reverse search vertex enumeration algorithm.*
Polytopes-combinatorics and computation
Birkhauser Basel, 2000.
.. [MMAT2014] McKelvey, Richard D., McLennan, Andrew M., and Turocy, Theodore L.
*Gambit: Software Tools for Game Theory, Version 13.1.2.*
http://www.gambit-project.org (2014).
.. [SLB2008] Shoham, Yoav, and Kevin Leyton-Brown.
*Multiagent systems: Algorithmic, game-theoretic, and logical foundations.*
Cambridge University Press, 2008.
AUTHOR:
- James Campbell and Vince Knight (06-2014): Original version
"""
#*****************************************************************************
# Copyright (C) 2014 James Campbell james.campbell@tanti.org.uk
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# http://www.gnu.org/licenses/
#*****************************************************************************
from collections import MutableMapping
from itertools import product
from parser import Parser
from sage.combinat.cartesian_product import CartesianProduct
from sage.misc.latex import latex
from sage.misc.misc import powerset
from sage.rings.all import QQ
from sage.structure.sage_object import SageObject
from sage.matrix.constructor import matrix
from sage.matrix.constructor import random_matrix
from sage.matrix.constructor import vector
from sage.misc.package import is_package_installed
from sage.misc.temporary_file import tmp_filename
try:
from gambit import Game
except ImportError:
Game = None
class NormalFormGame(SageObject, MutableMapping):
r"""
An object representing a Normal Form Game. Primarily used to compute the
Nash Equilibria.
INPUT:
- ``generator`` -- can be a list of 2 matrices, a single matrix or left
blank
"""
def __init__(self, generator=None):
r"""
Initializes a Normal Form game and checks the inputs.
EXAMPLES:
Can have games with more than 2 players::
sage: threegame = NormalFormGame()
sage: threegame.add_player(2) # Adding first player with 2 strategies
sage: threegame.add_player(2) # Adding second player with 2 strategies
sage: threegame.add_player(2) # Adding third player with 2 strategies
sage: threegame[0, 0, 0][0] = 3
sage: threegame[0, 0, 0][1] = 1
sage: threegame[0, 0, 0][2] = 4
sage: threegame[0, 0, 1][0] = 1
sage: threegame[0, 0, 1][1] = 5
sage: threegame[0, 0, 1][2] = 9
sage: threegame[0, 1, 0][0] = 2
sage: threegame[0, 1, 0][1] = 6
sage: threegame[0, 1, 0][2] = 5
sage: threegame[0, 1, 1][0] = 3
sage: threegame[0, 1, 1][1] = 5
sage: threegame[0, 1, 1][2] = 8
sage: threegame[1, 0, 0][0] = 9
sage: threegame[1, 0, 0][1] = 7
sage: threegame[1, 0, 0][2] = 9
sage: threegame[1, 0, 1][0] = 3
sage: threegame[1, 0, 1][1] = 2
sage: threegame[1, 0, 1][2] = 3
sage: threegame[1, 1, 0][0] = 8
sage: threegame[1, 1, 0][1] = 4
sage: threegame[1, 1, 0][2] = 6
sage: threegame[1, 1, 1][0] = 2
sage: threegame[1, 1, 1][1] = 6
sage: threegame[1, 1, 1][2] = 4
sage: threegame.obtain_nash()
Traceback (most recent call last):
...
NotImplementedError: Nash equilibrium for games with more than 2 players have not been implemented yet. Please see the gambit website (http://gambit.sourceforge.net/) that has a variety of available algorithms
Can initialise a game from a gambit game object::
sage: from gambit import Game # optional - gambit
sage: gambitgame= Game.new_table([2, 2]) # optional - gambit
sage: gambitgame[int(0), int(0)][int(0)] = int(5) # optional - gambit
sage: gambitgame[int(0), int(0)][int(1)] = int(8) # optional - gambit
sage: gambitgame[int(0), int(1)][int(0)] = int(2) # optional - gambit
sage: gambitgame[int(0), int(1)][int(1)] = int(11) # optional - gambit
sage: gambitgame[int(1), int(0)][int(0)] = int(10) # optional - gambit
sage: gambitgame[int(1), int(0)][int(1)] = int(7) # optional - gambit
sage: gambitgame[int(1), int(1)][int(0)] = int(5) # optional - gambit
sage: gambitgame[int(1), int(1)][int(1)] = int(5) # optional - gambit
sage: g = NormalFormGame(gambitgame) # optional - gambit
sage: g # optional - gambit
Normal Form Game with the following utilities: {(0, 1): [2.0, 11.0], (1, 0): [10.0, 7.0], (0, 0): [5.0, 8.0], (1, 1): [5.0, 5.0]}
TESTS:
Raise error if matrices aren't the same size::
sage: p1 = matrix([[1, 2], [3, 4]])
sage: p2 = matrix([[3, 3], [1, 4], [6, 6]])
sage: error = NormalFormGame([p1, p2])
Traceback (most recent call last):
...
ValueError: matrices must be the same size
Note that when initializing, a single argument must be passed::
sage: p1 = matrix([[1, 2], [3, 4]])
sage: p2 = matrix([[3, 3], [1, 4], [6, 6]])
sage: error = NormalFormGame(p1, p2)
Traceback (most recent call last):
...
TypeError: __init__() takes at most 2 arguments (3 given)
When initiating, argument passed must be a list or nothing::
sage: error = NormalFormGame({4:6, 6:9})
Traceback (most recent call last):
...
TypeError: Generator function must be a list, gambit game or nothing
When passing nothing, the utilities then need to be entered manually::
sage: game = NormalFormGame()
sage: game
Normal Form Game with the following utilities: {}
"""
self.players = []
self.utilities = {}
matrices = []
if generator is not None:
if type(generator) is not list and type(generator) is not Game:
raise TypeError("Generator function must be a list, gambit game or nothing")
if type(generator) is list:
if len(generator) == 1:
generator.append(-generator[-1])
matrices = generator
if matrices[0].dimensions() != matrices[1].dimensions():
raise ValueError("matrices must be the same size")
self._two_matrix_game(matrices)
elif type(generator) is Game:
game = generator
self._gambit_game(game)
def __delitem__(self, key):
r"""
This method is one of a collection that aims to make a game
instance behave like a dictionary which can be used if a game
is to be generated without using a matrix.
Here we set up deleting an element of the utilities dictionary::
sage: A = matrix([[2, 5], [0, 4]])
sage: B = matrix([[2, 0], [5, 4]])
sage: prisoners_dilemma = NormalFormGame([A, B])
sage: prisoners_dilemma
Normal Form Game with the following utilities: {(0, 1): [5, 0], (1, 0): [0, 5], (0, 0): [2, 2], (1, 1): [4, 4]}
sage: del(prisoners_dilemma[(0,1)])
sage: prisoners_dilemma
Normal Form Game with the following utilities: {(1, 0): [0, 5], (0, 0): [2, 2], (1, 1): [4, 4]}
"""
self.utilities.pop(key, None)
def __getitem__(self, key):
r"""
This method is one of a collection that aims to make a game
instance behave like a dictionary which can be used if a game
is to be generated without using a matrix.
Here we allow for querying a key::
sage: A = matrix([[2, 5], [0, 4]])
sage: B = matrix([[2, 0], [5, 4]])
sage: prisoners_dilemma = NormalFormGame([A, B])
sage: prisoners_dilemma[(0, 1)]
[5, 0]
sage: del(prisoners_dilemma[(0,1)])
sage: prisoners_dilemma[(0, 1)]
Traceback (most recent call last):
...
KeyError: (0, 1)
"""
return self.utilities[key]
def __iter__(self):
r"""
This method is one of a collection that aims to make a game
instance behave like a dictionary which can be used if a game
is to be generated without using a matrix.
Here we allow for iteration over the game to correspond to
iteration over keys of the utility dictionary::
sage: A = matrix([[2, 5], [0, 4]])
sage: B = matrix([[2, 0], [5, 4]])
sage: prisoners_dilemma = NormalFormGame([A, B])
sage: for key in prisoners_dilemma:
....: print "The strategy pair {} gives utilities {}".format(key, prisoners_dilemma[key])
The strategy pair (0, 1) gives utilities [5, 0]
The strategy pair (1, 0) gives utilities [0, 5]
The strategy pair (0, 0) gives utilities [2, 2]
The strategy pair (1, 1) gives utilities [4, 4]
"""
return iter(self.utilities)
def __setitem__(self, key, value):
r"""
This method is one of a collection that aims to make a game
instance behave like a dictionary which can be used if a game
is to be generated without using a matrix.
Here we set up setting the value of a key::
sage: A = matrix([[2, 5], [0, 4]])
sage: B = matrix([[2, 0], [5, 4]])
sage: prisoners_dilemma = NormalFormGame([A, B])
sage: del(prisoners_dilemma[(0,1)])
sage: prisoners_dilemma[(0,1)] = [5,6]
sage: prisoners_dilemma.payoff_matrices()
(
[2 5] [2 6]
[0 4], [5 4]
)
We can use the dictionary-like interface to overwrite a strategy
profile::
sage: prisoners_dilemma[(0,1)] = [-3,-30]
sage: prisoners_dilemma.payoff_matrices()
(
[ 2 -3] [ 2 -30]
[ 0 4], [ 5 4]
)
"""
self.utilities[key] = value
def __len__(self):
r"""
Return the length of the game to be the length of the utilities.
EXAMPLES::
sage: A = matrix([[2, 5], [0, 4]])
sage: B = matrix([[2, 0], [5, 4]])
sage: prisoners_dilemma = NormalFormGame([A, B])
sage: len(prisoners_dilemma)
4
"""
return len(self.utilities)
def _repr_(self):
r"""
Return the strategy_profiles of the game.
EXAMPLES:
Basic description of the game shown when calling the game instance::
sage: p1 = matrix([[1, 2], [3, 4]])
sage: p2 = matrix([[3, 3], [1, 4]])
sage: g = NormalFormGame([p1, p2])
sage: g
Normal Form Game with the following utilities: {(0, 1): [2, 3], (1, 0): [3, 1], (0, 0): [1, 3], (1, 1): [4, 4]}
"""
base_str = "Normal Form Game with the following utilities: {}"
return base_str.format(self.utilities)
def _latex_(self):
r"""
Return the LaTeX code representing the ``NormalFormGame``.
EXAMPLES:
LaTeX method shows the two payoff matrices for a two player game::
sage: A = matrix([[-1, -2], [-12, 2]])
sage: B = matrix([[1, 0], [1, -1]])
sage: g = NormalFormGame([A, B])
sage: latex(g)
\left(\left(\begin{array}{rr}
-1 & -2 \\
-12 & 2
\end{array}\right), \left(\begin{array}{rr}
1 & 0 \\
1 & -1
\end{array}\right)\right)
LaTeX method shows nothing interesting for games with more players::
sage: g = NormalFormGame()
sage: g.add_player(2) # Adding first player with 2 strategies
sage: g.add_player(2) # Adding second player with 2 strategies
sage: g.add_player(2) # Creating a game with three players
sage: latex(g)
\text{\texttt{Normal{ }Form{ }Game{ }...[False,{ }False,{ }False]{\char`\}}}}
"""
if len(self.players) == 2:
M1, M2 = self.payoff_matrices()
return "\left(%s, %s\\right)" % (M1._latex_(), M2._latex_())
return latex(self.__str__())
def _two_matrix_game(self, matrices):
r"""
Populate ``self.utilities`` with the values from 2 matrices.
EXAMPLES:
A small example game::
sage: A = matrix([[1, 0], [-2, 3]])
sage: B = matrix([[3, 2], [-1, 0]])
sage: two_game = NormalFormGame()
sage: two_game._two_matrix_game([A, B])
"""
self.players = []
self.utilities = {}
self.add_player(matrices[0].dimensions()[0])
self.add_player(matrices[1].dimensions()[1])
for strategy_profile in self.utilities:
self.utilities[strategy_profile] = [matrices[0][strategy_profile],
matrices[1][strategy_profile]]
def _gambit_game(self, game):
r"""
Creates a ``NormalFormGame`` object from a Gambit game.
TESTS::
sage: from gambit import Game # optional - gambit
sage: testgame = Game.new_table([2, 2]) # optional - gambit
sage: testgame[int(0), int(0)][int(0)] = int(8) # optional - gambit
sage: testgame[int(0), int(0)][int(1)] = int(8) # optional - gambit
sage: testgame[int(0), int(1)][int(0)] = int(2) # optional - gambit
sage: testgame[int(0), int(1)][int(1)] = int(10) # optional - gambit
sage: testgame[int(1), int(0)][int(0)] = int(10) # optional - gambit
sage: testgame[int(1), int(0)][int(1)] = int(2) # optional - gambit
sage: testgame[int(1), int(1)][int(0)] = int(5) # optional - gambit
sage: testgame[int(1), int(1)][int(1)] = int(5) # optional - gambit
sage: g = NormalFormGame() # optional - gambit
sage: g._gambit_game(testgame) # optional - gambit
sage: g # optional - gambit
Normal Form Game with the following utilities:
{(0, 1): [2.0, 10.0], (1, 0): [10.0, 2.0],
(0, 0): [8.0, 8.0], (1, 1): [5.0, 5.0]}
"""