Use score-scaling Elo for non-duels.
[xonotic/xonstat.git] / xonstat / elo.py
1 import logging
2 import math
3 import random
4 import sys
5 from xonstat.models import *
6
7
8 log = logging.getLogger(__name__)
9
10
11 class EloParms:
12     def __init__(self, global_K = 15, initial = 100, floor = 100, logdistancefactor = math.log(10)/float(400), maxlogdistance = math.log(10)):
13         self.global_K = global_K
14         self.initial = initial
15         self.floor = floor
16         self.logdistancefactor = logdistancefactor
17         self.maxlogdistance = maxlogdistance
18
19
20 class KReduction:
21     def __init__(self, fulltime, mintime, minratio, games_min, games_max, games_factor):
22         self.fulltime = fulltime
23         self.mintime = mintime
24         self.minratio = minratio
25         self.games_min = games_min
26         self.games_max = games_max
27         self.games_factor = games_factor
28
29     def eval(self, mygames, mytime, matchtime):
30         if mytime < self.mintime:
31             return 0
32         if mytime < self.minratio * matchtime:
33             return 0
34         if mytime < self.fulltime:
35             k = mytime / float(self.fulltime)
36         else:
37             k = 1.0
38         if mygames >= self.games_max:
39             k *= self.games_factor
40         elif mygames > self.games_min:
41             k *= 1.0 - (1.0 - self.games_factor) * (mygames - self.games_min) / float(self.games_max - self.games_min)
42         return k
43
44
45 def process_elos(game, session, game_type_cd=None):
46     if game_type_cd is None:
47         game_type_cd = game.game_type_cd
48
49     # we do not have the actual duration of the game, so use the 
50     # maximum alivetime of the players instead
51     duration = 0
52     for d in session.query(sfunc.max(PlayerGameStat.alivetime)).\
53                 filter(PlayerGameStat.game_id==game.game_id).\
54                 one():
55         duration = d.seconds
56
57     scores = {}
58     alivetimes = {}
59     for (p,s,a) in session.query(PlayerGameStat.player_id, 
60             PlayerGameStat.score, PlayerGameStat.alivetime).\
61             filter(PlayerGameStat.game_id==game.game_id).\
62             filter(PlayerGameStat.alivetime > timedelta(seconds=0)).\
63             filter(PlayerGameStat.player_id > 2).\
64             all():
65                 # scores are per second
66                 scores[p] = s/float(a.seconds)
67                 alivetimes[p] = a.seconds
68
69     player_ids = scores.keys()
70
71     elos = {}
72     for e in session.query(PlayerElo).\
73             filter(PlayerElo.player_id.in_(player_ids)).\
74             filter(PlayerElo.game_type_cd==game_type_cd).all():
75                 elos[e.player_id] = e
76
77     # ensure that all player_ids have an elo record
78     for pid in player_ids:
79         if pid not in elos.keys():
80             elos[pid] = PlayerElo(pid, game_type_cd, ELOPARMS.initial)
81
82     for pid in player_ids:
83         elos[pid].k = KREDUCTION.eval(elos[pid].games, alivetimes[pid],
84                 duration)
85         if elos[pid].k == 0:
86             del(elos[pid])
87             del(scores[pid])
88             del(alivetimes[pid])
89
90     elos = update_elos(game, session, elos, scores, ELOPARMS)
91
92     # add the elos to the session for committing
93     for e in elos:
94         session.add(elos[e])
95
96
97 def update_elos(game, session, elos, scores, ep):
98     if len(elos) < 2:
99         return elos
100
101     pids = elos.keys()
102
103     eloadjust = {}
104     for pid in pids:
105         eloadjust[pid] = 0.0
106
107     for i in xrange(0, len(pids)):
108         ei = elos[pids[i]]
109         for j in xrange(i+1, len(pids)):
110             ej = elos[pids[j]]
111             si = scores[ei.player_id]
112             sj = scores[ej.player_id]
113
114             # normalize scores
115             ofs = min(0, si, sj)
116             si -= ofs
117             sj -= ofs
118             if si + sj == 0:
119                 si, sj = 1, 1 # a draw
120
121             # real score factor
122             scorefactor_real = si / float(si + sj)
123
124             # duels are done traditionally - a win nets
125             # full points, not the score factor
126             if game.game_type_cd == 'duel':
127                 # player i won
128                 if scorefactor_real > 0.5:
129                     scorefactor_real = 1.0
130                 # player j won
131                 elif scorefactor_real < 0.5:
132                     scorefactor_real = 0.0
133                 # nothing to do here for draws
134
135             # expected score factor by elo
136             elodiff = min(ep.maxlogdistance, max(-ep.maxlogdistance,
137                 (float(ei.elo) - float(ej.elo)) * ep.logdistancefactor))
138             scorefactor_elo = 1 / (1 + math.exp(-elodiff))
139
140             # initial adjustment values, which we may modify with additional rules
141             adjustmenti = scorefactor_real - scorefactor_elo
142             adjustmentj = scorefactor_elo - scorefactor_real
143
144             # log.debug("Player i: {0}".format(ei.player_id))
145             # log.debug("Player i's K: {0}".format(ei.k))
146             # log.debug("Player j: {0}".format(ej.player_id))
147             # log.debug("Player j's K: {0}".format(ej.k))
148             # log.debug("Scorefactor real: {0}".format(scorefactor_real))
149             # log.debug("Scorefactor elo: {0}".format(scorefactor_elo))
150             # log.debug("adjustment i: {0}".format(adjustmenti))
151             # log.debug("adjustment j: {0}".format(adjustmentj))
152
153             if scorefactor_elo > 0.5:
154             # player i is expected to win
155                 if scorefactor_real > 0.5:
156                 # he DID win, so he should never lose points.
157                     adjustmenti = max(0, adjustmenti)
158                 else:
159                 # he lost, but let's make it continuous (making him lose less points in the result)
160                     adjustmenti = (2 * scorefactor_real - 1) * scorefactor_elo
161             else:
162             # player j is expected to win
163                 if scorefactor_real > 0.5:
164                 # he lost, but let's make it continuous (making him lose less points in the result)
165                     adjustmentj = (1 - 2 * scorefactor_real) * (1 - scorefactor_elo)
166                 else:
167                 # he DID win, so he should never lose points.
168                     adjustmentj = max(0, adjustmentj)
169
170             eloadjust[ei.player_id] += adjustmenti
171             eloadjust[ej.player_id] += adjustmentj
172
173     elo_deltas = {}
174     for pid in pids:
175         old_elo = float(elos[pid].elo)
176         new_elo = max(float(elos[pid].elo) + eloadjust[pid] * elos[pid].k * ep.global_K / float(len(elos) - 1), ep.floor)
177         elo_deltas[pid] = new_elo - old_elo
178
179         elos[pid].elo = new_elo
180         elos[pid].games += 1
181
182         log.debug("Setting Player {0}'s Elo delta to {1}. Elo is now {2} (was {3}).".format(pid, elo_deltas[pid], new_elo, old_elo))
183
184     save_elo_deltas(game, session, elo_deltas)
185
186     return elos
187
188
189 def save_elo_deltas(game, session, elo_deltas):
190     """
191     Saves the amount by which each player's Elo goes up or down
192     in a given game in the PlayerGameStat row, allowing for scoreboard display.
193
194     elo_deltas is a dictionary such that elo_deltas[player_id] is the elo_delta
195     for that player_id.
196     """
197     pgstats = {}
198     for pgstat in session.query(PlayerGameStat).\
199             filter(PlayerGameStat.game_id == game.game_id).\
200             all():
201                 pgstats[pgstat.player_id] = pgstat
202
203     for pid in elo_deltas.keys():
204         try:
205             pgstats[pid].elo_delta = elo_deltas[pid]
206             session.add(pgstats[pid])
207         except:
208             log.debug("Unable to save Elo delta value for player_id {0}".format(pid))
209
210
211 # parameters for K reduction
212 # this may be touched even if the DB already exists
213 KREDUCTION = KReduction(600, 120, 0.5, 0, 32, 0.2)
214
215 # parameters for chess elo
216 # only global_K may be touched even if the DB already exists
217 # we start at K=200, and fall to K=40 over the first 20 games
218 ELOPARMS = EloParms(global_K = 200)