4 from datetime import timedelta
5 from sqlalchemy.orm import mapper
6 from sqlalchemy.orm import scoped_session
7 from sqlalchemy.orm import sessionmaker
8 from sqlalchemy.ext.declarative import declarative_base
9 from xonstat.elo import KREDUCTION, ELOPARMS
10 from xonstat.util import strip_colors, html_colors, pretty_date
12 log = logging.getLogger(__name__)
14 DBSession = scoped_session(sessionmaker())
15 Base = declarative_base()
17 # define objects for all tables
19 def nick_html_colors(self):
21 return "Anonymous Player"
23 return html_colors(self.nick)
25 def nick_strip_colors(self):
27 return "Anonymous Player"
29 return strip_colors(self.nick)
31 def joined_pretty_date(self):
32 return pretty_date(self.create_dt)
35 return "<Player(%s, %s)>" % (self.player_id,
36 self.nick.encode('utf-8'))
39 class GameType(object):
41 return "<GameType(%s, %s, %s)>" % (self.game_type_cd, self.descr,
47 return "<Weapon(%s, %s, %s)>" % (self.weapon_cd, self.descr,
52 def __init__(self, name=None, hashkey=None, ip_addr=None):
54 self.hashkey = hashkey
55 self.ip_addr = ip_addr
58 return "<Server(%s, %s)>" % (self.server_id, self.name.encode('utf-8'))
62 def __init__(self, name=None):
66 return "<Map(%s, %s, %s)>" % (self.map_id, self.name, self.version)
70 def __init__(self, game_id=None, start_dt=None, game_type_cd=None,
71 server_id=None, map_id=None, winner=None):
72 self.game_id = game_id
73 self.start_dt = start_dt
74 self.game_type_cd = game_type_cd
75 self.server_id = server_id
80 return "<Game(%s, %s, %s, %s)>" % (self.game_id, self.start_dt,
81 self.game_type_cd, self.server_id)
84 return pretty_date(self.start_dt)
86 def process_elos(self, session, game_type_cd=None):
87 if game_type_cd is None:
88 game_type_cd = self.game_type_cd
92 for (p,s,a) in session.query(PlayerGameStat.player_id,
93 PlayerGameStat.score, PlayerGameStat.alivetime).\
94 filter(PlayerGameStat.game_id==self.game_id).\
95 filter(PlayerGameStat.alivetime > timedelta(seconds=0)).\
96 filter(PlayerGameStat.player_id > 2).\
98 # scores are per second
99 scores[p] = s/float(a.seconds)
100 alivetimes[p] = a.seconds
102 player_ids = scores.keys()
105 for e in session.query(PlayerElo).\
106 filter(PlayerElo.player_id.in_(player_ids)).\
107 filter(PlayerElo.game_type_cd==game_type_cd).all():
108 elos[e.player_id] = e
110 # ensure that all player_ids have an elo record
111 for pid in player_ids:
112 if pid not in elos.keys():
113 elos[pid] = PlayerElo(pid, game_type_cd)
115 for pid in player_ids:
116 elos[pid].k = KREDUCTION.eval(elos[pid].games, alivetimes[pid], 0)
118 elos = self.update_elos(elos, scores, ELOPARMS)
120 # add the elos to the session for committing
124 if game_type_cd == 'duel':
125 self.process_elos(session, "dm")
127 def update_elos(self, elos, scores, ep):
129 for pid in elos.keys():
137 for i in xrange(0, len(pids)):
139 for j in xrange(i+1, len(pids)):
141 si = scores[ei.player_id]
142 sj = scores[ej.player_id]
149 si, sj = 1, 1 # a draw
152 scorefactor_real = si / float(si + sj)
154 # estimated score factor by elo
155 elodiff = min(ep.maxlogdistance, max(-ep.maxlogdistance,
156 (float(ei.elo) - float(ej.elo)) * ep.logdistancefactor))
157 scorefactor_elo = 1 / (1 + math.exp(-elodiff))
159 # how much adjustment is good?
160 # scorefactor(elodiff) = 1 / (1 + e^(-elodiff * logdistancefactor))
161 # elodiff(scorefactor) = -ln(1/scorefactor - 1) / logdistancefactor
162 # elodiff'(scorefactor) = 1 / ((scorefactor) (1 - scorefactor) logdistancefactor)
163 # elodiff'(scorefactor) >= 4 / logdistancefactor
165 # adjust'(scorefactor) = K1 + K2
168 # K1 + K2 <= 4 / logdistancefactor <= elodiff'(scorefactor)
169 # as we then don't overcompensate
171 adjustment = scorefactor_real - scorefactor_elo
172 eloadjust[ei.player_id] += adjustment
173 eloadjust[ej.player_id] -= adjustment
175 elos[pid].elo = max(float(elos[pid].elo) + eloadjust[pid] * elos[pid].k * ep.global_K / float(len(elos) - 1), ep.floor)
180 class PlayerGameStat(object):
181 def __init__(self, player_game_stat_id=None, create_dt=None):
182 self.player_game_stat_id = player_game_stat_id
183 self.create_dt = create_dt
186 return "<PlayerGameStat(%s, %s, %s)>" \
187 % (self.player_id, self.game_id, self.create_dt)
189 def nick_stripped(self):
190 if self.nick is None:
191 return "Anonymous Player"
193 return strip_colors(self.nick)
195 def nick_html_colors(self):
196 if self.nick is None:
197 return "Anonymous Player"
199 return html_colors(self.nick)
201 def team_html_color(self):
214 class Achievement(object):
216 return "<Achievement(%s, %s, %s)>" % (self.achievement_cd, self.descr,
220 class PlayerAchievement(object):
222 return "<PlayerAchievement(%s, %s)>" % (self.player_id, self.achievement_cd)
225 class PlayerWeaponStat(object):
227 return "<PlayerWeaponStat(%s, %s, %s)>" % (self.player_weapon_stats_id,
228 self.player_id, self.game_id)
231 class Hashkey(object):
232 def __init__(self, player_id=None, hashkey=None):
233 self.player_id = player_id
234 self.hashkey = hashkey
237 return "<Hashkey(%s, %s)>" % (self.player_id, self.hashkey)
240 class PlayerNick(object):
242 return "<PlayerNick(%s, %s)>" % (self.player_id, self.stripped_nick)
245 class PlayerElo(object):
246 def __init__(self, player_id=None, game_type_cd=None):
248 self.player_id = player_id
249 self.game_type_cd = game_type_cd
252 self.elo = ELOPARMS.initial
255 return "<PlayerElo(pid=%s, gametype=%s, elo=%s)>" % \
256 (self.player_id, self.game_type_cd, self.elo)
259 def initialize_db(engine=None):
260 DBSession.configure(bind=engine)
261 Base.metadata.bind = engine
262 Base.metadata.create_all(engine)
263 MetaData = sqlalchemy.MetaData(bind=engine, reflect=True)
265 # assign all those tables to an object
266 achievements_table = MetaData.tables['achievements']
267 cd_achievement_table = MetaData.tables['cd_achievement']
268 cd_game_type_table = MetaData.tables['cd_game_type']
269 cd_weapon_table = MetaData.tables['cd_weapon']
270 db_version_table = MetaData.tables['db_version']
271 games_table = MetaData.tables['games']
272 hashkeys_table = MetaData.tables['hashkeys']
273 maps_table = MetaData.tables['maps']
274 player_game_stats_table = MetaData.tables['player_game_stats']
275 players_table = MetaData.tables['players']
276 player_weapon_stats_table = MetaData.tables['player_weapon_stats']
277 servers_table = MetaData.tables['servers']
278 player_nicks_table = MetaData.tables['player_nicks']
279 player_elos_table = MetaData.tables['player_elos']
281 # now map the tables and the objects together
282 mapper(PlayerAchievement, achievements_table)
283 mapper(Achievement, cd_achievement_table)
284 mapper(GameType, cd_game_type_table)
285 mapper(Weapon, cd_weapon_table)
286 mapper(Game, games_table)
287 mapper(Hashkey, hashkeys_table)
288 mapper(Map, maps_table)
289 mapper(PlayerGameStat, player_game_stats_table)
290 mapper(Player, players_table)
291 mapper(PlayerWeaponStat, player_weapon_stats_table)
292 mapper(Server, servers_table)
293 mapper(PlayerNick, player_nicks_table)
294 mapper(PlayerElo, player_elos_table)