]> git.xonotic.org Git - xonotic/xonstat.git/blob - xonstat/models.py
Add initial support for JSON on map_index view.
[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, 
38                 self.nick.encode('utf-8'))
39
40
41 class GameType(object):
42     def __repr__(self):
43         return "<GameType(%s, %s, %s)>" % (self.game_type_cd, self.descr, 
44                 self.active_ind)
45
46
47 class Weapon(object):
48     def __repr__(self):
49         return "<Weapon(%s, %s, %s)>" % (self.weapon_cd, self.descr, 
50                 self.active_ind)
51
52
53 class Server(object):
54     def __init__(self, name=None, hashkey=None, ip_addr=None):
55         self.name = name
56         self.hashkey = hashkey
57         self.ip_addr = ip_addr
58
59     def __repr__(self):
60         return "<Server(%s, %s)>" % (self.server_id, self.name.encode('utf-8'))
61
62
63 class Map(object):
64     def __init__(self, name=None):
65         self.name = name
66
67     def __repr__(self):
68         return "<Map(%s, %s, %s)>" % (self.map_id, self.name, self.version)
69
70     def to_dict(self):
71         return {'map_id':self.map_id, 'name':self.name}
72
73
74 class Game(object):
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
81         self.map_id = map_id
82         self.winner = winner
83
84     def __repr__(self):
85         return "<Game(%s, %s, %s, %s)>" % (self.game_id, self.start_dt, 
86                 self.game_type_cd, self.server_id)
87
88     def fuzzy_date(self):
89         return pretty_date(self.start_dt)
90
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
94
95         # we do not have the actual duration of the game, so use the 
96         # maximum alivetime of the players instead
97         duration = 0
98         for d in session.query(sfunc.max(PlayerGameStat.alivetime)).\
99                     filter(PlayerGameStat.game_id==self.game_id).\
100                     one():
101             duration = d.seconds
102
103         scores = {}
104         alivetimes = {}
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).\
110                 all():
111                     # scores are per second
112                     scores[p] = s/float(a.seconds)
113                     alivetimes[p] = a.seconds
114
115         player_ids = scores.keys()
116
117         elos = {}
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
122
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)
127
128         for pid in player_ids:
129             elos[pid].k = KREDUCTION.eval(elos[pid].games, alivetimes[pid],
130                     duration)
131             if elos[pid].k == 0:
132                 del(elos[pid])
133                 del(scores[pid])
134                 del(alivetimes[pid])
135
136         elos = self.update_elos(elos, scores, ELOPARMS)
137
138         # add the elos to the session for committing
139         for e in elos:
140             session.add(elos[e])
141
142         if game_type_cd == 'duel':
143             self.process_elos(session, "dm")
144
145     def update_elos(self, elos, scores, ep):
146         eloadjust = {}
147         for pid in elos.keys():
148             eloadjust[pid] = 0
149
150         if len(elos) < 2:
151             return elos
152
153         pids = elos.keys()
154
155         for i in xrange(0, len(pids)):
156             ei = elos[pids[i]]
157             for j in xrange(i+1, len(pids)):
158                 ej = elos[pids[j]]
159                 si = scores[ei.player_id]
160                 sj = scores[ej.player_id]
161
162                 # normalize scores
163                 ofs = min(0, si, sj)
164                 si -= ofs
165                 sj -= ofs
166                 if si + sj == 0:
167                     si, sj = 1, 1 # a draw
168
169                 # real score factor
170                 scorefactor_real = si / float(si + sj)
171
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))
176
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
182
183                 # adjust'(scorefactor) = K1 + K2
184
185                 # so we want:
186                 # K1 + K2 <= 4 / logdistancefactor <= elodiff'(scorefactor)
187                 # as we then don't overcompensate
188
189                 adjustment = scorefactor_real - scorefactor_elo
190                 eloadjust[ei.player_id] += adjustment
191                 eloadjust[ej.player_id] -= adjustment
192         for pid in pids:
193             elos[pid].elo = max(float(elos[pid].elo) + eloadjust[pid] * elos[pid].k * ep.global_K / float(len(elos) - 1), ep.floor)
194             elos[pid].games += 1
195         return elos
196
197
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
202
203     def __repr__(self):
204         return "<PlayerGameStat(%s, %s, %s)>" \
205         % (self.player_id, self.game_id, self.create_dt)
206
207     def nick_stripped(self):
208         if self.nick is None:
209             return "Anonymous Player"
210         else:
211             return strip_colors(self.nick)
212
213     def nick_html_colors(self):
214         if self.nick is None:
215             return "Anonymous Player"
216         else:
217             return html_colors(self.nick)
218
219     def team_html_color(self):
220         # blue
221         if self.team == 5:
222             return "red"
223         # red
224         if self.team == 14:
225             return "blue"
226         if self.team == 13:
227             return "yellow"
228         if self.team == 10:
229             return "pink"
230
231
232 class Achievement(object):
233     def __repr__(self):
234         return "<Achievement(%s, %s, %s)>" % (self.achievement_cd, self.descr,
235                 self.limit)
236
237
238 class PlayerAchievement(object):
239     def __repr__(self):
240         return "<PlayerAchievement(%s, %s)>" % (self.player_id, self.achievement_cd)
241
242
243 class PlayerWeaponStat(object):
244     def __repr__(self):
245         return "<PlayerWeaponStat(%s, %s, %s)>" % (self.player_weapon_stats_id,
246                 self.player_id, self.game_id)
247
248
249 class Hashkey(object):
250     def __init__(self, player_id=None, hashkey=None):
251         self.player_id = player_id
252         self.hashkey = hashkey
253
254     def __repr__(self):
255         return "<Hashkey(%s, %s)>" % (self.player_id, self.hashkey)
256
257
258 class PlayerNick(object):
259     def __repr__(self):
260         return "<PlayerNick(%s, %s)>" % (self.player_id, self.stripped_nick)
261
262
263 class PlayerElo(object):
264     def __init__(self, player_id=None, game_type_cd=None):
265
266         self.player_id = player_id
267         self.game_type_cd = game_type_cd
268         self.score = 0
269         self.games = 0
270         self.elo = ELOPARMS.initial
271
272     def __repr__(self):
273         return "<PlayerElo(pid=%s, gametype=%s, elo=%s)>" % \
274                 (self.player_id, self.game_type_cd, self.elo)
275
276
277 class PlayerRank(object):
278
279     def nick_html_colors(self):
280         if self.nick is None:
281             return "Anonymous Player"
282         else:
283             return html_colors(self.nick)
284
285
286     def __repr__(self):
287         return "<PlayerRank(pid=%s, gametype=%s, rank=%s)>" % \
288                 (self.player_id, self.game_type_cd, self.rank)
289
290
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)
296
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']
313
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)