5 import sqlalchemy.sql.functions as sfunc
6 from datetime import timedelta
7 from sqlalchemy.orm import mapper
8 from sqlalchemy.orm import scoped_session
9 from sqlalchemy.orm import sessionmaker
10 from sqlalchemy.ext.declarative import declarative_base
11 from xonstat.elo import KREDUCTION, ELOPARMS
12 from xonstat.util import strip_colors, html_colors, pretty_date
14 log = logging.getLogger(__name__)
16 DBSession = scoped_session(sessionmaker())
17 Base = declarative_base()
19 # define objects for all tables
21 def nick_html_colors(self):
23 return "Anonymous Player"
25 return html_colors(self.nick)
27 def nick_strip_colors(self):
29 return "Anonymous Player"
31 return strip_colors(self.nick)
33 def joined_pretty_date(self):
34 return pretty_date(self.create_dt)
37 return "<Player(%s, %s)>" % (self.player_id, self.nick.encode('utf-8'))
40 return {'player_id':self.player_id, 'name':self.nick.encode('utf-8')}
43 class GameType(object):
45 return "<GameType(%s, %s, %s)>" % (self.game_type_cd, self.descr, self.active_ind)
48 return {'game_type_cd':self.game_type_cd, 'name':self.descr, 'active':self.active_ind}
53 return "<Weapon(%s, %s, %s)>" % (self.weapon_cd, self.descr, self.active_ind)
56 return {'weapon_cd':self.weapon_cd, 'name':self.descr, 'active':self.active_ind}
60 def __init__(self, name=None, hashkey=None, ip_addr=None):
62 self.hashkey = hashkey
63 self.ip_addr = ip_addr
66 return "<Server(%s, %s)>" % (self.server_id, self.name.encode('utf-8'))
69 return {'server_id':self.server_id, 'name':self.name.encode('utf-8')}
73 def __init__(self, name=None):
77 return "<Map(%s, %s, %s)>" % (self.map_id, self.name, self.version)
80 return {'map_id':self.map_id, 'name':self.name, 'version':self.version}
84 def __init__(self, game_id=None, start_dt=None, game_type_cd=None,
85 server_id=None, map_id=None, winner=None):
86 self.game_id = game_id
87 self.start_dt = start_dt
88 self.game_type_cd = game_type_cd
89 self.server_id = server_id
94 return "<Game(%s, %s, %s, %s)>" % (self.game_id, self.start_dt, self.game_type_cd, self.server_id)
97 return {'game_id':self.game_id, 'start':self.start_dt.strftime('%Y-%m-%dT%H:%M:%SZ'), 'game_type_cd':self.game_type_cd, 'server_id':self.server_id}
100 return pretty_date(self.start_dt)
102 def process_elos(self, session, game_type_cd=None):
103 if game_type_cd is None:
104 game_type_cd = self.game_type_cd
106 # we do not have the actual duration of the game, so use the
107 # maximum alivetime of the players instead
109 for d in session.query(sfunc.max(PlayerGameStat.alivetime)).\
110 filter(PlayerGameStat.game_id==self.game_id).\
116 for (p,s,a) in session.query(PlayerGameStat.player_id,
117 PlayerGameStat.score, PlayerGameStat.alivetime).\
118 filter(PlayerGameStat.game_id==self.game_id).\
119 filter(PlayerGameStat.alivetime > timedelta(seconds=0)).\
120 filter(PlayerGameStat.player_id > 2).\
122 # scores are per second
123 scores[p] = s/float(a.seconds)
124 alivetimes[p] = a.seconds
126 player_ids = scores.keys()
129 for e in session.query(PlayerElo).\
130 filter(PlayerElo.player_id.in_(player_ids)).\
131 filter(PlayerElo.game_type_cd==game_type_cd).all():
132 elos[e.player_id] = e
134 # ensure that all player_ids have an elo record
135 for pid in player_ids:
136 if pid not in elos.keys():
137 elos[pid] = PlayerElo(pid, game_type_cd)
139 for pid in player_ids:
140 elos[pid].k = KREDUCTION.eval(elos[pid].games, alivetimes[pid],
147 elos = self.update_elos(session, elos, scores, ELOPARMS)
149 # add the elos to the session for committing
153 if game_type_cd == 'duel':
154 self.process_elos(session, "dm")
157 def update_elos(self, session, elos, scores, ep):
159 for pid in elos.keys():
167 for i in xrange(0, len(pids)):
169 for j in xrange(i+1, len(pids)):
171 si = scores[ei.player_id]
172 sj = scores[ej.player_id]
179 si, sj = 1, 1 # a draw
182 scorefactor_real = si / float(si + sj)
184 # estimated score factor by elo
185 elodiff = min(ep.maxlogdistance, max(-ep.maxlogdistance,
186 (float(ei.elo) - float(ej.elo)) * ep.logdistancefactor))
187 scorefactor_elo = 1 / (1 + math.exp(-elodiff))
189 # how much adjustment is good?
190 # scorefactor(elodiff) = 1 / (1 + e^(-elodiff * logdistancefactor))
191 # elodiff(scorefactor) = -ln(1/scorefactor - 1) / logdistancefactor
192 # elodiff'(scorefactor) = 1 / ((scorefactor) (1 - scorefactor) logdistancefactor)
193 # elodiff'(scorefactor) >= 4 / logdistancefactor
195 # adjust'(scorefactor) = K1 + K2
198 # K1 + K2 <= 4 / logdistancefactor <= elodiff'(scorefactor)
199 # as we then don't overcompensate
201 adjustment = scorefactor_real - scorefactor_elo
202 eloadjust[ei.player_id] += adjustment
203 eloadjust[ej.player_id] -= adjustment
206 elo_delta = eloadjust[pid] * elos[pid].k * ep.global_K / float(len(elos) - 1)
208 if float(elos[pid].elo) + elo_delta < ep.floor:
209 elo_deltas[pid] = elos[pid].elo - ep.floor
211 elo_deltas[pid] = elo_delta
213 # can't go below the floor
214 elos[pid].elo = max(float(elos[pid].elo) + elo_delta, ep.floor)
217 self.save_elo_deltas(session, elo_deltas)
222 def save_elo_deltas(self, session, elo_deltas):
224 Saves the amount by which each player's Elo goes up or down
225 in a given game in the PlayerGameStat row, allowing for scoreboard display.
227 elo_deltas is a dictionary such that elo_deltas[player_id] is the elo_delta
231 for pgstat in session.query(PlayerGameStat).\
232 filter(PlayerGameStat.game_id == self.game_id).\
234 pgstats[pgstat.player_id] = pgstat
236 for pid in elo_deltas.keys():
238 pgstats[pid].elo_delta = elo_deltas[pid]
239 session.add(pgstats[pid])
241 log.debug("Unable to save Elo delta value for player_id {0}".format(pid))
244 class PlayerGameStat(object):
245 def __init__(self, player_game_stat_id=None, create_dt=None):
246 self.player_game_stat_id = player_game_stat_id
247 self.create_dt = create_dt
250 return "<PlayerGameStat(%s, %s, %s)>" % (self.player_id, self.game_id, self.create_dt)
253 return {'player_id':self.player_id, 'game_id':self.game_id, 'create_dt':self.create_dt.strftime('%Y-%m-%dT%H:%M:%SZ')}
255 def nick_stripped(self):
256 if self.nick is None:
257 return "Anonymous Player"
259 return strip_colors(self.nick)
261 def nick_html_colors(self):
262 if self.nick is None:
263 return "Anonymous Player"
265 return html_colors(self.nick)
267 def team_html_color(self):
280 class Achievement(object):
282 return "<Achievement(%s, %s, %s)>" % (self.achievement_cd, self.descr, self.limit)
285 return {'achievement_cd':self.achievement_cd, 'name':self.descr, 'limit':self.limit}
288 class PlayerAchievement(object):
290 return "<PlayerAchievement(%s, %s)>" % (self.player_id, self.achievement_cd)
293 return {'player_id':self.player_id, 'achievement_cd':self.achievement_cd}
296 class PlayerWeaponStat(object):
298 return "<PlayerWeaponStat(%s, %s, %s)>" % (self.player_weapon_stats_id, self.player_id, self.game_id)
301 return {'player_weapon_stats_id':self.player_weapon_stats_id, 'player_id':self.player_id, 'game_id':self.game_id}
304 class Hashkey(object):
305 def __init__(self, player_id=None, hashkey=None):
306 self.player_id = player_id
307 self.hashkey = hashkey
310 return "<Hashkey(%s, %s)>" % (self.player_id, self.hashkey)
313 return {'player_id':self.player_id, 'hashkey':self.hashkey}
316 class PlayerNick(object):
318 return "<PlayerNick(%s, %s)>" % (self.player_id, self.stripped_nick)
321 return {'player_id':self.player_id, 'name':self.stripped_nick}
324 class PlayerElo(object):
325 def __init__(self, player_id=None, game_type_cd=None):
327 self.player_id = player_id
328 self.game_type_cd = game_type_cd
331 self.elo = ELOPARMS.initial
334 return "<PlayerElo(pid=%s, gametype=%s, elo=%s)>" % (self.player_id, self.game_type_cd, self.elo)
337 return {'player_id':self.player_id, 'game_type_cd':self.game_type_cd, 'elo':self.elo}
340 class PlayerRank(object):
342 def nick_html_colors(self):
343 if self.nick is None:
344 return "Anonymous Player"
346 return html_colors(self.nick)
349 return "<PlayerRank(pid=%s, gametype=%s, rank=%s)>" % (self.player_id, self.game_type_cd, self.rank)
352 return {'player_id':self.player_id, 'game_type_cd':self.game_type_cd, 'rank':self.rank}
355 def initialize_db(engine=None):
356 DBSession.configure(bind=engine)
357 Base.metadata.bind = engine
358 Base.metadata.create_all(engine)
359 MetaData = sqlalchemy.MetaData(bind=engine, reflect=True)
361 # assign all those tables to an object
362 achievements_table = MetaData.tables['achievements']
363 cd_achievement_table = MetaData.tables['cd_achievement']
364 cd_game_type_table = MetaData.tables['cd_game_type']
365 cd_weapon_table = MetaData.tables['cd_weapon']
366 db_version_table = MetaData.tables['db_version']
367 games_table = MetaData.tables['games']
368 hashkeys_table = MetaData.tables['hashkeys']
369 maps_table = MetaData.tables['maps']
370 player_game_stats_table = MetaData.tables['player_game_stats']
371 players_table = MetaData.tables['players']
372 player_weapon_stats_table = MetaData.tables['player_weapon_stats']
373 servers_table = MetaData.tables['servers']
374 player_nicks_table = MetaData.tables['player_nicks']
375 player_elos_table = MetaData.tables['player_elos']
376 player_ranks_table = MetaData.tables['player_ranks']
378 # now map the tables and the objects together
379 mapper(PlayerAchievement, achievements_table)
380 mapper(Achievement, cd_achievement_table)
381 mapper(GameType, cd_game_type_table)
382 mapper(Weapon, cd_weapon_table)
383 mapper(Game, games_table)
384 mapper(Hashkey, hashkeys_table)
385 mapper(Map, maps_table)
386 mapper(PlayerGameStat, player_game_stats_table)
387 mapper(Player, players_table)
388 mapper(PlayerWeaponStat, player_weapon_stats_table)
389 mapper(Server, servers_table)
390 mapper(PlayerNick, player_nicks_table)
391 mapper(PlayerElo, player_elos_table)
392 mapper(PlayerRank, player_ranks_table)