5 from xonstat.models import PlayerGlicko, Game, PlayerGameStat
7 log = logging.getLogger(__name__)
10 # log.addHandler(logging.StreamHandler())
11 # log.setLevel(logging.DEBUG)
13 # the default system volatility constant
16 # how much ping influences results
17 LATENCY_TREND_FACTOR = 0.2
21 return 1 / math.sqrt(1 + (3 * phi ** 2) / (math.pi ** 2))
24 def calc_e(mu, mu_j, phi_j):
25 return 1. / (1 + math.exp(-calc_g(phi_j) * (mu - mu_j)))
29 """ Estimated variance of the team or player's ratings based only on game outcomes. """
31 for i in range(len(gs)):
32 total += (gs[i] ** 2) * es[i] * (1-es[i])
37 def calc_delta(v, gs, es, results):
39 Compute the estimated improvement in rating by comparing the pre-period rating to the
40 performance rating based only on game outcomes.
43 for i in range(len(gs)):
44 total += gs[i] * (results[i] - es[i])
49 def calc_sigma_bar(sigma, delta, phi, v, tau=TAU):
50 """ Compute the new volatility. """
52 A = a = math.log(sigma**2)
54 # pre-compute some terms
60 term_a = (e_up_x * (delta_sq - phi_sq - v - e_up_x)) / (2 * (phi_sq + v + e_up_x) ** 2)
61 term_b = (x - a) / tau ** 2
62 return term_a - term_b
64 if delta_sq > (phi_sq + v):
65 B = math.log(delta_sq - phi_sq - v)
68 while f(a - k * tau) < 0:
73 while abs(B - A) > epsilon:
74 C = A + (A - B) * (fa / (fb - fa))
85 # log.debug("A={}, B={}, C={}, fA={}, fB={}, fC={}".format(A, B, C, fa, fb, fc))
87 return math.e ** (A / 2)
90 def rate(player, opponents, results):
92 Calculate the ratings improvement for a given player, provided their opponents and
93 corresponding results versus them.
95 p_g2 = player.to_glicko2()
99 for i in range(len(opponents)):
100 o_g2 = opponents[i].to_glicko2()
101 gs.append(calc_g(o_g2.phi))
102 es.append(calc_e(p_g2.mu, o_g2.mu, o_g2.phi))
105 # log.debug("j={} muj={} phij={} g={} e={} s={}"
106 # .format(i+1, o_g2.mu, o_g2.phi, gs[i], es[i], results[i]))
109 delta = calc_delta(v, gs, es, results)
110 sigma_bar = calc_sigma_bar(p_g2.sigma, delta, p_g2.phi, v)
112 phi_tmp = math.sqrt(p_g2.phi ** 2 + sigma_bar ** 2)
113 phi_bar = 1/math.sqrt((1/phi_tmp**2) + (1/v))
116 for i in range(len(opponents)):
117 sum_terms += gs[i] * (results[i] - es[i])
119 mu_bar = p_g2.mu + phi_bar**2 * sum_terms
121 new_rating = PlayerGlicko(player.player_id, player.game_type_cd, player.category, mu_bar,
122 phi_bar, sigma_bar).from_glicko2()
125 # log.debug("v={}".format(v))
126 # log.debug("delta={}".format(delta))
127 # log.debug("sigma_temp={}".format(sigma_temp))
128 # log.debug("sigma_bar={}".format(sigma_bar))
129 # log.debug("phi_bar={}".format(phi_bar))
130 # log.debug("mu_bar={}".format(mu_bar))
131 # log.debug("new_rating: {} {} {}".format(new_rating.mu, new_rating.phi, new_rating.sigma))
138 Scale the points gained or lost for players based on time played in the given game.
140 def __init__(self, full_time=600, min_time=120, min_ratio=0.5):
141 # full time is the time played to count the player in a game
142 self.full_time = full_time
144 # min time is the time played to count the player at all in a game
145 self.min_time = min_time
147 # min_ratio is the ratio of the game's time to be played to be counted fully (provided
148 # they went past `full_time` and `min_time` above.
149 self.min_ratio = min_ratio
151 def eval(self, my_time, match_time):
152 # kick out players who didn't play enough of the match
153 if my_time < self.min_time:
156 if my_time < self.min_ratio * match_time:
159 # scale based on time played versus what is defined as `full_time`
160 if my_time < self.full_time:
161 k = my_time / float(self.full_time)
168 # Parameters for reduction of points
169 KREDUCTION = KReduction()
172 class GlickoWIP(object):
173 """ A work-in-progress Glicko value. """
174 def __init__(self, pg):
176 Initialize a GlickoWIP instance.
177 :param pg: the player's PlayerGlicko record.
179 # the player's current (or base) PlayerGlicko record
182 # the list of k factors for each game in the ranking period
185 # the list of ping factors for each game in the ranking period
186 self.ping_factors = []
188 # the list of opponents (PlayerGlicko or PlayerGlickoBase) in the ranking period
191 # the list of results for those games in the ranking period
195 class GlickoProcessor(object):
197 Processes an arbitrary list games using the Glicko2 algorithm.
199 def __init__(self, session):
201 Create a GlickoProcessor instance.
203 :param session: the SQLAlchemy session to use for fetching/saving records.
205 self.session = session
208 def _pingratio(self, pi, pj):
210 Calculate the ping differences between the two players, but only if both have them.
212 :param pi: the latency of player I
213 :param pj: the latency of player J
216 if pi is None or pj is None or pi < 0 or pj < 0:
221 return float(pi)/(pi+pj)
223 def _load_game(self, game_id):
225 game = self.session.query(Game).filter(Game.game_id==game_id).one()
227 except Exception as e:
228 log.error("Game ID {} not found.".format(game_id))
232 def _load_pgstats(self, game):
234 Retrieve the game stats from the database for the game in question.
236 :param game: the game record whose player stats will be retrieved
237 :return: list of PlayerGameStat
240 pgstats_raw = self.session.query(PlayerGameStat)\
241 .filter(PlayerGameStat.game_id==game.game_id)\
242 .filter(PlayerGameStat.player_id > 2)\
245 except Exception as e:
246 log.error("Error fetching player_game_stat records for game {}".format(game.game_id))
251 for pgstat in pgstats_raw:
252 # ensure warmup isn't included in the pgstat records
253 if pgstat.alivetime > game.duration:
254 pgstat.alivetime = game.duration
256 # ensure players played enough of the match to be included
257 k = KREDUCTION.eval(pgstat.alivetime.total_seconds(), game.duration.total_seconds())
261 pgstats.append(pgstat)
265 def _load_glicko_wip(self, player_id, game_type_cd, category):
267 Retrieve a PlayerGlicko record from the database.
269 :param player_id: the player ID to fetch
270 :param game_type_cd: the game type code
271 :param category: the category of glicko to retrieve
272 :return: PlayerGlicko
274 if (player_id, game_type_cd, category) in self.wips:
275 return self.wips[(player_id, game_type_cd, category)]
278 pg = self.session.query(PlayerGlicko)\
279 .filter(PlayerGlicko.player_id==player_id)\
280 .filter(PlayerGlicko.game_type_cd==game_type_cd)\
281 .filter(PlayerGlicko.category==category)\
285 pg = PlayerGlicko(player_id, game_type_cd, category)
287 # cache this in the wips dict
289 self.wips[(player_id, game_type_cd, category)] = wip
293 def load(self, game_id):
295 Load all of the needed information from the database. Compute results for each player pair.
297 game = self._load_game(game_id)
298 pgstats = self._load_pgstats(game)
299 game_type_cd = game.game_type_cd
300 category = game.category
303 # wipi/j => work in progress record for player i/j
304 # ki/j => k reduction value for player i/j
305 # si/j => score per second for player i/j
306 # pi/j => ping ratio for player i/j
307 for i in xrange(0, len(pgstats)):
308 wipi = self._load_glicko_wip(pgstats[i].player_id, game_type_cd, category)
309 ki = KREDUCTION.eval(pgstats[i].alivetime.total_seconds(),
310 game.duration.total_seconds())
311 si = pgstats[i].score/float(game.duration.total_seconds())
313 for j in xrange(i+1, len(pgstats)):
314 # ping factor is opponent-specific
315 pi = self._pingratio(pgstats[i].avg_latency, pgstats[j].avg_latency)
318 wipj = self._load_glicko_wip(pgstats[j].player_id, game_type_cd, category)
319 kj = KREDUCTION.eval(pgstats[j].alivetime.total_seconds(),
320 game.duration.total_seconds())
321 sj = pgstats[j].score/float(game.duration.seconds)
324 ofs = min(0.0, si, sj)
328 si, sj = 1, 1 # a draw
330 scorefactor_i = si / float(si + sj)
331 scorefactor_j = 1.0 - si
333 wipi.k_factors.append(ki)
334 wipi.ping_factors.append(pi)
335 wipi.opponents.append(wipj.pg)
336 wipi.results.append(scorefactor_i)
338 wipj.k_factors.append(kj)
339 wipj.ping_factors.append(pj)
340 wipj.opponents.append(wipi.pg)
341 wipj.results.append(scorefactor_j)
345 Calculate the Glicko2 ratings, deviations, and volatility updates for the records loaded.
347 for wip in self.wips.values():
348 new_pg = rate(wip.pg, wip.opponents, wip.results)
350 log.debug("New rating for player {} before factors: mu={} phi={} sigma={}"
351 .format(pg.player_id, new_pg.mu, new_pg.phi, new_pg.sigma))
353 avg_k_factor = sum(wip.k_factors)/len(wip.k_factors)
354 avg_ping_factor = LATENCY_TREND_FACTOR * sum(wip.ping_factors)/len(wip.ping_factors)
356 points_delta = (new_pg.mu - wip.pg.mu) * avg_k_factor * avg_ping_factor
358 wip.pg.mu += points_delta
359 wip.pg.phi = new_pg.phi
360 wip.pg.sigma = new_pg.sigma
362 log.debug("New rating for player {} after factors: mu={} phi={} sigma={}"
363 .format(wip.pg.player_id, wip.pg.mu, wip.pg.phi, wip.pg.sigma))
365 def save(self, session):
367 Put all changed PlayerElo and PlayerGameStat instances into the
368 session to be updated or inserted upon commit.
374 # the example in the actual Glicko2 paper, for verification purposes
375 pA = PlayerGlicko(1, "duel", mu=1500, phi=200)
376 pB = PlayerGlicko(2, "duel", mu=1400, phi=30)
377 pC = PlayerGlicko(3, "duel", mu=1550, phi=100)
378 pD = PlayerGlicko(4, "duel", mu=1700, phi=300)
380 opponents = [pB, pC, pD]
383 rate(pA, opponents, results)
386 if __name__ == "__main__":