]> git.xonotic.org Git - xonotic/xonstat.git/blob - xonstat/models.py
Fix merge conflict, change indentation a bit.
[xonotic/xonstat.git] / xonstat / models.py
1 import json
2 import logging
3 import math
4 import sqlalchemy
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
13
14 log = logging.getLogger(__name__)
15
16 DBSession = scoped_session(sessionmaker())
17 Base = declarative_base()
18
19 # define objects for all tables
20 class Player(object):
21     def nick_html_colors(self):
22         if self.nick is None:
23             return "Anonymous Player"
24         else:
25             return html_colors(self.nick)
26
27     def nick_strip_colors(self):
28         if self.nick is None:
29             return "Anonymous Player"
30         else:
31             return strip_colors(self.nick)
32
33     def joined_pretty_date(self):
34         return pretty_date(self.create_dt)
35
36     def __repr__(self):
37         return "<Player(%s, %s)>" % (self.player_id, self.nick.encode('utf-8'))
38
39     def to_dict(self):
40         return {'player_id':self.player_id, 'name':self.nick.encode('utf-8')}
41
42
43 class GameType(object):
44     def __repr__(self):
45         return "<GameType(%s, %s, %s)>" % (self.game_type_cd, self.descr, self.active_ind)
46
47     def to_dict(self):
48         return {'game_type_cd':self.game_type_cd, 'name':self.descr, 'active':self.active_ind}
49
50
51 class Weapon(object):
52     def __repr__(self):
53         return "<Weapon(%s, %s, %s)>" % (self.weapon_cd, self.descr, self.active_ind)
54
55     def to_dict(self):
56         return {'weapon_cd':self.weapon_cd, 'name':self.descr, 'active':self.active_ind}
57
58
59 class Server(object):
60     def __init__(self, name=None, hashkey=None, ip_addr=None):
61         self.name = name
62         self.hashkey = hashkey
63         self.ip_addr = ip_addr
64
65     def __repr__(self):
66         return "<Server(%s, %s)>" % (self.server_id, self.name.encode('utf-8'))
67
68     def to_dict(self):
69         return {'server_id':self.server_id, 'name':self.name.encode('utf-8')}
70
71
72 class Map(object):
73     def __init__(self, name=None):
74         self.name = name
75
76     def __repr__(self):
77         return "<Map(%s, %s, %s)>" % (self.map_id, self.name, self.version)
78
79     def to_dict(self):
80         return {'map_id':self.map_id, 'name':self.name, 'version':self.version}
81
82
83 class Game(object):
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
90         self.map_id = map_id
91         self.winner = winner
92
93     def __repr__(self):
94         return "<Game(%s, %s, %s, %s)>" % (self.game_id, self.start_dt, self.game_type_cd, self.server_id)
95
96     def to_dict(self):
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}
98
99     def fuzzy_date(self):
100         return pretty_date(self.start_dt)
101
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
105
106         # we do not have the actual duration of the game, so use the 
107         # maximum alivetime of the players instead
108         duration = 0
109         for d in session.query(sfunc.max(PlayerGameStat.alivetime)).\
110                     filter(PlayerGameStat.game_id==self.game_id).\
111                     one():
112             duration = d.seconds
113
114         scores = {}
115         alivetimes = {}
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).\
121                 all():
122                     # scores are per second
123                     scores[p] = s/float(a.seconds)
124                     alivetimes[p] = a.seconds
125
126         player_ids = scores.keys()
127
128         elos = {}
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
133
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)
138
139         for pid in player_ids:
140             elos[pid].k = KREDUCTION.eval(elos[pid].games, alivetimes[pid],
141                     duration)
142             if elos[pid].k == 0:
143                 del(elos[pid])
144                 del(scores[pid])
145                 del(alivetimes[pid])
146
147         elos = self.update_elos(elos, scores, ELOPARMS)
148
149         # add the elos to the session for committing
150         for e in elos:
151             session.add(elos[e])
152
153         if game_type_cd == 'duel':
154             self.process_elos(session, "dm")
155
156     def update_elos(self, elos, scores, ep):
157         eloadjust = {}
158         for pid in elos.keys():
159             eloadjust[pid] = 0
160
161         if len(elos) < 2:
162             return elos
163
164         pids = elos.keys()
165
166         for i in xrange(0, len(pids)):
167             ei = elos[pids[i]]
168             for j in xrange(i+1, len(pids)):
169                 ej = elos[pids[j]]
170                 si = scores[ei.player_id]
171                 sj = scores[ej.player_id]
172
173                 # normalize scores
174                 ofs = min(0, si, sj)
175                 si -= ofs
176                 sj -= ofs
177                 if si + sj == 0:
178                     si, sj = 1, 1 # a draw
179
180                 # real score factor
181                 scorefactor_real = si / float(si + sj)
182
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))
187
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
193
194                 # adjust'(scorefactor) = K1 + K2
195
196                 # so we want:
197                 # K1 + K2 <= 4 / logdistancefactor <= elodiff'(scorefactor)
198                 # as we then don't overcompensate
199
200                 adjustment = scorefactor_real - scorefactor_elo
201                 eloadjust[ei.player_id] += adjustment
202                 eloadjust[ej.player_id] -= adjustment
203         for pid in pids:
204             elos[pid].elo = max(float(elos[pid].elo) + eloadjust[pid] * elos[pid].k * ep.global_K / float(len(elos) - 1), ep.floor)
205             elos[pid].games += 1
206         return elos
207
208
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
213
214     def __repr__(self):
215         return "<PlayerGameStat(%s, %s, %s)>" % (self.player_id, self.game_id, self.create_dt)
216
217     def to_dict(self):
218         return {'player_id':self.player_id, 'game_id':self.game_id, 'create_dt':self.create_dt.strftime('%Y-%m-%dT%H:%M:%SZ')}
219
220     def nick_stripped(self):
221         if self.nick is None:
222             return "Anonymous Player"
223         else:
224             return strip_colors(self.nick)
225
226     def nick_html_colors(self):
227         if self.nick is None:
228             return "Anonymous Player"
229         else:
230             return html_colors(self.nick)
231
232     def team_html_color(self):
233         # blue
234         if self.team == 5:
235             return "red"
236         # red
237         if self.team == 14:
238             return "blue"
239         if self.team == 13:
240             return "yellow"
241         if self.team == 10:
242             return "pink"
243
244
245 class Achievement(object):
246     def __repr__(self):
247         return "<Achievement(%s, %s, %s)>" % (self.achievement_cd, self.descr, self.limit)
248
249     def to_dict(self):
250         return {'achievement_cd':self.achievement_cd, 'name':self.descr, 'limit':self.limit}
251
252
253 class PlayerAchievement(object):
254     def __repr__(self):
255         return "<PlayerAchievement(%s, %s)>" % (self.player_id, self.achievement_cd)
256
257     def to_dict(self):
258         return {'player_id':self.player_id, 'achievement_cd':self.achievement_cd}
259
260
261 class PlayerWeaponStat(object):
262     def __repr__(self):
263         return "<PlayerWeaponStat(%s, %s, %s)>" % (self.player_weapon_stats_id, self.player_id, self.game_id)
264
265     def to_dict(self):
266         return {'player_weapon_stats_id':self.player_weapon_stats_id, 'player_id':self.player_id, 'game_id':self.game_id}
267
268
269 class Hashkey(object):
270     def __init__(self, player_id=None, hashkey=None):
271         self.player_id = player_id
272         self.hashkey = hashkey
273
274     def __repr__(self):
275         return "<Hashkey(%s, %s)>" % (self.player_id, self.hashkey)
276
277     def to_dict(self):
278         return {'player_id':self.player_id, 'hashkey':self.hashkey}
279
280
281 class PlayerNick(object):
282     def __repr__(self):
283         return "<PlayerNick(%s, %s)>" % (self.player_id, self.stripped_nick)
284
285     def to_dict(self):
286         return {'player_id':self.player_id, 'name':self.stripped_nick}
287
288
289 class PlayerElo(object):
290     def __init__(self, player_id=None, game_type_cd=None):
291
292         self.player_id = player_id
293         self.game_type_cd = game_type_cd
294         self.score = 0
295         self.games = 0
296         self.elo = ELOPARMS.initial
297
298     def __repr__(self):
299         return "<PlayerElo(pid=%s, gametype=%s, elo=%s)>" % (self.player_id, self.game_type_cd, self.elo)
300
301     def to_dict(self):
302         return {'player_id':self.player_id, 'game_type_cd':self.game_type_cd, 'elo':self.elo}
303
304
305 class PlayerRank(object):
306
307     def nick_html_colors(self):
308         if self.nick is None:
309             return "Anonymous Player"
310         else:
311             return html_colors(self.nick)
312
313     def __repr__(self):
314         return "<PlayerRank(pid=%s, gametype=%s, rank=%s)>" % (self.player_id, self.game_type_cd, self.rank)
315
316     def to_dict(self):
317         return {'player_id':self.player_id, 'game_type_cd':self.game_type_cd, 'rank':self.rank}
318
319
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)
325
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']
342
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)