-
Notifications
You must be signed in to change notification settings - Fork 1
/
compute_stats.py
1641 lines (1380 loc) · 60.9 KB
/
compute_stats.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
import collections
from deck_info import DeckInfo, BOW_HOMEWORLDS, GOOD_TYPES, PROD_TYPES, EXPANSIONS, BaseDeckInfo, GSDeckInfo, RvIDeckInfo, BoWDeckInfo, DISCARDABLE_CARDS
from name_handler import name_handler
import tableau_scorer
import math
import pprint
import random
import re
import os
import simplejson as json
import shutil
import sys
import time
outputDir = 'output'
runDir = os.getcwd()
EXP_ABBREV = ['base', 'tgs', 'rvi', 'bow']
EXP_ABBREV_EXPANSIONS = zip(EXP_ABBREV, EXPANSIONS)
BASE_SKILL = 1500
MOVEMENT_CONST = 15
GS_GOALS = [
'Most Prod worlds',
'Most Developments',
'Most Military',
'Most Rares or Novelties',
'First 5 vps',
'First 6 pt dev',
'First all phase powers',
'First discard',
'First all worlds',
'First 3 aliens',
]
RVI_GOALS = GS_GOALS + [
'Most Explore Powers',
'Most Rebel Military Worlds',
'First 4 Prod goods',
'First 3 Uplift',
'First 8 Tableau'
]
BOW_GOALS = RVI_GOALS + [
'Most Consume Powers',
'Most Prestige',
'First 2 Prestige + 3 vps',
'First peace / war',
'First military influence'
]
MATCH_TRAILING_DIGITS = re.compile('(\d+)$')
# move to deck info
TITLE = 'RFTGStats.com: Race for the Galaxy Statistics'
JS_INCLUDE = (
'<script type="text/javascript" src="card_attrs.js"></script>'
'<script type="text/javascript" src="genie_analysis.js"></script>'
)
CSS = '<link rel="stylesheet" type="text/css" href="style.css" />'
INTRO_BLURB = """<h2>Introduction</h2>
<p>Hi, welcome to Race for the Galaxy
statistics page by <a href="player_rrenaud.html">rrenaud</a>,
<a href="player_Danny.html">Danny</a>, and
<a href="player_Aragos.html">Aragos</a>.
All of the data here is collected from the wonderful
<a href="http://genie.game-host.org">Genie online Race for the Galaxy server
</a>, the <a href="http://flexboardgames.com/Rftg.html">Flexboardgames Race
for the Galaxy server</a>, or <a href="http://www.keldon.net/rftg">Keldon's Race for the Galaxy server</a>. The code that computes this information is
open source and available
at <a href="http://code.google.com/p/rftgstats">the rftgstats google code
project</a>. These stats look best when viewed with a recent version of
<a href="http://mozilla.org">Firefox 3</a> or <a
href="http://www.google.com/chrome">Chrome</a>. The raw data from genie is
available <a href="condensed_games.json.gz">here</a>. The raw data from flex is
available <a href="condensed_flex.json.gz">here</a>. The raw data from keldon is available <a href="condensed_keldon.json.gz">here</a>. Contributions
welcome!</p>"""
SIX_DEV_BLURB = """<h3>Sub-analysis</h3>
<p>Here is a graph of the number of points each <a href="six_dev_analysis.html">
six cost development scores</a> when it both when a 6 dev is played and when
not played."""
CARDS_GAME_SIZE = """<p>Here is an animated graph of the winning
rate/play rate as a function of <a href="game_size.html">the number of
players</a>."""
CARDS_GOALS = """<p>Here is an animated graph on the win rate play/rate as
a function of the <a href="goals_vs_nongoals.html">inclusion of goals</a>."""
WINNING_RATES_BLURB = """<h3>A brief discussion about <i>Winning Rates</i></h3>
<p>
An <i>n</i> player game is worth <i>n</i> points. The wining rate is the
number of points accumulated divided by the number of games played.
Thus, if you win a 4 player game, lose a 3 player game, and lose a 2
player game, your winning rate would (4 + 0 + 0) / 3 = 1.33.
Thus, a totally average and optimally balanced homeworld will have a
winning rate of near 1 after many games. Likewise, a player whose skill
is totally representative of the distribution of the player population will
have a winning rate of 1.
<h3><i>Skill Normalized</i> win rates</h3>
<p>One problem with win rates is that they do not scale well with player skill.
Therefore, I compute a prior probability to win the game for each player based
on the player ratings before the start of a game. Consider a hypothetical game
between players rrenaud, fairgr, and kingcong. Assume that rating system
predicts that the players will win with .3, .5, and .2 respectively. Then if
fairgr wins, he (or specifically in the winning rate graph, the cards he played)
will be awarded 3 points, and will be expected to win 1.5 points. If rrenaud
wins, the cards he played will be awarded 3 points, and expected to win
.9 points. If kingcong wins, her cards wil be awarded 3 points, and are
expected to win .6 points. I call the the total awarded poins divided by
the expected number of points the <i>Skill normalized</i> win rate, and it
is what is plotted in the card graph below."""
WINNING_RATE_VS_PLAY_RATE_DESCRIPTION = """<p>
<h2>Skill normalized card winning rate vs play rate</h2>
<p>This graph shows data by analyzing end game tableaus. </p>
<p>Strong cards have high skill normalized winning rates and
tend to be played more often.
You can click on a card's icon to see its name.</p>
<p>Cards played as homeworlds are excluded from the data, so that they don't
totally skew the play rate.
<p>The absolute play rate is divided by the number of instances of the card
in the deck, so investment credits is divided by 2, and contact specialist
is divided by 3. By doing so, cheap developments do not dominate the play
frequency.</p>
<p>
"""
HOMEWORLD_WINNING_RATE_DESCRIPTION = """<p>Influence of goal on winning rate
of homeworld.</p>
<p>The baseline winning rate of each homeworld is the fat dot.
The winning rate with the goal is the end of the segment without
the dot. Hence, you can tell the absolute rate of winning by the
end of the line, and the relative change by the magnitude of the line.</p>
"""
RATING_BLURB = """<h3>Rating Methodology</h3>
<p>Each column comes from running an Elo rating algorithm on a
filtered set of games. The first number is the rating and the second number is
the percentile for that rating. To display a rating, 10 2-player games,
7 3-player, or 5 4-player games are required.
These differ from the Genie rating in at
least the following ways.
<ul>
<li>The ratings are computed with an Elo system with K value 15. I am
unsure about what the Genie server uses.
<font size=-1>Eventually, I'll play around with fitting some more sophisticated
models to the data.</font></li>
<li>Ties do not count.</li>
<li>In multiplayer games, a second place is scored the same as a last place
finish. Win or bust!</li>
<li>The ratings are computed in game number order (which is ordered by game
start time),
rather than game end time, as Genie does. Since there are some players who game
the Genie system, I suspect this method may be slightly more accurate simply
because players do not have much of an incentive to game it.</li>
<li>This includes games from flex, which are currently all assumed to occur
after the last game on genie. Similarly, all games from keldon are assumed to occur after the last game on flex.</li>
</ul>
"""
def GoalVector(goals):
ret = [0] * len(GS_GOALS)
for goal in goals:
ret[GS_GOALS.index(goal)] = 1
return ret
def GetAndRemove(dict, key):
ret = dict[key]
del dict[key]
return ret
class FixedExpansionGameSet:
def __init__(self, games, exp_ver):
self.games = [g for g in games if g.Expansion() == exp_ver]
self.exp_ver = exp_ver
self.exp_name = EXPANSIONS[exp_ver]
self.goals = []
self.deck = BaseDeckInfo
if exp_ver == 1:
self.goals = GS_GOALS
self.deck = GSDeckInfo
elif exp_ver == 2:
self.goals = RVI_GOALS
self.deck = RvIDeckInfo
elif exp_ver == 3:
self.goals = BOW_GOALS
self.deck = BoWDeckInfo
def Goals(self):
return self.goals
def Deck(self):
return self.deck
class Game:
def __init__(self, game_dict):
n = float(len(game_dict['player_list']))
self.game_id = GetAndRemove(game_dict, 'game_id')
server = self.Server()
self.player_list = [PlayerResult(p, server)
for p in game_dict['player_list']]
del game_dict['player_list']
for player_result in self.PlayerList():
player_result.SetWinPoints(0.0)
player_result.SetGame(self)
if 'winners' in game_dict:
winners = []
for name in game_dict['winners']:
for player in self.player_list:
if player.Name() == name:
winners.append(player)
self.winners = winners
winners = self.GameWinners()
for player_result in winners:
player_result.SetWinPoints(n / len(winners))
self.player_list.sort(key = PlayerResult.WinPoints, reverse=True)
self.goals = []
if 'goals' in game_dict:
self.goals = GetAndRemove(game_dict, 'goals')
self.expansion = GetAndRemove(game_dict, 'expansion')
self.advanced = GetAndRemove(game_dict, 'advanced')
if '_id' in game_dict:
del game_dict['_id']
def __str__(self):
player_info_string = '\t' + '\n\t'.join(
str(p) for p in self.PlayerList())
return '%s %s\n' % (self.GameId(), player_info_string)
def Server(self):
host = self.game_id
if host.startswith('http://'): host = host[len('http://'):]
host = host[:host.find('.')]
return host
def WinningScore(self):
ret = float('-inf')
for result in self.PlayerList():
ret = max(ret, result.Score())
return ret
#return max(result.Score() for result in self.PlayerList())
def GameWinners(self):
if 'winners' in vars(self):
return self.winners
max_score = self.WinningScore()
return [p for p in self.PlayerList() if p.Score() == max_score]
def Tied(self):
return len(self.GameWinners()) > 1
def PlayerList(self):
return self.player_list
def GameId(self):
return self.game_id
def GameNo(self):
return int(MATCH_TRAILING_DIGITS.search(self.game_id).group(1))
def Goals(self):
return self.goals
def GoalVector(self):
return GoalVector(self.Goals())
def GoalGame(self):
return len(self.goals) > 0
def Expansion(self):
return self.expansion
def Advanced(self):
return self.advanced
def PlayerResultForName(self, player_name):
for player in self.PlayerList():
if player.Name() == player_name:
return player
raise ValueError
class PlayerResult:
def __init__(self, player_info_dict, server):
self.cards = GetAndRemove(player_info_dict, 'cards')
self.homeworld = ''
# This misclassifes initial doomed world settles that are
# other homeworlds. I doubt that happens all that often
# though.
if len(self.cards):
if self.cards[0] in BOW_HOMEWORLDS:
self.homeworld = self.cards[0]
else:
self.homeworld = 'Doomed World'
self.name = GetAndRemove(player_info_dict, 'name')
rename = name_handler.GetPrimaryName(self.name, server)
if self.name != rename:
#print self.name, '->', rename
self.name = rename
self.points = GetAndRemove(player_info_dict, 'points')
self.hand = GetAndRemove(player_info_dict, 'hand')
self.goods = GetAndRemove(player_info_dict, 'goods')
if 'prestige' in player_info_dict:
self.prestige = GetAndRemove(player_info_dict, 'prestige')
self.goals = []
if 'goals' in player_info_dict:
self.goals = GetAndRemove(player_info_dict, 'goals')
self.chips = GetAndRemove(player_info_dict, 'chips')
assert len(player_info_dict) == 0, player_info_dict.keys()
def Homeworld(self):
return self.homeworld
def SetGame(self, game):
self.game = game
def Game(self):
return self.game
def SetWinPoints(self, win_points):
self.win_points = win_points
def WinPoints(self):
return self.win_points
def Points(self):
return self.points
def Score(self):
return self.points * 100 + self.goods + self.hand
def Prestige(self):
if 'prestige' in vars(self):
return self.prestige
return 0
def Chips(self):
return self.chips
def Cards(self):
return self.cards
def Goals(self):
return self.goals
def GoalVector(self, weight = 1):
ret = [0] * len(GS_GOALS)
for goal in self.goals:
ret[GS_GOALS.index(goal)] = weight
return ret
def __str__(self):
card_str = ','.join(self.cards)
goal_str = ','.join(self.goals)
return '%s %d %d %s <%s>' % (
self.Name(), self.points, self.chips, card_str, goal_str)
def __repr__(self):
return self.__str__()
def WonGoalVector(self):
return GoalVector(self.goals)
def CardVector(self, record_places = True):
card_vec = [0] * DeckInfo.NumCards()
dw_comp = 0
if (self.Homeworld() == 'Doomed World' and
self.Cards()[0] != 'Doomed World'):
dw_comp += 1
card_vec[DeckInfo.CardIndexByName(self.Homeworld())] = 1
for idx, card in enumerate(self.Cards()):
card_ind = DeckInfo.CardIndexByName(card)
if record_places:
card_vec[card_ind] = dw_comp + idx + 1
else:
card_vec[card_ind] = 1
return card_vec
def Name(self):
return self.name
class RandomVariableObserver:
def __init__(self):
self.freq = 0
self.sum = 0.0
self.sum_sq = 0.0
def AddOutcome(self, val):
self.freq += 1
self.sum += val
self.sum_sq += val * val
def Frequency(self):
return self.freq
def Mean(self):
return self.sum / (self.freq or 1)
def Variance(self):
if self.freq <= 1:
return 1e10
return (self.sum_sq - (self.sum ** 2) / self.freq) / (self.freq - 1)
def StdDev(self):
return self.Variance() ** .5
def SampleStdDev(self):
return (self.Variance() / (self.freq or 1)) ** .5
def ComputeWinningStatsByHomeworld(games, rating_system):
def HomeworldYielder(player_result, game):
yield player_result.Homeworld()
return ComputeStatsByBucketFromGames(games, HomeworldYielder,
rating_system)
def ComputeStatsByBucketFromPlayerResults(player_results,
bucketter, rating_system):
wins = collections.defaultdict(RandomVariableObserver)
norm_wins = collections.defaultdict(RandomVariableObserver)
for player_result in player_results:
game = player_result.Game()
game_id = game.GameId()
n = float(len(game.PlayerList()))
player_name = player_result.Name()
if rating_system:
won_prob = rating_system.ProbWonAtGameId(game_id, player_name)
else:
won_prob = 1.0 / n
normalized_outcome = player_result.WinPoints() / (n * won_prob)
standard_outcome = player_result.WinPoints()
for key in bucketter(player_result, game):
norm_wins[key].AddOutcome(normalized_outcome)
wins[key].AddOutcome(standard_outcome)
bucket_infos = []
for bucket in norm_wins:
bucket_infos.append(BucketInfo(
bucket, wins[bucket].Mean(), wins[bucket].SampleStdDev(),
norm_wins[bucket].Mean(), norm_wins[bucket].SampleStdDev(),
wins[bucket].Frequency()))
bucket_infos.sort(key = lambda x: -x.win_points)
return bucket_infos
def PlayerResultsFromGames(games):
ret = []
for game in games:
ret.extend(game.PlayerList())
return ret
def ComputeStatsByBucketFromGames(games, bucketter, rating_system = None):
return ComputeStatsByBucketFromPlayerResults(PlayerResultsFromGames(games),
bucketter, rating_system)
def FilterOutTies(games):
return [g for g in games if not g.Tied()]
class PlayerSkillInfo:
def __init__(self, rating, wins, exp_wins, games_played):
self.rating = rating
self.wins = wins
self.exp_wins = exp_wins
self.games_played = games_played
self.percentile = None
def __repr__(self):
return str(self.rating)
def SortDictByKeys(d):
return sorted(d.items(), key = lambda x: -x[1])
class EloSkillModel:
def __init__(self, base_rating, move_const):
self.ratings = {}
self.base_rating = base_rating
self.move_const = move_const
def Predict(self, winner_name, loser_name):
winner_rating = self.GetSkillInfo(winner_name).rating
loser_rating = self.GetSkillInfo(loser_name).rating
return EloProbability(winner_rating, loser_rating)
def AdjustRatings(self, winner, losers):
"""Adjust the winner and losers ratings; return the rating changes."""
delta = {winner: 0.0}
for loser in losers:
winner_wins_prob = self.Predict(winner, loser)
loser_wins_prob = 1.0 - winner_wins_prob
# higher loser_wins_prob means a weaker opponent, which should
# be penalized more.
loser_rating_move = -loser_wins_prob * self.move_const
delta[loser] = loser_rating_move
self.ratings[loser].rating += loser_rating_move
delta[winner] += -loser_rating_move
self.ratings[winner].rating += -loser_rating_move
return delta
def GetSkillInfo(self, name):
if name not in self.ratings:
self.ratings[name] = PlayerSkillInfo(self.base_rating, 0, 0, 0)
return self.ratings[name]
def PlayersSortedBySkill(self):
return sorted(self.ratings.items(),
key = lambda x: -x[1].rating)
def NormalizeProbs(prob_list):
s = sum(prob_list)
return [i / s for i in prob_list]
class MultiSkillModelProbProd(EloSkillModel):
def __init__(self, base_rating, move_const):
EloSkillModel.__init__(self, base_rating, move_const)
def MultiplayerWinProb(self, player_list):
ret = []
for player1 in player_list:
ret.append(1)
for player2 in player_list:
if player1 != player2:
ret[-1] = ret[-1] * self.Predict(player1, player2)
return NormalizeProbs(ret)
class PoweredSkillModelProbProd(EloSkillModel):
def __init__(self, base_rating, move_const, pow3, pow4, pow5, pow6):
EloSkillModel.__init__(self, base_rating, move_const)
self.pows = [1, 1, 1, pow3, pow4, pow5, pow6]
def MultiplayerWinProb(self, player_list):
ret = []
for player1 in player_list:
ret.append(1)
for player2 in player_list:
if player1 != player2:
p = self.Predict(player1, player2) ** self.pows[
len(player_list)]
ret[-1] = ret[-1] * p
return NormalizeProbs(ret)
class UberNaiveMultiSkillModel(EloSkillModel):
def __init__(self, base_rating, move_const):
EloSkillModel.__init__(self, base_rating, move_const)
def MultiplayerWinProb(self, player_list):
return [1. / len(player_list)] * len(player_list)
class SkillRatings:
def __init__(self, games, skill_model):
self.skill_model = skill_model
self.rating_flow = collections.defaultdict(
lambda: collections.defaultdict(float))
self.rating_by_homeworld_flow = collections.defaultdict(
lambda: collections.defaultdict(float))
self.rating_by_opp_homeworld_flow = collections.defaultdict(
lambda: collections.defaultdict(float))
self.model_log_loss = 0.0
self.winner_pred_log_loss = 0.0
self.ratings_at_game_id = collections.defaultdict(dict)
self.prob_won_at_game_id = collections.defaultdict(dict)
for game in FilterOutTies(games):
winner = game.GameWinners()[0]
win_name = winner.Name()
losers = []
game_id = game.GameId()
for player in game.PlayerList():
player_name = player.Name()
rating = self.GetSkillInfo(player_name).rating
self.ratings_at_game_id[game_id][player_name] = rating
if player_name == win_name:
continue
loser_name = player.Name()
win_prob = self.skill_model.Predict(win_name, loser_name)
self.model_log_loss += math.log(win_prob) / math.log(2)
losers.append(loser_name)
player_names = [player.Name() for player in
game.PlayerList()]
winner_idx = player_names.index(win_name)
winner_hw = game.PlayerList()[winner_idx].Homeworld()
multiplayer_win_probs = skill_model.MultiplayerWinProb(
player_names)
name_prob_pairs = zip(player_names, multiplayer_win_probs)
self.prob_won_at_game_id[game_id] = name_prob_pairs
pred = multiplayer_win_probs[winner_idx]
self.winner_pred_log_loss += math.log(pred) / math.log(2)
delta = self.skill_model.AdjustRatings(win_name, losers)
for player_name in delta:
skill_info = self.GetSkillInfo(player_name)
skill_info.games_played += 1
skill_info.exp_wins += 1.0 / (len(game.PlayerList()))
homeworld = game.PlayerResultForName(player_name).Homeworld()
self.rating_by_homeworld_flow[player_name][homeworld] += (
delta[player_name])
if win_name == player_name:
continue
ohf = self.rating_by_opp_homeworld_flow
ohf[win_name][homeworld] -= delta[player_name]
ohf[player_name][winner_hw] += delta[player_name]
# This symettry is wrong for rating systems which are more
# general than Elo.
self.rating_flow[win_name][player_name] -= delta[player_name]
self.rating_flow[player_name][win_name] += delta[player_name]
self.GetSkillInfo(win_name).wins += 1.0
self.sorted_by_skill = self.skill_model.PlayersSortedBySkill()
self.ranking_percentile = {}
for idx, (name, skill_info) in enumerate(self.sorted_by_skill):
self.ranking_percentile[name] = 100.0 * (1.0 - (
float(idx) / len(self.sorted_by_skill)))
def RatingAtGameId(self, game_id, player_name):
return self.ratings_at_game_id[game_id][player_name]
def ProbWonAtGameId(self, game_id, player_name):
name_probs = self.prob_won_at_game_id[game_id]
for name, prob in name_probs:
if player_name == name:
return prob
raise ValueError()
def ModelPerformance(self):
return self.model_log_loss
def GetHomeworldSkillFlow(self, name):
return SortDictByKeys(self.rating_by_homeworld_flow[name])
def GetOpponentHomeworldSkillFlow(self, name):
return SortDictByKeys(self.rating_by_opp_homeworld_flow[name])
def HasPlayer(self, name):
return name in self.ranking_percentile
def NumPlayers(self):
return len(self.sorted_by_skill)
def GetSkillInfo(self, name):
return self.skill_model.GetSkillInfo(name)
def GetPercentile(self, name):
return self.ranking_percentile[name]
def GetRatingFlow(self, name):
return SortDictByKeys(self.rating_flow[name])
def PlayersSortedBySkill(self):
return self.sorted_by_skill
def ComputeRatingBuckets(self, games, num_buckets):
skills_weighted_by_games = []
for g in games:
for p in g.PlayerList():
rating = self.GetSkillInfo(p.Name()).rating
skills_weighted_by_games.append(rating)
skills_weighted_by_games.sort()
num_player_game_results = float(len(skills_weighted_by_games))
skill_sections = []
for i in range(1, num_buckets):
idx = int(num_player_game_results * i / num_buckets)
skill_sections.append(skills_weighted_by_games[idx])
skill_sections.append(1e10)
return skill_sections
def PlayerSkillBucket(self, player_name, skill_sections):
player_rating = self.skill_model.GetSkillInfo(player_name).rating
skill_level = 0
for bucket in skill_sections:
if player_rating > bucket:
skill_level += 1
return skill_level
def EloProbability(r1, r2):
"""Probability that r1 beats r2"""
return 1 / (1 + 10 ** ((r2 - r1) / 400.0))
def FilterDiscardables(mapping):
ret = dict(mapping)
for card in DISCARDABLE_CARDS:
if card in mapping:
del ret[card]
return ret
class BucketInfo:
def __init__(self, key,
win_points, win_points_ssd,
norm_win_points, norm_win_points_ssd, frequency):
self.key = key
self.win_points = win_points
self.win_points_ssd = max(win_points_ssd, 0)
self.frequency = frequency
self.norm_win_points = norm_win_points
self.norm_win_points_ssd = norm_win_points_ssd
def __str__(self):
return '%s,win points:%f,freq: %f,ssd: %f' % (
str(self.key), self.win_points, self.frequency, self.win_points_ssd)
# this has the overly non-general assumption that the card is the key, rather
# than simply a part of the key
def ComputeByCardStats(player_results, card_yielder, skill_ratings, gameset):
bucketted_stats = ComputeStatsByBucketFromPlayerResults(
player_results, card_yielder, skill_ratings)
grouped_by_card = {}
total_tableaus = float(len(player_results))
for bucket_info in bucketted_stats:
card = bucket_info.key
prob_per_card_name = bucket_info.frequency / total_tableaus
prob_per_card_name_var = prob_per_card_name * (1 - prob_per_card_name)
scaled_var = prob_per_card_name_var / total_tableaus
prob_per_card_name_ssd = scaled_var ** .5
freq_in_deck = DeckInfo.CardFrequencyInDeck(card, gameset.exp_ver)
prob_per_card = prob_per_card_name / freq_in_deck
prob_per_card_ssd = prob_per_card_name_ssd / freq_in_deck
grouped_by_card[card] = {
'win_points': bucket_info.win_points,
'norm_win_points': bucket_info.norm_win_points,
'norm_win_points_ssd': bucket_info.norm_win_points_ssd,
'prob_per_card': prob_per_card,
'prob_per_card_ssd': prob_per_card_ssd
}
return grouped_by_card
def ComputeWinningStatsByCardPlayed(player_results, skill_ratings, gameset):
def NonHomeworldCardYielder(player_result, game):
for idx, card in enumerate(player_result.Cards()):
if not (idx == 0 and card in BOW_HOMEWORLDS or
card == 'Gambling World'):
yield card
return FilterDiscardables(ComputeByCardStats(
player_results, NonHomeworldCardYielder, skill_ratings, gameset))
def VersionInfluenceOnCardStats(games, skill_ratings):
stats_by_ver = []
for version_idx, version_abbrev in enumerate(EXP_ABBREV):
gameset = FixedExpansionGameSet(games, version_idx)
cur_stats = ComputeWinningStatsByCardPlayed(
PlayerResultsFromGames(gameset.games), skill_ratings, gameset)
stats_by_ver.append({'title': version_abbrev,
'data': cur_stats})
return stats_by_ver
def GoalInfluenceOnCardStats(player_results, skill_ratings, gameset):
with_goals, without_goals = [], []
for player_result in player_results:
if player_result.Game().GoalGame():
with_goals.append(player_result)
else:
without_goals.append(player_result)
return [
{'title': 'Without goals',
'data': ComputeWinningStatsByCardPlayed(without_goals,
skill_ratings, gameset)},
{'title': 'With goals',
'data': ComputeWinningStatsByCardPlayed(with_goals,
skill_ratings, gameset)}
]
def GameSizeInfluenceOnCardStats(player_results, ratings, gameset):
games_by_size = collections.defaultdict(list)
for player_result in player_results:
game_size = len(player_result.Game().PlayerList())
games_by_size[game_size].append(player_result)
return [
{'title': 'Game Size %d' % size,
'data': ComputeWinningStatsByCardPlayed(games_by_size[size],
ratings, gameset)}
for size in sorted(games_by_size.keys())
]
def FilterOutNonGoals(games):
return [g for g in games if g.GoalGame()]
class HomeworldGoalAnalysis:
def __init__(self, games, gameset, player_ratings):
self.gameset = gameset
games = FilterOutNonGoals(games)
def HomeworldGoalYielder(player_result, game):
for goal in game.Goals():
yield player_result.Homeworld(), goal
self.bucketted_by_homeworld_goal = ComputeStatsByBucketFromGames(
games, HomeworldGoalYielder, player_ratings)
self.keyed_by_homeworld_goal = collections.defaultdict(lambda :0)
for bucket in self.bucketted_by_homeworld_goal:
self.keyed_by_homeworld_goal[bucket.key] = bucket.norm_win_points
self.bucketted_by_homeworld = ComputeWinningStatsByHomeworld(
games, player_ratings)
def RenderStatsAsHtml(self):
html = '<table border=1><tr><td>Homeworld</td>'
html += '<td>Baseline Winning Rate</td>'
html += '<td>Frequency</td>'
for goal in self.gameset.Goals():
html += '<td>%s</td>' % goal
html += '</tr>\n'
for bucket_info in self.bucketted_by_homeworld:
homeworld = bucket_info.key
win_points = bucket_info.norm_win_points
freq = bucket_info.frequency
html += '<tr><td>%s</td><td>%.3f</td><td>%d</td>' % (
homeworld, win_points, freq)
for goal in self.gameset.Goals():
diff = (
self.keyed_by_homeworld_goal[(homeworld, goal)] -
win_points)
html += '<td>%.3f</td>' % diff
html += '</tr>\n'
html += '</table>\n'
return html
def _Serialize(self):
ret = []
for bucket_info in self.bucketted_by_homeworld:
homeworld = bucket_info.key
ret.append({'homeworld': homeworld,
'win_points': bucket_info.norm_win_points,
'adjusted_rate': []})
for goal in self.gameset.Goals():
ret[-1]['adjusted_rate'].append(
self.keyed_by_homeworld_goal[(homeworld, goal)])
return ret
def RenderToJson(self):
return json.dumps(self._Serialize())
class OverviewStats:
def __init__(self, games):
self.max_genie_id = 0
self.max_flex_id = 0
self.max_keldon_id = 0
self.games_played = len(games)
self.exps = [0] * len(EXPANSIONS)
player_size = collections.defaultdict(int)
race_type = collections.defaultdict(int)
for game in games:
if 'flex' in game.GameId():
self.max_flex_id = max(self.max_flex_id, game.GameNo())
elif 'keldon' in game.GameId():
self.max_keldon_id = max(self.max_keldon_id, game.GameNo())
else:
self.max_genie_id = max(self.max_genie_id, game.GameNo())
adv = ''
if game.Advanced() == 1:
adv = ' adv'
players_size_str = '%dp%s' % ( len(game.PlayerList()), adv )
player_size[players_size_str] += 1
race_type_str = 'Base'
if game.Expansion() == 1:
race_type_str = 'Gathering Storm'
elif game.Expansion() == 2:
race_type_str = 'Rebel vs Imperium'
elif game.Expansion() == 3:
race_type_str = 'Brink of War'
if game.GoalGame():
if game.Expansion() == 0:
print game
race_type_str += ' with Goals'
race_type[race_type_str] += 1
self.exps[game.Expansion()] += 1
self.player_size = player_size.items()
self.player_size.sort()
self.race_type = race_type.items()
self.race_type.sort()
def NumExpansionGames(self, exp_no):
return self.exps[exp_no]
def RenderAsHTMLTable(self):
header_fmt = ('<table border=1><tr><td>%s</td><td>Num Games'
'</td><td>Percentage</td></tr>' )
html = '<a name="overview">'
html += '<h2>Overview</h2>'
html += '</a>'
html += '<div class="h3">'
html += 'Total games analyzed: %d<br>\n' % self.games_played
if self.max_genie_id:
html += 'Last seen genie game number: %d<br>\n' % self.max_genie_id
if self.max_flex_id:
html += 'Last seen flex game number: %d<br>\n' % self.max_flex_id
if self.max_keldon_id:
html += 'Last seen keldon game number: %d<br>\n' % self.max_keldon_id
html += header_fmt % 'Player Size'
for size in self.player_size:
html += '<tr><td>%s</td><td>%d</td><td>%d%%</td></tr>' % (
( size[0], size[1], int( 100. * size[1] / self.games_played )))
html += '</table border=1>'
html += header_fmt % 'Game Type'
for d in self.race_type:
html += '<tr><td>%s</td><td>%d</td><td>%d%%</td></tr>' % (
( d[0], d[1], int( 100. * d[1] / self.games_played )))
html += '</table>'
html += '</div>'
return html
def PlayerFile(player_name):
return 'player_' + player_name + '.html'
def PlayerLink(player_name, exp=None, anchor_text=None):
exp_text = ''
if exp is not None:
exp_text = exp + '/'
if anchor_text is None:
anchor_text = player_name
aliases = ','.join(name_handler.GetAliases(player_name))
if aliases:
aliases = '(' + aliases + ')'
anchor_text = anchor_text + ' ' + aliases
return ('<a href="' + exp_text + PlayerFile(player_name) + '">' +
anchor_text + '</a>')
def RenderCardWinGraph(out_file, card_win_info):
out_file.write("""
<p>
<table><tr><td>Skill Normalized<br>Winning Rate</td>
<td><canvas id="cardWinInfoCanvas" height="600" width="800"></canvas></td>
</tr>
<tr>
<td></td><td><center>
Probability instance of card appears on tableau</center></td>
</tr>
</table>
<script type="text/javascript">
var cardWinInfo = %s;
RenderCardWinInfo(cardWinInfo,document.getElementById("cardWinInfoCanvas"));
</script>
</p>
""" % json.dumps(card_win_info, indent=2))
def RenderCardAnimationGraph(out_file, animated_win_info):
out_file.write("""
<p><div id="cardDataAnimHolder">
<script type="text/javascript">
window.onload = function() {
var cardWinAnimationInfo = %s;
var animation = CardDataAnimation("cardDataAnimHolder");
animation.Render(cardWinAnimationInfo);
}
</script>
</p>
""" % json.dumps(animated_win_info, indent=2))
def AdjustedWinPoints(cardWinInfo):
observed_norm_win_points = []
for card in cardWinInfo:
c = cardWinInfo[card]
norm_win_points_per_game = c['prob_per_card'] * c['norm_win_points']
c['norm_win_points_per_game'] = norm_win_points_per_game