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(elos, scores, ELOPARMS)
149 # add the elos to the session for committing
153 if game_type_cd == 'duel':
154 self.process_elos(session, "dm")
156 def update_elos(self, elos, scores, ep):
158 for pid in elos.keys():
166 for i in xrange(0, len(pids)):
168 for j in xrange(i+1, len(pids)):
170 si = scores[ei.player_id]
171 sj = scores[ej.player_id]
178 si, sj = 1, 1 # a draw
181 scorefactor_real = si / float(si + sj)
183 # estimated score factor by elo
184 elodiff = min(ep.maxlogdistance, max(-ep.maxlogdistance,
185 (float(ei.elo) - float(ej.elo)) * ep.logdistancefactor))
186 scorefactor_elo = 1 / (1 + math.exp(-elodiff))
188 # how much adjustment is good?
189 # scorefactor(elodiff) = 1 / (1 + e^(-elodiff * logdistancefactor))
190 # elodiff(scorefactor) = -ln(1/scorefactor - 1) / logdistancefactor
191 # elodiff'(scorefactor) = 1 / ((scorefactor) (1 - scorefactor) logdistancefactor)
192 # elodiff'(scorefactor) >= 4 / logdistancefactor
194 # adjust'(scorefactor) = K1 + K2
197 # K1 + K2 <= 4 / logdistancefactor <= elodiff'(scorefactor)
198 # as we then don't overcompensate
200 adjustment = scorefactor_real - scorefactor_elo
201 eloadjust[ei.player_id] += adjustment
202 eloadjust[ej.player_id] -= adjustment
204 elos[pid].elo = max(float(elos[pid].elo) + eloadjust[pid] * elos[pid].k * ep.global_K / float(len(elos) - 1), ep.floor)
209 class PlayerGameStat(object):
210 def __init__(self, player_game_stat_id=None, create_dt=None):
211 self.player_game_stat_id = player_game_stat_id
212 self.create_dt = create_dt
215 return "<PlayerGameStat(%s, %s, %s)>" % (self.player_id, self.game_id, self.create_dt)
218 return {'player_id':self.player_id, 'game_id':self.game_id, 'create_dt':self.create_dt.strftime('%Y-%m-%dT%H:%M:%SZ')}
220 def nick_stripped(self):
221 if self.nick is None:
222 return "Anonymous Player"
224 return strip_colors(self.nick)
226 def nick_html_colors(self):
227 if self.nick is None:
228 return "Anonymous Player"
230 return html_colors(self.nick)
232 def team_html_color(self):
245 class Achievement(object):
247 return "<Achievement(%s, %s, %s)>" % (self.achievement_cd, self.descr, self.limit)
250 return {'achievement_cd':self.achievement_cd, 'name':self.descr, 'limit':self.limit}
253 class PlayerAchievement(object):
255 return "<PlayerAchievement(%s, %s)>" % (self.player_id, self.achievement_cd)
258 return {'player_id':self.player_id, 'achievement_cd':self.achievement_cd}
261 class PlayerWeaponStat(object):
263 return "<PlayerWeaponStat(%s, %s, %s)>" % (self.player_weapon_stats_id, self.player_id, self.game_id)
266 return {'player_weapon_stats_id':self.player_weapon_stats_id, 'player_id':self.player_id, 'game_id':self.game_id}
269 class Hashkey(object):
270 def __init__(self, player_id=None, hashkey=None):
271 self.player_id = player_id
272 self.hashkey = hashkey
275 return "<Hashkey(%s, %s)>" % (self.player_id, self.hashkey)
278 return {'player_id':self.player_id, 'hashkey':self.hashkey}
281 class PlayerNick(object):
283 return "<PlayerNick(%s, %s)>" % (self.player_id, self.stripped_nick)
286 return {'player_id':self.player_id, 'name':self.stripped_nick}
289 class PlayerElo(object):
290 def __init__(self, player_id=None, game_type_cd=None):
292 self.player_id = player_id
293 self.game_type_cd = game_type_cd
296 self.elo = ELOPARMS.initial
299 return "<PlayerElo(pid=%s, gametype=%s, elo=%s)>" % (self.player_id, self.game_type_cd, self.elo)
302 return {'player_id':self.player_id, 'game_type_cd':self.game_type_cd, 'elo':self.elo}
305 class PlayerRank(object):
307 def nick_html_colors(self):
308 if self.nick is None:
309 return "Anonymous Player"
311 return html_colors(self.nick)
314 return "<PlayerRank(pid=%s, gametype=%s, rank=%s)>" % (self.player_id, self.game_type_cd, self.rank)
317 return {'player_id':self.player_id, 'game_type_cd':self.game_type_cd, 'rank':self.rank}
320 def initialize_db(engine=None):
321 DBSession.configure(bind=engine)
322 Base.metadata.bind = engine
323 Base.metadata.create_all(engine)
324 MetaData = sqlalchemy.MetaData(bind=engine, reflect=True)
326 # assign all those tables to an object
327 achievements_table = MetaData.tables['achievements']
328 cd_achievement_table = MetaData.tables['cd_achievement']
329 cd_game_type_table = MetaData.tables['cd_game_type']
330 cd_weapon_table = MetaData.tables['cd_weapon']
331 db_version_table = MetaData.tables['db_version']
332 games_table = MetaData.tables['games']
333 hashkeys_table = MetaData.tables['hashkeys']
334 maps_table = MetaData.tables['maps']
335 player_game_stats_table = MetaData.tables['player_game_stats']
336 players_table = MetaData.tables['players']
337 player_weapon_stats_table = MetaData.tables['player_weapon_stats']
338 servers_table = MetaData.tables['servers']
339 player_nicks_table = MetaData.tables['player_nicks']
340 player_elos_table = MetaData.tables['player_elos']
341 player_ranks_table = MetaData.tables['player_ranks']
343 # now map the tables and the objects together
344 mapper(PlayerAchievement, achievements_table)
345 mapper(Achievement, cd_achievement_table)
346 mapper(GameType, cd_game_type_table)
347 mapper(Weapon, cd_weapon_table)
348 mapper(Game, games_table)
349 mapper(Hashkey, hashkeys_table)
350 mapper(Map, maps_table)
351 mapper(PlayerGameStat, player_game_stats_table)
352 mapper(Player, players_table)
353 mapper(PlayerWeaponStat, player_weapon_stats_table)
354 mapper(Server, servers_table)
355 mapper(PlayerNick, player_nicks_table)
356 mapper(PlayerElo, player_elos_table)
357 mapper(PlayerRank, player_ranks_table)