Add player_ranks to the mix - it is a batch table intended to represent the latest...
[xonotic/xonstat.git] / xonstat / models.py
1 import logging
2 import math
3 import sqlalchemy
4 import sqlalchemy.sql.functions as sfunc
5 from datetime import timedelta
6 from sqlalchemy.orm import mapper
7 from sqlalchemy.orm import scoped_session
8 from sqlalchemy.orm import sessionmaker
9 from sqlalchemy.ext.declarative import declarative_base
10 from xonstat.elo import KREDUCTION, ELOPARMS
11 from xonstat.util import strip_colors, html_colors, pretty_date
12
13 log = logging.getLogger(__name__)
14
15 DBSession = scoped_session(sessionmaker())
16 Base = declarative_base()
17
18 # define objects for all tables
19 class Player(object):
20     def nick_html_colors(self):
21         if self.nick is None:
22             return "Anonymous Player"
23         else:
24             return html_colors(self.nick)
25
26     def nick_strip_colors(self):
27         if self.nick is None:
28             return "Anonymous Player"
29         else:
30             return strip_colors(self.nick)
31
32     def joined_pretty_date(self):
33         return pretty_date(self.create_dt)
34
35     def __repr__(self):
36         return "<Player(%s, %s)>" % (self.player_id, 
37                 self.nick.encode('utf-8'))
38
39
40 class GameType(object):
41     def __repr__(self):
42         return "<GameType(%s, %s, %s)>" % (self.game_type_cd, self.descr, 
43                 self.active_ind)
44
45
46 class Weapon(object):
47     def __repr__(self):
48         return "<Weapon(%s, %s, %s)>" % (self.weapon_cd, self.descr, 
49                 self.active_ind)
50
51
52 class Server(object):
53     def __init__(self, name=None, hashkey=None, ip_addr=None):
54         self.name = name
55         self.hashkey = hashkey
56         self.ip_addr = ip_addr
57
58     def __repr__(self):
59         return "<Server(%s, %s)>" % (self.server_id, self.name.encode('utf-8'))
60
61
62 class Map(object):
63     def __init__(self, name=None):
64         self.name = name
65
66     def __repr__(self):
67         return "<Map(%s, %s, %s)>" % (self.map_id, self.name, self.version)
68
69
70 class Game(object):
71     def __init__(self, game_id=None, start_dt=None, game_type_cd=None, 
72             server_id=None, map_id=None, winner=None):
73         self.game_id = game_id
74         self.start_dt = start_dt
75         self.game_type_cd = game_type_cd
76         self.server_id = server_id
77         self.map_id = map_id
78         self.winner = winner
79
80     def __repr__(self):
81         return "<Game(%s, %s, %s, %s)>" % (self.game_id, self.start_dt, 
82                 self.game_type_cd, self.server_id)
83
84     def fuzzy_date(self):
85         return pretty_date(self.start_dt)
86
87     def process_elos(self, session, game_type_cd=None):
88         if game_type_cd is None:
89             game_type_cd = self.game_type_cd
90
91         # we do not have the actual duration of the game, so use the 
92         # maximum alivetime of the players instead
93         duration = 0
94         for d in session.query(sfunc.max(PlayerGameStat.alivetime)).\
95                     filter(PlayerGameStat.game_id==self.game_id).\
96                     one():
97             duration = d.seconds
98
99         scores = {}
100         alivetimes = {}
101         for (p,s,a) in session.query(PlayerGameStat.player_id, 
102                 PlayerGameStat.score, PlayerGameStat.alivetime).\
103                 filter(PlayerGameStat.game_id==self.game_id).\
104                 filter(PlayerGameStat.alivetime > timedelta(seconds=0)).\
105                 filter(PlayerGameStat.player_id > 2).\
106                 all():
107                     # scores are per second
108                     scores[p] = s/float(a.seconds)
109                     alivetimes[p] = a.seconds
110
111         player_ids = scores.keys()
112
113         elos = {}
114         for e in session.query(PlayerElo).\
115                 filter(PlayerElo.player_id.in_(player_ids)).\
116                 filter(PlayerElo.game_type_cd==game_type_cd).all():
117                     elos[e.player_id] = e
118
119         # ensure that all player_ids have an elo record
120         for pid in player_ids:
121             if pid not in elos.keys():
122                 elos[pid] = PlayerElo(pid, game_type_cd)
123
124         for pid in player_ids:
125             elos[pid].k = KREDUCTION.eval(elos[pid].games, alivetimes[pid],
126                     duration)
127             if elos[pid].k == 0:
128                 del(elos[pid])
129                 del(scores[pid])
130                 del(alivetimes[pid])
131
132         elos = self.update_elos(elos, scores, ELOPARMS)
133
134         # add the elos to the session for committing
135         for e in elos:
136             session.add(elos[e])
137
138         if game_type_cd == 'duel':
139             self.process_elos(session, "dm")
140
141     def update_elos(self, elos, scores, ep):
142         eloadjust = {}
143         for pid in elos.keys():
144             eloadjust[pid] = 0
145
146         if len(elos) < 2:
147             return elos
148
149         pids = elos.keys()
150
151         for i in xrange(0, len(pids)):
152             ei = elos[pids[i]]
153             for j in xrange(i+1, len(pids)):
154                 ej = elos[pids[j]]
155                 si = scores[ei.player_id]
156                 sj = scores[ej.player_id]
157
158                 # normalize scores
159                 ofs = min(0, si, sj)
160                 si -= ofs
161                 sj -= ofs
162                 if si + sj == 0:
163                     si, sj = 1, 1 # a draw
164
165                 # real score factor
166                 scorefactor_real = si / float(si + sj)
167
168                 # estimated score factor by elo
169                 elodiff = min(ep.maxlogdistance, max(-ep.maxlogdistance,
170                     (float(ei.elo) - float(ej.elo)) * ep.logdistancefactor))
171                 scorefactor_elo = 1 / (1 + math.exp(-elodiff))
172
173                 # how much adjustment is good?
174                 # scorefactor(elodiff) = 1 / (1 + e^(-elodiff * logdistancefactor))
175                 # elodiff(scorefactor) = -ln(1/scorefactor - 1) / logdistancefactor
176                 # elodiff'(scorefactor) = 1 / ((scorefactor) (1 - scorefactor) logdistancefactor)
177                 # elodiff'(scorefactor) >= 4 / logdistancefactor
178
179                 # adjust'(scorefactor) = K1 + K2
180
181                 # so we want:
182                 # K1 + K2 <= 4 / logdistancefactor <= elodiff'(scorefactor)
183                 # as we then don't overcompensate
184
185                 adjustment = scorefactor_real - scorefactor_elo
186                 eloadjust[ei.player_id] += adjustment
187                 eloadjust[ej.player_id] -= adjustment
188         for pid in pids:
189             elos[pid].elo = max(float(elos[pid].elo) + eloadjust[pid] * elos[pid].k * ep.global_K / float(len(elos) - 1), ep.floor)
190             elos[pid].games += 1
191         return elos
192
193
194 class PlayerGameStat(object):
195     def __init__(self, player_game_stat_id=None, create_dt=None):
196         self.player_game_stat_id = player_game_stat_id
197         self.create_dt = create_dt
198
199     def __repr__(self):
200         return "<PlayerGameStat(%s, %s, %s)>" \
201         % (self.player_id, self.game_id, self.create_dt)
202
203     def nick_stripped(self):
204         if self.nick is None:
205             return "Anonymous Player"
206         else:
207             return strip_colors(self.nick)
208
209     def nick_html_colors(self):
210         if self.nick is None:
211             return "Anonymous Player"
212         else:
213             return html_colors(self.nick)
214
215     def team_html_color(self):
216         # blue
217         if self.team == 5:
218             return "red"
219         # red
220         if self.team == 14:
221             return "blue"
222         if self.team == 13:
223             return "yellow"
224         if self.team == 10:
225             return "pink"
226
227
228 class Achievement(object):
229     def __repr__(self):
230         return "<Achievement(%s, %s, %s)>" % (self.achievement_cd, self.descr,
231                 self.limit)
232
233
234 class PlayerAchievement(object):
235     def __repr__(self):
236         return "<PlayerAchievement(%s, %s)>" % (self.player_id, self.achievement_cd)
237
238
239 class PlayerWeaponStat(object):
240     def __repr__(self):
241         return "<PlayerWeaponStat(%s, %s, %s)>" % (self.player_weapon_stats_id,
242                 self.player_id, self.game_id)
243
244
245 class Hashkey(object):
246     def __init__(self, player_id=None, hashkey=None):
247         self.player_id = player_id
248         self.hashkey = hashkey
249
250     def __repr__(self):
251         return "<Hashkey(%s, %s)>" % (self.player_id, self.hashkey)
252
253
254 class PlayerNick(object):
255     def __repr__(self):
256         return "<PlayerNick(%s, %s)>" % (self.player_id, self.stripped_nick)
257
258
259 class PlayerElo(object):
260     def __init__(self, player_id=None, game_type_cd=None):
261
262         self.player_id = player_id
263         self.game_type_cd = game_type_cd
264         self.score = 0
265         self.games = 0
266         self.elo = ELOPARMS.initial
267
268     def __repr__(self):
269         return "<PlayerElo(pid=%s, gametype=%s, elo=%s)>" % \
270                 (self.player_id, self.game_type_cd, self.elo)
271
272
273 class PlayerRank(object):
274
275     def nick_html_colors(self):
276         if self.nick is None:
277             return "Anonymous Player"
278         else:
279             return html_colors(self.nick)
280
281
282     def __repr__(self):
283         return "<PlayerRank(pid=%s, gametype=%s, rank=%s)>" % \
284                 (self.player_id, self.game_type_cd, self.rank)
285
286
287 def initialize_db(engine=None):
288     DBSession.configure(bind=engine)
289     Base.metadata.bind = engine
290     Base.metadata.create_all(engine)
291     MetaData = sqlalchemy.MetaData(bind=engine, reflect=True)
292
293     # assign all those tables to an object
294     achievements_table = MetaData.tables['achievements']
295     cd_achievement_table = MetaData.tables['cd_achievement']
296     cd_game_type_table = MetaData.tables['cd_game_type']
297     cd_weapon_table = MetaData.tables['cd_weapon']
298     db_version_table = MetaData.tables['db_version']
299     games_table = MetaData.tables['games']
300     hashkeys_table = MetaData.tables['hashkeys']
301     maps_table = MetaData.tables['maps']
302     player_game_stats_table = MetaData.tables['player_game_stats']
303     players_table = MetaData.tables['players']
304     player_weapon_stats_table = MetaData.tables['player_weapon_stats']
305     servers_table = MetaData.tables['servers']
306     player_nicks_table = MetaData.tables['player_nicks']
307     player_elos_table = MetaData.tables['player_elos']
308     player_ranks_table = MetaData.tables['player_ranks']
309
310     # now map the tables and the objects together
311     mapper(PlayerAchievement, achievements_table)
312     mapper(Achievement, cd_achievement_table)
313     mapper(GameType, cd_game_type_table)
314     mapper(Weapon, cd_weapon_table)
315     mapper(Game, games_table)
316     mapper(Hashkey, hashkeys_table)
317     mapper(Map, maps_table)
318     mapper(PlayerGameStat, player_game_stats_table)
319     mapper(Player, players_table)
320     mapper(PlayerWeaponStat, player_weapon_stats_table)
321     mapper(Server, servers_table)
322     mapper(PlayerNick, player_nicks_table)
323     mapper(PlayerElo, player_elos_table)
324     mapper(PlayerRank, player_ranks_table)