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,
38 self.nick.encode('utf-8'))
41 class GameType(object):
43 return "<GameType(%s, %s, %s)>" % (self.game_type_cd, self.descr,
49 return "<Weapon(%s, %s, %s)>" % (self.weapon_cd, self.descr,
54 def __init__(self, name=None, hashkey=None, ip_addr=None):
56 self.hashkey = hashkey
57 self.ip_addr = ip_addr
60 return "<Server(%s, %s)>" % (self.server_id, self.name.encode('utf-8'))
64 def __init__(self, name=None):
68 return "<Map(%s, %s, %s)>" % (self.map_id, self.name, self.version)
71 return {'map_id':self.map_id, 'name':self.name}
75 def __init__(self, game_id=None, start_dt=None, game_type_cd=None,
76 server_id=None, map_id=None, winner=None):
77 self.game_id = game_id
78 self.start_dt = start_dt
79 self.game_type_cd = game_type_cd
80 self.server_id = server_id
85 return "<Game(%s, %s, %s, %s)>" % (self.game_id, self.start_dt,
86 self.game_type_cd, self.server_id)
89 return pretty_date(self.start_dt)
91 def process_elos(self, session, game_type_cd=None):
92 if game_type_cd is None:
93 game_type_cd = self.game_type_cd
95 # we do not have the actual duration of the game, so use the
96 # maximum alivetime of the players instead
98 for d in session.query(sfunc.max(PlayerGameStat.alivetime)).\
99 filter(PlayerGameStat.game_id==self.game_id).\
105 for (p,s,a) in session.query(PlayerGameStat.player_id,
106 PlayerGameStat.score, PlayerGameStat.alivetime).\
107 filter(PlayerGameStat.game_id==self.game_id).\
108 filter(PlayerGameStat.alivetime > timedelta(seconds=0)).\
109 filter(PlayerGameStat.player_id > 2).\
111 # scores are per second
112 scores[p] = s/float(a.seconds)
113 alivetimes[p] = a.seconds
115 player_ids = scores.keys()
118 for e in session.query(PlayerElo).\
119 filter(PlayerElo.player_id.in_(player_ids)).\
120 filter(PlayerElo.game_type_cd==game_type_cd).all():
121 elos[e.player_id] = e
123 # ensure that all player_ids have an elo record
124 for pid in player_ids:
125 if pid not in elos.keys():
126 elos[pid] = PlayerElo(pid, game_type_cd)
128 for pid in player_ids:
129 elos[pid].k = KREDUCTION.eval(elos[pid].games, alivetimes[pid],
136 elos = self.update_elos(elos, scores, ELOPARMS)
138 # add the elos to the session for committing
142 if game_type_cd == 'duel':
143 self.process_elos(session, "dm")
145 def update_elos(self, elos, scores, ep):
147 for pid in elos.keys():
155 for i in xrange(0, len(pids)):
157 for j in xrange(i+1, len(pids)):
159 si = scores[ei.player_id]
160 sj = scores[ej.player_id]
167 si, sj = 1, 1 # a draw
170 scorefactor_real = si / float(si + sj)
172 # estimated score factor by elo
173 elodiff = min(ep.maxlogdistance, max(-ep.maxlogdistance,
174 (float(ei.elo) - float(ej.elo)) * ep.logdistancefactor))
175 scorefactor_elo = 1 / (1 + math.exp(-elodiff))
177 # how much adjustment is good?
178 # scorefactor(elodiff) = 1 / (1 + e^(-elodiff * logdistancefactor))
179 # elodiff(scorefactor) = -ln(1/scorefactor - 1) / logdistancefactor
180 # elodiff'(scorefactor) = 1 / ((scorefactor) (1 - scorefactor) logdistancefactor)
181 # elodiff'(scorefactor) >= 4 / logdistancefactor
183 # adjust'(scorefactor) = K1 + K2
186 # K1 + K2 <= 4 / logdistancefactor <= elodiff'(scorefactor)
187 # as we then don't overcompensate
189 adjustment = scorefactor_real - scorefactor_elo
190 eloadjust[ei.player_id] += adjustment
191 eloadjust[ej.player_id] -= adjustment
193 elos[pid].elo = max(float(elos[pid].elo) + eloadjust[pid] * elos[pid].k * ep.global_K / float(len(elos) - 1), ep.floor)
198 class PlayerGameStat(object):
199 def __init__(self, player_game_stat_id=None, create_dt=None):
200 self.player_game_stat_id = player_game_stat_id
201 self.create_dt = create_dt
204 return "<PlayerGameStat(%s, %s, %s)>" \
205 % (self.player_id, self.game_id, self.create_dt)
207 def nick_stripped(self):
208 if self.nick is None:
209 return "Anonymous Player"
211 return strip_colors(self.nick)
213 def nick_html_colors(self):
214 if self.nick is None:
215 return "Anonymous Player"
217 return html_colors(self.nick)
219 def team_html_color(self):
232 class Achievement(object):
234 return "<Achievement(%s, %s, %s)>" % (self.achievement_cd, self.descr,
238 class PlayerAchievement(object):
240 return "<PlayerAchievement(%s, %s)>" % (self.player_id, self.achievement_cd)
243 class PlayerWeaponStat(object):
245 return "<PlayerWeaponStat(%s, %s, %s)>" % (self.player_weapon_stats_id,
246 self.player_id, self.game_id)
249 class Hashkey(object):
250 def __init__(self, player_id=None, hashkey=None):
251 self.player_id = player_id
252 self.hashkey = hashkey
255 return "<Hashkey(%s, %s)>" % (self.player_id, self.hashkey)
258 class PlayerNick(object):
260 return "<PlayerNick(%s, %s)>" % (self.player_id, self.stripped_nick)
263 class PlayerElo(object):
264 def __init__(self, player_id=None, game_type_cd=None):
266 self.player_id = player_id
267 self.game_type_cd = game_type_cd
270 self.elo = ELOPARMS.initial
273 return "<PlayerElo(pid=%s, gametype=%s, elo=%s)>" % \
274 (self.player_id, self.game_type_cd, self.elo)
277 class PlayerRank(object):
279 def nick_html_colors(self):
280 if self.nick is None:
281 return "Anonymous Player"
283 return html_colors(self.nick)
287 return "<PlayerRank(pid=%s, gametype=%s, rank=%s)>" % \
288 (self.player_id, self.game_type_cd, self.rank)
291 def initialize_db(engine=None):
292 DBSession.configure(bind=engine)
293 Base.metadata.bind = engine
294 Base.metadata.create_all(engine)
295 MetaData = sqlalchemy.MetaData(bind=engine, reflect=True)
297 # assign all those tables to an object
298 achievements_table = MetaData.tables['achievements']
299 cd_achievement_table = MetaData.tables['cd_achievement']
300 cd_game_type_table = MetaData.tables['cd_game_type']
301 cd_weapon_table = MetaData.tables['cd_weapon']
302 db_version_table = MetaData.tables['db_version']
303 games_table = MetaData.tables['games']
304 hashkeys_table = MetaData.tables['hashkeys']
305 maps_table = MetaData.tables['maps']
306 player_game_stats_table = MetaData.tables['player_game_stats']
307 players_table = MetaData.tables['players']
308 player_weapon_stats_table = MetaData.tables['player_weapon_stats']
309 servers_table = MetaData.tables['servers']
310 player_nicks_table = MetaData.tables['player_nicks']
311 player_elos_table = MetaData.tables['player_elos']
312 player_ranks_table = MetaData.tables['player_ranks']
314 # now map the tables and the objects together
315 mapper(PlayerAchievement, achievements_table)
316 mapper(Achievement, cd_achievement_table)
317 mapper(GameType, cd_game_type_table)
318 mapper(Weapon, cd_weapon_table)
319 mapper(Game, games_table)
320 mapper(Hashkey, hashkeys_table)
321 mapper(Map, maps_table)
322 mapper(PlayerGameStat, player_game_stats_table)
323 mapper(Player, players_table)
324 mapper(PlayerWeaponStat, player_weapon_stats_table)
325 mapper(Server, servers_table)
326 mapper(PlayerNick, player_nicks_table)
327 mapper(PlayerElo, player_elos_table)
328 mapper(PlayerRank, player_ranks_table)