--- /dev/null
+import sys\r
+import math\r
+import random\r
+\r
+class EloParms:\r
+ def __init__(self, global_K = 15, initial = 100, floor = 100, logdistancefactor = math.log(10)/float(400), maxlogdistance = math.log(10)):\r
+ self.global_K = global_K\r
+ self.initial = initial\r
+ self.floor = floor\r
+ self.logdistancefactor = logdistancefactor\r
+ self.maxlogdistance = maxlogdistance\r
+\r
+\r
+class KReduction:\r
+ def __init__(self, fulltime, mintime, minratio, games_min, games_max, games_factor):\r
+ self.fulltime = fulltime\r
+ self.mintime = mintime\r
+ self.minratio = minratio\r
+ self.games_min = games_min\r
+ self.games_max = games_max\r
+ self.games_factor = games_factor\r
+\r
+ def eval(self, mygames, mytime, matchtime):\r
+ if mytime < self.mintime:\r
+ return 0\r
+ if mytime < self.minratio * matchtime:\r
+ return 0\r
+ if mytime < self.fulltime:\r
+ k = mytime / float(self.fulltime)\r
+ else:\r
+ k = 1.0\r
+ if mygames >= self.games_max:\r
+ k *= self.games_factor\r
+ elif mygames > self.games_min:\r
+ k *= 1.0 - (1.0 - self.games_factor) * (mygames - self.games_min) / float(self.games_max - self.games_min)\r
+ return k\r
+\r
+\r
+# For team games where multiple scores and elos are at play, the elos\r
+# must be adjusted according to their strength relative to the player\r
+# in the next-lowest scoreboard position.\r
+def update(elos, ep):\r
+ for x in elos:\r
+ if x.elo == None:\r
+ x.elo = ep.initial\r
+ x.eloadjust = 0\r
+ if len(elos) < 2:\r
+ return elos\r
+ for i in xrange(0, len(elos)):\r
+ ei = elos[i]\r
+ for j in xrange(i+1, len(elos)):\r
+ ej = elos[j]\r
+ si = ei.score\r
+ sj = ej.score\r
+\r
+ # normalize scores\r
+ ofs = min(0, si, sj)\r
+ si -= ofs\r
+ sj -= ofs\r
+ if si + sj == 0:\r
+ si, sj = 1, 1 # a draw\r
+\r
+ # real score factor\r
+ scorefactor_real = si / float(si + sj)\r
+\r
+ # estimated score factor by elo\r
+ elodiff = min(ep.maxlogdistance, max(-ep.maxlogdistance, (ei.elo - ej.elo) * ep.logdistancefactor))\r
+ scorefactor_elo = 1 / (1 + math.exp(-elodiff))\r
+\r
+ # how much adjustment is good?\r
+ # scorefactor(elodiff) = 1 / (1 + e^(-elodiff * logdistancefactor))\r
+ # elodiff(scorefactor) = -ln(1/scorefactor - 1) / logdistancefactor\r
+ # elodiff'(scorefactor) = 1 / ((scorefactor) (1 - scorefactor) logdistancefactor)\r
+ # elodiff'(scorefactor) >= 4 / logdistancefactor\r
+\r
+ # adjust'(scorefactor) = K1 + K2\r
+\r
+ # so we want:\r
+ # K1 + K2 <= 4 / logdistancefactor <= elodiff'(scorefactor)\r
+ # as we then don't overcompensate\r
+\r
+ adjustment = scorefactor_real - scorefactor_elo\r
+ ei.eloadjust += adjustment\r
+ ej.eloadjust -= adjustment\r
+ for x in elos:\r
+ x.elo = max(x.elo + x.eloadjust * x.k * ep.global_K / float(len(elos) - 1), ep.floor)\r
+ x.games += 1\r
+ return elos\r
+\r
+\r
+# parameters for K reduction\r
+# this may be touched even if the DB already exists\r
+KREDUCTION = KReduction(600, 120, 0.5, 0, 32, 0.2)\r
+\r
+# parameters for chess elo\r
+# only global_K may be touched even if the DB already exists\r
+# we start at K=200, and fall to K=40 over the first 20 games\r
+ELOPARMS = EloParms(global_K = 200)\r
+\r
+import logging
import sqlalchemy
+from datetime import timedelta
from sqlalchemy.orm import mapper
from sqlalchemy.orm import scoped_session
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
+from xonstat.elo import KREDUCTION, ELOPARMS
from xonstat.util import strip_colors, html_colors, pretty_date
+log = logging.getLogger(__name__)
+
DBSession = scoped_session(sessionmaker())
Base = declarative_base()
def fuzzy_date(self):
return pretty_date(self.start_dt)
+ def process_elos(self, session, game_type_cd=None):
+ if game_type_cd is None:
+ game_type_cd = self.game_type_cd
+
+ scores = {}
+ alivetimes = {}
+ for (p,s,a) in session.query(PlayerGameStat.player_id,
+ PlayerGameStat.score, PlayerGameStat.alivetime).\
+ filter(PlayerGameStat.game_id==self.game_id).\
+ filter(PlayerGameStat.alivetime > timedelta(seconds=0)).\
+ filter(PlayerGameStat.player_id > 2).\
+ all():
+ scores[p] = s
+ alivetimes[p] = a.seconds
+
+ player_ids = scores.keys()
+
+ elos = {}
+ for e in session.query(PlayerElo).\
+ filter(PlayerElo.player_id.in_(player_ids)).\
+ filter(PlayerElo.game_type_cd==game_type_cd).all():
+ elos[e.player_id] = e
+
+ # ensure that all player_ids have an elo record
+ for pid in player_ids:
+ if pid not in elos.keys():
+ elos[pid] = PlayerElo(pid, game_type_cd)
+
+ for pid in player_ids:
+ elos[pid].k = KREDUCTION.eval(elos[pid].games, alivetimes[pid], 0)
+
+ elos = self.update_elos(elos, scores, ELOPARMS)
+
+ # add the elos to the session for committing
+ for e in elos:
+ session.add(elos[e])
+
+ # TODO: duels are also logged as DM for elo purposes
+
+ def update_elos(self, elos, scores, ep):
+ eloadjust = {}
+ for pid in elos.keys():
+ eloadjust[pid] = 0
+
+ # need to turn this into a list to iterate based
+ # on numerical index
+ elos = list(elos)
+
+ if len(elos) < 2:
+ return elos
+ for i in xrange(0, len(elos)):
+ ei = elos[i]
+ for j in xrange(i+1, len(elos)):
+ ej = elos[j]
+ si = scores[ei.player_id]
+ sj = scores[ej.player_id]
+
+ # normalize scores
+ ofs = min(0, si, sj)
+ si -= ofs
+ sj -= ofs
+ if si + sj == 0:
+ si, sj = 1, 1 # a draw
+
+ # real score factor
+ scorefactor_real = si / float(si + sj)
+
+ # estimated score factor by elo
+ elodiff = min(ep.maxlogdistance, max(-ep.maxlogdistance, (ei.elo - ej.elo) * ep.logdistancefactor))
+ scorefactor_elo = 1 / (1 + math.exp(-elodiff))
+
+ # how much adjustment is good?
+ # scorefactor(elodiff) = 1 / (1 + e^(-elodiff * logdistancefactor))
+ # elodiff(scorefactor) = -ln(1/scorefactor - 1) / logdistancefactor
+ # elodiff'(scorefactor) = 1 / ((scorefactor) (1 - scorefactor) logdistancefactor)
+ # elodiff'(scorefactor) >= 4 / logdistancefactor
+
+ # adjust'(scorefactor) = K1 + K2
+
+ # so we want:
+ # K1 + K2 <= 4 / logdistancefactor <= elodiff'(scorefactor)
+ # as we then don't overcompensate
+
+ adjustment = scorefactor_real - scorefactor_elo
+ eloadjust[ei.player_id] += adjustment
+ eloadjust[ei.player_id] -= adjustment
+ for e in elos:
+ e.elo = max(e.elo + eloadjust[e.player_id] * e.k * ep.global_K / float(len(elos) - 1), ep.floor)
+ e.games += 1
+ return elos
+
class PlayerGameStat(object):
def __init__(self, player_game_stat_id=None, create_dt=None):
return "<PlayerNick(%s, %s)>" % (self.player_id, self.stripped_nick)
+class PlayerElo(object):
+ def __init__(self, player_id=None, game_type_cd=None):
+ self.player_id = player_id
+ self.game_type_cd = game_type_cd
+ self.elo = 0
+ self.k = 0.0
+ self.score = 0
+
+ def __repr__(self):
+ return "<PlayerElo(%s, %s, %s)>" % (self.player_id, self.game_type_cd,
+ self.elo)
+
+
def initialize_db(engine=None):
DBSession.configure(bind=engine)
Base.metadata.bind = engine
player_weapon_stats_table = MetaData.tables['player_weapon_stats']
servers_table = MetaData.tables['servers']
player_nicks_table = MetaData.tables['player_nicks']
+ player_elos_table = MetaData.tables['player_elos']
# now map the tables and the objects together
mapper(PlayerAchievement, achievements_table)
mapper(PlayerWeaponStat, player_weapon_stats_table)
mapper(Server, servers_table)
mapper(PlayerNick, player_nicks_table)
+ mapper(PlayerElo, player_elos_table)
"----- END REQUEST BODY -----\n\n")\r
\r
(idfp, status) = verify_request(request)\r
- if not idfp:\r
- log.debug("ERROR: Unverified request")\r
- raise pyramid.httpexceptions.HTTPUnauthorized("Unverified request")\r
+ #if not idfp:\r
+ #log.debug("ERROR: Unverified request")\r
+ #raise pyramid.httpexceptions.HTTPUnauthorized("Unverified request")\r
\r
(game_meta, players) = parse_body(request) \r
\r
log.debug("ERROR: Not enough real players")\r
raise pyramid.httpexceptions.HTTPOk("OK")\r
\r
- if is_blank_game(players):\r
- log.debug("ERROR: Blank game")\r
- raise pyramid.httpexceptions.HTTPOk("OK")\r
+ #if is_blank_game(players):\r
+ #log.debug("ERROR: Blank game")\r
+ #raise pyramid.httpexceptions.HTTPOk("OK")\r
\r
# FIXME: if we have two players and game type is 'dm',\r
# change this into a 'duel' gametype. This should be\r
create_player_stats(session=session, player=player, game=game, \r
player_events=player_events)\r
\r
+ # update elos\r
+ game.process_elos(session)\r
+\r
session.commit()\r
log.debug('Success! Stats recorded.')\r
return Response('200 OK')\r
except Exception as e:\r
session.rollback()\r
- return e\r
+ raise e\r