-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroshambot.py
1204 lines (1047 loc) · 39.5 KB
/
roshambot.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 random
import cmath
import numpy as np
from cmath import *
class game_master:
"""
A and B are two RPS objects which will play against each other.
"""
def __init__(self, A, B, ngames=1001, early_end=False):
self.score=[0,0]
self.move_list=[ '', '' ]
self.A=A
self.B=B
self.ngames=ngames
self.moves='rps'
self.trump={'r':'p', 'p':'s', 's':'r'}
self.early_end=early_end
def run_game(self):
"""
Run N games between the two players.
"""
for i in xrange(self.ngames):
a_move=self.A.get_move()
self.move_list[0]+=a_move
b_move=self.B.get_move()
self.move_list[1]+=b_move
#Tell the players the outcomes.
#Both players think they are player one.
a_i=self.moves.index(a_move)
b_j=self.moves.index(b_move)
if (a_i-1)%3==b_j:
self.score[0]+=1
self.A.report( a_move, b_move, 1 )
self.B.report( b_move, a_move, -1 )
elif (a_i+1)%3==b_j:
self.score[1]+=1
self.A.report( a_move, b_move, -1 )
self.B.report( b_move, a_move, 1 )
else:
self.A.report( a_move, b_move, 0 )
self.B.report( b_move, a_move, 0 )
if self.early_end and ( (self.score[0]>self.ngames/2) or (self.score[1]>self.ngames/2)):
break
return self.score
def plot(self, colors=['red', 'blue'], interval=None):
p=plot([])
n=len(self.move_list[0])
if interval==None:
if n>=100:
interval=int(0.01*n)
else:
interval=1
running_score=[0,0]
last_a_point=(0,0)
last_b_point=(0,0)
a_point=(0,0)
b_point=(0,0)
for i in range(n):
a=self.move_list[0][i]
b=self.move_list[1][i]
if a==self.trump[b]:
running_score[0]+=1
elif b==self.trump[a]:
running_score[1]+=1
s=sum(running_score)
if i%interval==0 and s!=0 and i>0:
last_a_point=a_point
last_b_point=b_point
a_point=(i, 1.0*running_score[0]/s)
b_point=(i, 1.0*running_score[1]/s)
p+=point2d( a_point, color='red')
p+=line2d( (last_a_point, a_point), color=colors[0] )
p+=point2d( b_point, color='blue')
p+=line2d( (last_b_point, b_point), color=colors[1] )
return p
def trial(self, n=10):
game_wins=[0,0]
for i in range(n):
A.__init__()
B.__init__()
self.score=[0,0]
self.run_game()
if score[0]>score[1]:
game_wins[0]+=1
else:
game_wins[1]+=1
return game_wins
#-------------------------------------------------------------------------------
#----RPS players.
#-------------------------------------------------------------------------------
#TODO: Probably the morally right thing to do would be to make an abstract class...
class rps_random:
"""
This is our model for an RPS player, from which others inherit.
The required methods for any player are `name`, `get_move`, and `report`.
`name` gives a human-ish name to the bot, used in `__repr__` calls.
`get_move` returns one of r,p,s.
`report` is used by the `game_master` to report back the outcome of a move.
"""
def __init__(self):
self.move_list=[ '', '' ]
self.score=[0,0]
self.rps='rps'
def name(self):
"""
The `name` method gives the bot a name, used by `__repr__`.
Or elsewhere, if you want.
"""
return 'Randy'
def __repr__(self):
return 'A player named '+self.name()
def trump(self, symbol):
"""
Symbol is one of `r`, `p`, `s`.
Return the symbol that beats provided symbol.
"""
if symbol=='r': return 'p'
if symbol=='p': return 's'
if symbol=='s': return 'r'
def get_move(self):
"""
Choose a move.
"""
return random.choice('rps')
def report(self, my_move, opponent_move, outcome):
"""
The `report` method allows the `game_master` to report the outcome of the
last play. The report consists of your move, the opponent's move, and
who won. (Which is redundant information, but so there.)
"""
self.move_list[0]+=my_move
self.move_list[1]+=opponent_move
if outcome==1:
self.score[0]+=1
elif outcome==-1:
self.score[1]+=1
#-------------------------------------------------------------------------------
class beat_last(rps_random):
"""
Plays to beat the opponent's last move. This is actually a pretty common
pattern amongst flustered human players.
Named Michael Jackson for 'Just Beat It'.
"""
def name(self):
return 'Michael Jackson'
def get_move(self):
"""
Choose a move.
"""
if len(self.move_list[0])==0:
return random.choice('rps')
return self.trump(self.move_list[1][-1])
#-------------------------------------------------------------------------------
class reverse_beat_last(rps_random):
"""
Like MJ, but plays to _lose_ to the last move played by the opponent.
"""
def name(self):
mj='noskcaJ leahciM'
return mj
def get_move(self):
"""
Choose a move.
"""
if len(self.move_list[0])==0:
return random.choice('rps')
return self.trump(self.trump(self.move_list[1][-1]))
#-------------------------------------------------------------------------------
class all_rock(rps_random):
"""
Good ol' rock. Nothing beats rock.
"""
def name(self):
return 'Bart Simpson'
def get_move(self):
"""
Choose a move.
"""
return 'r'
#-------------------------------------------------------------------------------
class all_scissors(rps_random):
"""
It's hard to have an interesting strategy when your hands are scissors.
"""
def name(self):
return 'Edward Scissorhands'
def get_move(self):
"""
Choose a move.
"""
return 's'
#-------------------------------------------------------------------------------
class all_paper(rps_random):
"""
Poor predicatble Bart. Always plays rock.
"""
def name(self):
return 'Lisa Simpson'
def get_move(self):
"""
Choose a move.
"""
return 'p'
#-------------------------------------------------------------------------------
class rock_622(rps_random):
"""
Homer on the other hand has learned from experience, and only plays rock
60% of the time, with his other plays split evenly between paper and scissors.
"""
def name(self):
return 'Smrt Homer'
def get_move(self):
"""
Choose a move.
"""
x=random.random()
if x<0.6: return 'r'
if x<0.8: return 'p'
return 's'
#-------------------------------------------------------------------------------
class random_bias(rps_random):
"""
This bot generates a random bias at creation, and then takes rps at random
according to the bias.
"""
def name(self):
return 'Random bias ' + str(tuple([round(x,2) for x in self.cutoffs]))
def __init__(self):
self.move_list=[ '', '' ]
self.score=[0,0]
self.rps='rps'
self.cutoffs=[ random.random(), random.random() ]
self.cutoffs.sort()
self.cutoffs=tuple(self.cutoffs)
def get_move(self):
"""
Choose a move.
"""
x=random.random()
if x<self.cutoffs[0]: return 'r'
if x>self.cutoffs[1]: return 's'
return 'p'
#-------------------------------------------------------------------------------
class switchbot(rps_random):
"""
Switchbot is a random bot, but never plays the same thing twice in a row.
Also pretty common behaviour for humans...
"""
def name(self):
return 'Switchbot'
def get_move(self):
if len(self.move_list[0])==0: return random.choice('rps')
a=self.move_list[0][-1]
if a=='r': return random.choice('ps')
if a=='p': return random.choice('rs')
if a=='s': return random.choice('rp')
#-------------------------------------------------------------------------------
class counter_switchbot(rps_random):
"""
Like switchbot, but plays anything except the opponent's last move.
"""
def name(self):
return 'Counter Switchbot'
def get_move(self):
if len(self.move_list[0])==0: return random.choice('rps')
a=self.move_list[1][-1]
if a=='r': return random.choice('ps')
if a=='p': return random.choice('rs')
if a=='s': return random.choice('rp')
#-------------------------------------------------------------------------------
class rfind(rps_random):
"""
Search backwards through the move list for the longest possible string
matching the current game state, and predict that the opponent will play
the same way as before.
This algorithm kills many learning algorithms, because learning algorithms
'stabilize' and tend to play the same plays given the same data once
they've seen enough data.
"""
def name(self):
return 'Rfind'
def get_move(self):
if len(self.move_list[0])==0: return random.choice('rps')
#Kill last letter to avoid the trivial match.
n=len(self.move_list[1])
upper_bound=min(20, n-1)
m=-1
for k in range(upper_bound, 1, -1):
match_string=self.move_list[1][-k:]
m=self.move_list[1].rfind(match_string,0,-1)
if m!=-1:
break
if m==-1: return random.choice('rps')
return self.trump( self.move_list[1][m+k] )
#-------------------------------------------------------------------------------
class kcycle(rps_random):
"""
Plays to beat move k steps ago from either own or opponent's move list.
If beating own move list, this bot is periodic with period 3*k.
`k` and `stream` are chosen randomly at startup, or can be selected.
`k` is the length of cycle to use.
`stream` should be 0 for the player's own move list, or 1 for the opponent's
move list.
"""
def name(self):
return 'Lance '+str(self.k)+'-Strong '+str(self.stream)
#Plays to beat most frequent opponent move.
def __init__(self, k=None, stream=None):
self.move_list=[ '', '' ]
self.score=[0,0]
self.moves='rps'
self.opponent_move_totals=[0,0,0]
if stream==None:
self.stream=1
if random.random()>.5: self.stream=0
else:
self.stream=stream
if k==None:
self.k=random.randint(1,50)
else:
self.k=k
def get_move(self):
if len(self.move_list[0])<self.k: return random.choice('rps')
return self.trump( self.move_list[self.stream][-self.k] )
#-------------------------------------------------------------------------------
class freqbot(rps_random):
"""
Simply plays to beat whatever the most frequent opponent move has been to
this point.
"""
def name(self):
return 'Freqbot'
def __init__(self):
self.move_list=[ '', '' ]
self.score=[0,0]
self.moves='rps'
self.opponent_move_totals=[0,0,0]
def report(self, my_move, opponent_move, outcome):
self.move_list[0]+=my_move
self.move_list[1]+=opponent_move
i=('rps').index(opponent_move)
self.opponent_move_totals[i]+=1
if outcome==1:
self.score[0]+=1
elif outcome==-1:
self.score[1]+=1
def get_move(self):
if len(self.move_list[0])==0: return random.choice('rps')
i=self.opponent_move_totals.index( max(self.opponent_move_totals) )
if i==0: return 'p'
if i==1: return 's'
return 'r'
#-------------------------------------------------------------------------------
class humanbot(rps_random):
"""
This is a bot with a fixed probability distribution based on gameplay of
actual humans. Probabilities are based on move sequences of maximum
length five, which is certainly more than I can keep track of....
"""
def name(self):
return 'ho0m4nbot'
def __init__(self):
self.move_list=[ '', '' ]
self.score=[0,0]
self.moves='rps'
f=file('openings.txt')
R=[r.split('|') for r in f.readlines()][2:]
move_totals=[ [0,0,0] for i in range(6) ]
data=[ {} for i in range(6) ]
for i in range(len(R)):
R[i]=[ s.strip() for s in R[i] ]
#n=number of moves in current sequence.
n=len(R[i][0])
for j in range(3):
R[i][j+2]=int(R[i][j+2])+1
#Data file tracks info in order 'rsp' instead of 'rps'. go figure.
data[n][(R[i][0],R[i][1])]=(R[i][2],R[i][4],R[i][3])
move_totals[n][0]+=R[i][2]
move_totals[n][1]+=R[i][4]
move_totals[n][2]+=R[i][3]
self.move_totals=move_totals
self.data=data
def compute_probabilities(self):
#Using Bayes' theorem, we get that:
# P(H|D) = #(observations of D and H) / #(observations of D)
if len(self.move_list[1])<5:
D=(self.move_list[0],self.move_list[1])
else:
D=(self.move_list[0][-5:],self.move_list[1][-5:])
n=len(D[0])
while not self.data[n].has_key(D):
D=(D[0][1:], D[1][1:])
n-=1
if self.data[n].has_key(D):
N = sum(self.data[n][D])
P = [ 1.0*x/N for x in self.data[n][D] ]
return P
return [1.0/3 for i in range(3)]
def get_move(self):
P=self.compute_probabilities()
#choose a random guess using probabilities.
x=random.random()
if x<P[0]: return 'r'
if x<P[0]+P[1]: return 'p'
return 's'
#-------------------------------------------------------------------------------
class terminator(humanbot):
"""
A machine designed to kill humans.
"""
def name(self):
return 'Terminator'
def compute_probabilities(self):
#Use the same data as humanbot, but with relative roles reversed, so as
#to come to the same decision as humanbot.
if len(self.move_list[1])<5:
D=(self.move_list[1],self.move_list[0])
else:
D=(self.move_list[1][-5:],self.move_list[0][-5:])
n=len(D[0])
while not self.data[n].has_key(D):
D=(D[0][1:], D[1][1:])
n-=1
if self.data[n].has_key(D):
N = sum(self.data[n][D])
P = [ 1.0*x/N for x in self.data[n][D] ]
return P
return [1.0/3 for i in range(3)]
def get_move(self):
P=self.compute_probabilities()
#choose a random guess using probabilities.
x=random.random()
if x<P[0]: return self.trump('r')
if x<P[0]+P[1]: return self.trump('p')
return self.trump('s')
#-------------------------------------------------------------------------------
class bayes(rps_random):
"""
Keep track of all of opponent's k-move sequences and following moves.
Use the collected data to estimate probability of each future move.
Predict a move using the estimated probability distribution, then play
the trumping move.
Takes a 'memory' parameter which determines the length of history to keep track of.
The number of tracked variables is exponential in the memory parameter;
we create 3^(k+1) bins to track.
This allows (much) better performance up to a point, but then drops off when
the number of bins grows too large relative to the number of games played.
"""
def __init__(self, memory=1):
self.move_list=[ '', '' ]
self.score=[0,0]
self.moves='rps'
#memory is the number of moves to keep track of in computing probabilities.
#Our data requirements for high confidence are exponential in this variable,
#but should eventually get better predictions with higher memory
self.memory=memory
last=['r', 'p', 's']
mtuples=last[:]
#Generate all rps tuples of length memory
for i in xrange(self.memory-1):
new=[]
for a in last: new.append( 'r' + a )
for a in last: new.append( 'p' + a )
for a in last: new.append( 's' + a )
last=new
self.mtuples=last
#Observed mtuples of opponent moves, initialized at one observation each.
self.data={ a: [1,1,1] for a in self.mtuples }
def name(self):
return 'Bayes '+str(self.memory)
def report(self, my_move, opponent_move, outcome):
self.move_list[0]+=my_move
self.move_list[1]+=opponent_move
i=('rps').index(opponent_move)
if outcome==1:
self.score[0]+=1
elif outcome==-1:
self.score[1]+=1
#Update data tables.
if len(self.move_list[0])>self.memory:
#m is the previous move
new_data = self.move_list[1][-self.memory-1:-1]
j='rps'.index( opponent_move )
self.data[new_data][j]+=1
if outcome==1:
self.score[0]+=1
elif outcome==-1:
self.score[1]+=1
def compute_probabilities(self):
#Using Bayes' theorem, we get that:
# P(H|D) = #(observations of D and H) / #(observations of D)
if len(self.move_list[1])<self.memory:
return [1.0/3 for i in xrange(3)]
D = self.move_list[1][-self.memory:]
N = sum(self.data[D])
P = [ 1.0*x/N for x in self.data[D] ]
return P
def get_move(self):
if len(self.move_list[0])<self.memory: return random.choice('rps')
P=self.compute_probabilities()
#choose a random guess using probabilities.
x=random.random()
if x<P[0]: return self.trump( 'r' )
if x<P[0]+P[1]: return self.trump( 'p' )
return self.trump( 's' )
#-------------------------------------------------------------------------------
class double_bayes(rps_random):
"""
Like `bayes`, but also keeps track of its own moves in computing the
probability distribution. As a result, tends to not have enough data to
find patterns in 1000 games if `memory` is greater than 2.
"""
def __init__(self, memory=1):
self.move_list=[ '', '' ]
self.score=[0,0]
self.moves='rps'
#memory is the number of moves to keep track of in computing probabilities.
#Our data requirements for high confidence are exponential in this variable,
#but should eventually get better predictions with higher memory...
self.memory=memory
last=['r', 'p', 's']
mtuples=last[:]
#Generate all rps tuples of length memory
for i in xrange(self.memory-1):
new=[]
for a in last: new.append( 'r' + a )
for a in last: new.append( 'p' + a )
for a in last: new.append( 's' + a )
last=new
self.mtuples=last
#Observed mtuples of opponent moves, initialized at one observation each.
keys=[]
for a in self.mtuples:
for b in self.mtuples:
keys.append( (a,b) )
self.data={ (a,b): [1,1,1] for (a,b) in keys }
def name(self):
return 'Double Bayes '+str(self.memory)
def report(self, my_move, opponent_move, outcome):
self.move_list[0]+=my_move
self.move_list[1]+=opponent_move
i=('rps').index(opponent_move)
if outcome==1:
self.score[0]+=1
elif outcome==-1:
self.score[1]+=1
#Update data tables.
if len(self.move_list[0])>self.memory:
#m is the previous move
a = self.move_list[0][-self.memory-1:-1]
b = self.move_list[1][-self.memory-1:-1]
new_data=(a,b)
j='rps'.index( opponent_move )
self.data[new_data][j]+=1
if outcome==1:
self.score[0]+=1
elif outcome==-1:
self.score[1]+=1
def compute_probabilities(self):
#Using Bayes' theorem, we get that:
# P(H|D) = #(observations of D and H) / #(observations of D)
if len(self.move_list[1])<self.memory:
return [1.0/3 for i in xrange(3)]
a = self.move_list[0][-self.memory:]
b = self.move_list[1][-self.memory:]
D=(a,b)
N = sum(self.data[D])
P = [ 1.0*x/N for x in self.data[D] ]
return P
def get_move(self):
if len(self.move_list[0])<self.memory: return random.choice('rps')
P=self.compute_probabilities()
#choose a random guess using probabilities.
x=random.random()
if x<P[0]: return self.trump( 'r' )
if x<P[0]+P[1]: return self.trump( 'p' )
return self.trump( 's' )
#-------------------------------------------------------------------------------
class max_freq_bayes(bayes):
"""
Like `bayes`, but always plays to beat the play with highest probability
given the current game state. Thus, named the Frequentist.
"""
def name(self):
return 'Frequentist '+str(self.memory)
def get_move(self):
if len(self.move_list[0])<self.memory: return random.choice('rps')
P=self.compute_probabilities()
#return most likely guess.
return self.trump( 'rps'[P.index(max(P))] )
#-------------------------------------------------------------------------------
class naive_bayes(rps_random):
"""
Keeps track of number of times H is played when the ith previous move was J,
for each i in 1 to a specified k.
Then applies the naive Bayes algorithm on this data. The number of pieces
of information is now only linear in k instead of exponential, but we obtain
a cruder estimate of the probabilities involved using the Naive Bayes
approximation.
In fact, we are losing the time data when we apply naive Bayes, so this ends
up being a really bad algorithm.
"""
def __init__(self, memory=1):
self.rps='rps'
self.move_list=[ '', '' ]
self.score=[0,0]
#memory is the number of moves to keep track of in computing probabilities.
self.memory=memory
mtuples=[]
#Generate all rps tuples of length memory
for i in xrange(self.memory):
for a in self.rps: mtuples.append( (i,a) )
self.mtuples=tuple(mtuples)
#Observed mtuples of opponent moves, initialized at one observation each.
self.data={ a: [1,1,1] for a in self.mtuples }
#Number of observations: should be sum of all data vectors.
self.N=3*len(self.mtuples)
#Total number of r,p,s thrown by opponent.
self.opponent_move_totals=[len(self.mtuples) for i in range(3)]
def name(self):
return 'Naive Bayes '+str(self.memory)
def report(self, my_move, opponent_move, outcome):
self.move_list[0]+=my_move
self.move_list[1]+=opponent_move
if outcome==1:
self.score[0]+=1
elif outcome==-1:
self.score[1]+=1
#Update data tables.
x=('rps').index(opponent_move)
for i in range(min([len(self.move_list[1])-2, self.memory])):
#update entry for the ith-to-last move.
move=self.move_list[1][-i-2]
self.data[(i,move)][x]+=1
#Increased one more data observation.
self.N+=1
self.opponent_move_totals[x]+=1
if outcome==1:
self.score[0]+=1
elif outcome==-1:
self.score[1]+=1
def compute_probabilities(self):
#Using Naive Bayes' theorem, we get that:
# P(H|D) = scaling_factor* prod( #(observations of D_i and H) / #(observations of D_i) )
if len(self.move_list[1])==1:
return [1.0/3 for i in xrange(3)]
P=[1,1,1]
n=len(self.mtuples)
#We insert some random historical data if we haven't played many games yet.
#This keeps us flexible while figuring out our strategy.
if len(self.move_list[1])<self.memory:
D=''
diff=self.memory-len(self.move_list[1])
for i in range(diff): D+=random.choice('rps')
D+=self.move_list[1][-self.memory+diff:]
else:
D = self.move_list[1][-self.memory:]
for i in xrange(3):
#prior
P[i]=self.opponent_move_totals[i]*1.0/self.N
#product of conditionals.
for j in range(self.memory):
d=self.data[ (j, D[-j]) ]
P[i] *= 1.0*d[i]/self.opponent_move_totals[i]
#Normalize by probability of data.
scaling_term=sum(P)
P=[p/scaling_term for p in P]
return P
def get_move(self):
if len(self.move_list[0])<self.memory: return random.choice('rps')
P=self.compute_probabilities()
#return most likely guess.
return self.trump( 'rps'[P.index(max(P))] )
#-------------------------------------------------------------------------------
z1=(-.5+sqrt(3)/2*1j)
z2=(-.5-sqrt(3)/2*1j)
cd={'r':1, 'p':z1, 's':z2}
class diaconis(rps_random):
"""
`diaconis` is similar to the bayes bot, but we search for interesting
factors instead of just using the last few moves.
Factor search uses representations of C_3^m, and iterates over certain
substrings of the move list to try to find useful factors for predicting
the next opponent move.
`M` determines the maximum length substring to use for the factor search.
With 1000 rounds of RPS, M should probably be 3 or 4.
`max_width` determines the maximum width of substrings of the move list
to search in. A high max_width reduces the number of examples that the
algorithm will be able to learn on when the width of a substring is
high relative to the number of moves that have occurred.
"""
def __init__(self, M=3, max_width=10):
self.move_list=[ '', '' ]
#To simplify computations later, we keep track of the game history in a
#merged move list, where each pair of entries is one turn of play.
#Odd entries are self's moves, and even entries are opponent moves.
self.merged_move_list=''
self.score=[0,0]
self.rps='rps'
self.M=M
self.max_width=max_width
self.character_tables=[ self.c3m_character_table(m) for m in range(M+1) ]
self.factors=self.generate_factors(M,max_width,1)
self.last_checked_factor=[-1 for i in range(M+1)]
self.best_factor=None
self.best_factor_score=0
def name(self):
return 'Persi'
#----------
#The next chunk of code is set-up for doing our fourier transforms on C_3^m
#and translating between strings and numbers.
#----------
def num_to_tuple(self, n, m=None):
"""
Take a number and generate a tuple of digits base 3 (in reverse order).
Specifying `m` pads the end of the tuple with zeroes if the length of
the tuple is less than `m`.
"""
if n==0:
L=[0]
else:
L=[]
for k in range(ceil(log(n,3).real)+1):
L.append( ((n//3**k))%3 )
while len(L)<m: L.append(0)
if n==0: return tuple(L)
while L[-1]==0 and len(L)>m: L.pop()
return tuple(L)
#This line works well in sage but not pure python:
#return tuple([int(x) for x in n.str(3)])
def tuple_to_num(self, t):
"""
Given a tuple of base 3 digits in reverse order,
return the corresponding integer.
"""
return sum([3**(k)*t[k] for k in range(len(t))])
def tuple_to_rps(self, t):
"""
Given a tuple of base 3 digits in reverse order,
return a string of `r`, `p`, and `s` characters.
"""
out=''
for i in t:
out+='rps'[i]
return out
def num_to_rps(self, n, m=None):
"""
Given a number,
return a string of `r`, `p`, and `s` characters.
"""
t=self.num_to_tuple(n,m)
return self.tuple_to_rps(t)
def c3m_character_table(self, m):
"""
Generate the character table for C_{3^m}. Note that the table contains
(3^m)^2 entries!
On my (slow) cpu, m=5 takes .5s, and m=6 takes 5.63s.
Our class generates the appropriate tables at init time, so you should
use those whenever possible:
They are stored in `self.character_tables`
"""
M=[]
zeta=[exp(i*2*pi*1j/3) for i in range(3)]
elm_list=[self.num_to_tuple(i,m) for i in range(3**m)]
for i in range(3**m):
#Work with the ith representation.
t=elm_list[i]
#t gives the exponents used for each of the m generators.
row = [ prod([zeta[x[j]]**t[j] for j in range(m)]) for x in elm_list ]
M.append(tuple(row))
return np.matrix(M)
def f_from_string(self, s=None, m=None, gaps=None, target=1):
"""
Generate a likelihood function on C_3^m from the string s.
`gaps` is a list of length m-1, indicating the number of characters
to skip after each letter when generating a substring of size m.
For example, if m=4 and gaps=[2,0,3], then a resulting string
will look like 'r..ps...p.r', skipping 2 after the first character, 0
after the second character, and 3 after the third character. The final
entry does nothing, since there's no fifth character in the substring.
The resulting string is then 'rpspr'.
`target` determines whether to try to predict my own moves (`0`) or the
opponent's moves (`1`).
"""
f={}
if s==None: s=self.merged_move_list
if m==None: m=self.M
nmoves=len(s)/2
if gaps==None: gaps=[0 for i in range(m-1)]
gaps=list(gaps)
while len(gaps)>m: gaps.pop()
#width is the total width of the substrings as they sit in `s`.
#For example, the substring 'r..ps...p.r' has width 11.
width=m+sum(gaps)
#Width determines the number of samples we can take:
total_samples=len(s)-width
#We will take slices of `s` and use a set of local indices on the slices.
local_indices=[gaps[0]]
gaps=gaps[1:]
for i in gaps: local_indices.append(local_indices[-1]+i+1)
#Track the total number of r,p,s, assuming we've seen every possible
#combination of data and outcome once prior to the start of the game.
rps_totals=[3**m,3**m,3**m]
for i in range(nmoves-width-2):
local=s[2*i:2*i+width]
w=''
for j in local_indices: w+=local[j]
key=w[:]
out=i+int(math.ceil(width/2))
if target==1:
output=s[2*out+1]
else:
output=s[2*out]
q='rps'.index(output)
rps_totals[q]+=1
if key in f.keys():
f[key][q]+=1
else:
f[key]=[1,1,1]
f[key][q]+=1
#Now create a matrix of probabilities from f..
g={}
output=[]
for i in range(3**m):
s=self.num_to_rps(i,m)
if f.has_key(s):
t=sum(f[s])
output.append([1.0*x/t for x in f[s]])
else:
output.append([1.0/3 for x in range(3)])
output=np.matrix(output)
return (f,output)
def fhat(self, M, absolute=False):
"""
Generate the Fourier coefficients for a matrix M generated by the
`f_from_string` method.
f a function on C_3^m, given as a complex vector of lenth 3^m. The
Fourier transform is just the product of the character table time f.
"""
#m=ceil(log(f.size, 3).real)
fhat=(self.character_tables[1]*M.transpose()).transpose()
if absolute:
sq=lambda a: (a*a.conjugate()).real
sqv=np.vectorize(sq)
return sqv(fhat)
return fhat
#---------
# And now we place code for actual in-play factor selection and move generation.
#---------
def evaluate_factor(self, m, gaps, target=1):
"""
Evaluate the viability of a factor.
The factor consists of:
`m`: The number of moves involved in the factor
`gaps`: List of size of gaps between the `m` moves
`target`: 0 for predicting own move, 1 for predicting the opponent's move.