]> git.xonotic.org Git - xonotic/xonstat.git/blob - xonstat/models.py
Should be ready to go now!
[xonotic/xonstat.git] / xonstat / models.py
1 import logging
2 import math
3 import sqlalchemy
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
11
12 log = logging.getLogger(__name__)
13
14 DBSession = scoped_session(sessionmaker())
15 Base = declarative_base()
16
17 # define objects for all tables
18 class Player(object):
19     def nick_html_colors(self):
20         if self.nick is None:
21             return "Anonymous Player"
22         else:
23             return html_colors(self.nick)
24
25     def nick_strip_colors(self):
26         if self.nick is None:
27             return "Anonymous Player"
28         else:
29             return strip_colors(self.nick)
30
31     def joined_pretty_date(self):
32         return pretty_date(self.create_dt)
33
34     def __repr__(self):
35         return "<Player(%s, %s)>" % (self.player_id, 
36                 self.nick.encode('utf-8'))
37
38
39 class GameType(object):
40     def __repr__(self):
41         return "<GameType(%s, %s, %s)>" % (self.game_type_cd, self.descr, 
42                 self.active_ind)
43
44
45 class Weapon(object):
46     def __repr__(self):
47         return "<Weapon(%s, %s, %s)>" % (self.weapon_cd, self.descr, 
48                 self.active_ind)
49
50
51 class Server(object):
52     def __init__(self, name=None, hashkey=None, ip_addr=None):
53         self.name = name
54         self.hashkey = hashkey
55         self.ip_addr = ip_addr
56
57     def __repr__(self):
58         return "<Server(%s, %s)>" % (self.server_id, self.name.encode('utf-8'))
59
60
61 class Map(object):
62     def __init__(self, name=None):
63         self.name = name
64
65     def __repr__(self):
66         return "<Map(%s, %s, %s)>" % (self.map_id, self.name, self.version)
67
68
69 class Game(object):
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
76         self.map_id = map_id
77         self.winner = winner
78
79     def __repr__(self):
80         return "<Game(%s, %s, %s, %s)>" % (self.game_id, self.start_dt, 
81                 self.game_type_cd, self.server_id)
82
83     def fuzzy_date(self):
84         return pretty_date(self.start_dt)
85
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
89
90         scores = {}
91         alivetimes = {}
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).\
97                 all():
98                     # scores are per second
99                     scores[p] = s/float(a.seconds)
100                     alivetimes[p] = a.seconds
101
102         player_ids = scores.keys()
103
104         elos = {}
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
109
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)
114
115         for pid in player_ids:
116             elos[pid].k = KREDUCTION.eval(elos[pid].games, alivetimes[pid], 0)
117
118         elos = self.update_elos(elos, scores, ELOPARMS)
119
120         # add the elos to the session for committing
121         for e in elos:
122             session.add(elos[e])
123
124         if game_type_cd == 'duel':
125             self.process_elos(session, "dm")
126
127     def update_elos(self, elos, scores, ep):
128         eloadjust = {}
129         for pid in elos.keys():
130             eloadjust[pid] = 0
131
132         if len(elos) < 2:
133             return elos
134
135         pids = elos.keys()
136
137         for i in xrange(0, len(pids)):
138             ei = elos[pids[i]]
139             for j in xrange(i+1, len(pids)):
140                 ej = elos[pids[j]]
141                 si = scores[ei.player_id]
142                 sj = scores[ej.player_id]
143
144                 # normalize scores
145                 ofs = min(0, si, sj)
146                 si -= ofs
147                 sj -= ofs
148                 if si + sj == 0:
149                     si, sj = 1, 1 # a draw
150
151                 # real score factor
152                 scorefactor_real = si / float(si + sj)
153
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))
158
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
164
165                 # adjust'(scorefactor) = K1 + K2
166
167                 # so we want:
168                 # K1 + K2 <= 4 / logdistancefactor <= elodiff'(scorefactor)
169                 # as we then don't overcompensate
170
171                 adjustment = scorefactor_real - scorefactor_elo
172                 eloadjust[ei.player_id] += adjustment
173                 eloadjust[ej.player_id] -= adjustment
174         for pid in pids:
175             elos[pid].elo = max(float(elos[pid].elo) + eloadjust[pid] * elos[pid].k * ep.global_K / float(len(elos) - 1), ep.floor)
176             elos[pid].games += 1
177         return elos
178
179
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
184
185     def __repr__(self):
186         return "<PlayerGameStat(%s, %s, %s)>" \
187         % (self.player_id, self.game_id, self.create_dt)
188
189     def nick_stripped(self):
190         if self.nick is None:
191             return "Anonymous Player"
192         else:
193             return strip_colors(self.nick)
194
195     def nick_html_colors(self):
196         if self.nick is None:
197             return "Anonymous Player"
198         else:
199             return html_colors(self.nick)
200
201     def team_html_color(self):
202         # blue
203         if self.team == 5:
204             return "red"
205         # red
206         if self.team == 14:
207             return "blue"
208         if self.team == 13:
209             return "yellow"
210         if self.team == 10:
211             return "pink"
212
213
214 class Achievement(object):
215     def __repr__(self):
216         return "<Achievement(%s, %s, %s)>" % (self.achievement_cd, self.descr,
217                 self.limit)
218
219
220 class PlayerAchievement(object):
221     def __repr__(self):
222         return "<PlayerAchievement(%s, %s)>" % (self.player_id, self.achievement_cd)
223
224
225 class PlayerWeaponStat(object):
226     def __repr__(self):
227         return "<PlayerWeaponStat(%s, %s, %s)>" % (self.player_weapon_stats_id,
228                 self.player_id, self.game_id)
229
230
231 class Hashkey(object):
232     def __init__(self, player_id=None, hashkey=None):
233         self.player_id = player_id
234         self.hashkey = hashkey
235
236     def __repr__(self):
237         return "<Hashkey(%s, %s)>" % (self.player_id, self.hashkey)
238
239
240 class PlayerNick(object):
241     def __repr__(self):
242         return "<PlayerNick(%s, %s)>" % (self.player_id, self.stripped_nick)
243
244
245 class PlayerElo(object):
246     def __init__(self, player_id=None, game_type_cd=None):
247
248         self.player_id = player_id
249         self.game_type_cd = game_type_cd
250         self.score = 0
251         self.games = 0
252         self.elo = ELOPARMS.initial
253
254     def __repr__(self):
255         return "<PlayerElo(pid=%s, gametype=%s, elo=%s)>" % \
256                 (self.player_id, self.game_type_cd, self.elo)
257
258
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)
264
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']
280
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)