Ejemplo n.º 1
0
def import_results(args):
    """
    Imports the match data of a csv file into the result table.

    :param args: A list with arguments from the argument parser
    :type args: namespace
    """

    print "Importing results from", args.file

    try:
        csvfile, reader, hasHeader = utils.get_csv(args.file)
        line = 0

        if hasHeader:
            print "\tFirst line of csv file is ignored. It seems to be a " \
                  "header row.\n"

        # nickname --> player
        players = {}

        for row in reader:
            if line != 0 or (line == 0 and not hasHeader):
                if row[1] is row[2]:
                    continue

                player1 = players.get(row[1], None)
                player2 = players.get(row[2], None)
                if player1 is None:
                    player1, created = utils.add_player(row[1], commit=False)
                    players[player1.nickname.value] = player1
                if player2 is None:
                    player2, created = utils.add_player(row[2], commit=False)
                    players[player2.nickname.value] = player2

                dbRow = Match1on1(player1=player1.player_id.value,
                                  player2=player2.player_id.value,
                                  outcome=row[3],
                                  date=row[0])
                dbRow.save(commit=False)

            if line % 100 == 0:
                sys.stdout.write("\r" + "Imported %d entries..." % line)
                sys.stdout.flush()
            line = line + 1

        Rank_Elo.commit()
        Rank_Glicko.commit()
        Match1on1.commit()
        csvfile.close()
        print "\rImported %d entries." % (line - (1 if hasHeader else 0))
    except csv.Error:
        print "Error importing %s in line %d" % (args.file, line)
    except IOError:
        print "No such file: %s" % args.file
Ejemplo n.º 2
0
def import_results(args):
    """
    Imports the match data of a csv file into the result table.

    :param args: A list with arguments from the argument parser
    :type args: namespace
    """

    print "Importing results from", args.file

    try:
        csvfile, reader, hasHeader = utils.get_csv(args.file)
        line = 0

        if hasHeader:
            print "\tFirst line of csv file is ignored. It seems to be a " \
                  "header row.\n"

        # nickname --> player
        players = {}

        for row in reader:
            if line != 0 or (line == 0 and not hasHeader):
                if row[1] is row[2]:
                    continue

                player1 = players.get(row[1], None)
                player2 = players.get(row[2], None)
                if player1 is None:
                    player1, created = utils.add_player(row[1], commit=False)
                    players[player1.nickname.value] = player1
                if player2 is None:
                    player2, created = utils.add_player(row[2], commit=False)
                    players[player2.nickname.value] = player2

                dbRow = Match1on1(player1=player1.player_id.value,
                    player2=player2.player_id.value, outcome=row[3],
                    date=row[0])
                dbRow.save(commit=False)

            if line % 100 == 0:
                sys.stdout.write("\r" + "Imported %d entries..." % line)
                sys.stdout.flush()
            line = line + 1

        Rank_Elo.commit()
        Rank_Glicko.commit()
        Match1on1.commit()
        csvfile.close()
        print "\rImported %d entries." % (line - (1 if hasHeader else 0))
    except csv.Error:
        print "Error importing %s in line %d" % (args.file, line)
    except IOError:
        print "No such file: %s" % args.file
Ejemplo n.º 3
0
 def match_elo(rating):
     ratings = Rank_Elo.query().all()
     best = None
     deviation = 99999999
     for r in ratings:
         if (best is None or abs(r.value.value - rating.value.value) <
                 deviation) and r.player_id.value != rating.player_id.value:
             best = r
             deviation = abs(r.value.value - rating.value.value)
     return best
Ejemplo n.º 4
0
 def match_elo(rating):
     ratings = Rank_Elo.query().all()
     best = None
     deviation = 99999999
     for r in ratings:
         if (best is None or abs(r.value.value - rating.value.value) <
             deviation) and r.player_id.value != rating.player_id.value:
             best = r
             deviation = abs(r.value.value - rating.value.value)
     return best
Ejemplo n.º 5
0
def add_player(nickname, firstname="", lastname="", commit=False):
    """
    Adds a player and the corresponding ranks to the database. If the player
    already exsits, this function does nothing.

    :param nickname: The nickname of the player to add
    :type nickname: string
    :param firstname: The first name of the player to add
    :type firstname: string
    :param lastname: The last name of the player to add
    :type lastname: string
    :param commit: True if the rows should be committed
    :type commit: bool
    :return: Tupel (the player model, False if player already existed)
    """
    player = Player.query().get(nickname=nickname)
    created = False
    if player == None:
        created = True
        player = Player(firstname=firstname, lastname=lastname,
            nickname=nickname)
        player.save(commit)
        rank = Rank_Elo(player_id=player.player_id.value)
        rank.save(commit)
        rank = Rank_Glicko(player_id=player.player_id.value)
        rank.save(commit)

    return player, created
Ejemplo n.º 6
0
    def update_elo():
        sys.stdout.write("Query matches...")
        matches = Match1on1.query().all()
        sys.stdout.write("\rBeginning to update %d matches" % len(matches))
        print ""

        # constants
        conf = utils.get_config(args)
        k = conf["elo.chess.k"]
        func = conf["elo.chess.function"]

        # Query all ratings and store it in a dictionary. This is done to store
        # the newest rating data in memory. We do not have to commit.
        ratings = Rank_Elo.query().all()
        rdict = {}
        for r in ratings:
            rdict[r.player_id.value] = r

        updates = 0
        for match in matches:
            rating1 = rdict[match.player1.value]
            rating2 = rdict[match.player2.value]

            result = elo.elo1on1(rating1.value.value, rating2.value.value,
                                 match.outcome.value, k, func)
            rating1.value = result[0]
            rating2.value = result[1]

            updates = updates + 1
            if updates % 50 == 0:
                sys.stdout.write("\r" + "Updated %d matches..." % updates)
                sys.stdout.flush()

        # update table
        for r in ratings:
            r.save(commit=False)
        Rank_Elo.commit()
        print "\rUpdated", updates, "matches."
Ejemplo n.º 7
0
    def update_elo():
        sys.stdout.write("Query matches...")
        matches = Match1on1.query().all()
        sys.stdout.write("\rBeginning to update %d matches" % len(matches))
        print ""

        # constants
        conf = utils.get_config(args)
        k = conf["elo.chess.k"]
        func = conf["elo.chess.function"]

        # Query all ratings and store it in a dictionary. This is done to store
        # the newest rating data in memory. We do not have to commit.
        ratings = Rank_Elo.query().all()
        rdict = {}
        for r in ratings:
            rdict[r.player_id.value] = r

        updates = 0
        for match in matches:
            rating1 = rdict[match.player1.value]
            rating2 = rdict[match.player2.value]

            result = elo.elo1on1(rating1.value.value, rating2.value.value,
                match.outcome.value, k, func)
            rating1.value = result[0]
            rating2.value = result[1]

            updates = updates + 1
            if updates % 50 == 0:
                sys.stdout.write("\r" + "Updated %d matches..." % updates)
                sys.stdout.flush()

        # update table
        for r in ratings:
            r.save(commit=False)
        Rank_Elo.commit()
        print "\rUpdated", updates, "matches."
Ejemplo n.º 8
0
    def best_worst_elo():
        ranks = Rank_Elo.query().all()
        ranks = sorted(ranks, key=lambda x: x.value.value, reverse=best)

        # the table to print out
        table = [['Rank', 'Rating', 'Nick', 'Firstname', 'Lastname', 'ID']]
        #print "Rank\tRating\tNick\tForename\tSurname\tid"

        for i in range(min(args.amount, len(ranks))):
            player = Player().query().get(player_id=ranks[i].player_id.value)
            #print "%d\t%d\t%s\t%s,\t%s\t%s" % (i + 1, ranks[i].value.value,
            #    player.nickname.value, player.firstname.value,
            #    player.lastname.value, player.player_id.value)
            table.append([i + 1, ranks[i].value.value,
                player.nickname.value, player.firstname.value,
                player.lastname.value, player.player_id.value])
        utils.print_table(table)
Ejemplo n.º 9
0
    def best_worst_elo():
        ranks = Rank_Elo.query().all()
        ranks = sorted(ranks, key=lambda x: x.value.value, reverse=best)

        # the table to print out
        table = [['Rank', 'Rating', 'Nick', 'Firstname', 'Lastname', 'ID']]
        #print "Rank\tRating\tNick\tForename\tSurname\tid"

        for i in range(min(args.amount, len(ranks))):
            player = Player().query().get(player_id=ranks[i].player_id.value)
            #print "%d\t%d\t%s\t%s,\t%s\t%s" % (i + 1, ranks[i].value.value,
            #    player.nickname.value, player.firstname.value,
            #    player.lastname.value, player.player_id.value)
            table.append([
                i + 1, ranks[i].value.value, player.nickname.value,
                player.firstname.value, player.lastname.value,
                player.player_id.value
            ])
        utils.print_table(table)
Ejemplo n.º 10
0
 def rating_elo(player):
     if player is None:
         return None
     return Rank_Elo.query().get(player_id=player.player_id.value)
Ejemplo n.º 11
0
 def clear_elo():
     ranks = Rank_Elo.query().all()
     for rank in ranks:
         rank.value = 1500
         rank.save(commit=False)
     Rank_Elo.commit()
Ejemplo n.º 12
0
def predict(args):
    """
    Reads match constellations from an input file and writes the
    results to a specified output file.

    :param args: A list with arguments from the argument parser
    :type args: namespace
    """
    if os.path.abspath(args.ifile) == os.path.abspath(args.ofile):
        print "You tried to overwrite your input with your output file."
        print "Aborted."
        return

    if args.algorithm == "glicko":
        print "Not implemented yet"
        return

    try:
        modes = {True: "incremental", False: "non-incremental"}
        print "Predicting the matches in %s mode" % modes[args.incremental]
        print "Open %s and write into %s..." % (args.ifile, args.ofile)
        csvfile, reader, hasHeader = utils.get_csv(args.ifile)
        ofile = open(args.ofile, 'w')
        line = 0

        if hasHeader:
            print "\tFirst line of csv file is ignored. It seems to be a " \
                  "header row.\n"

        # constants
        conf = utils.get_config(args)
        k = conf["elo.chess.k"]
        func = conf["elo.chess.function"]

        # Query all ratings and store it in a dictionary. This is done for
        # faster access and on-the-fly calculation of new elo values
        ratings = Rank_Elo.query().all()
        rdict = {}
        for r in ratings:
            player = Player.query().get(player_id=r.player_id.value)
            rdict[player.nickname.value] = r

        for row in reader:
            if line != 0 or (line == 0 and not hasHeader):
                ratings = (rdict.get(row[1], None), rdict.get(row[2], None))
                if ratings[0] is None or ratings[1] is None:
                    continue
                value1 = ratings[0].value.value
                value2 = ratings[1].value.value

                if (value1 > value2):
                    outcome = 1
                elif (value1 < value2):
                    outcome = 0
                else:
                    outcome = 0.5

                if args.incremental:
                    result = elo.elo1on1(value1, value2, outcome, k, func)
                    ratings[0].value = result[0]
                    ratings[1].value = result[1]

                ofile.write("%s,%s,%s,%s\n" %
                            (row[0], row[1], row[2], str(outcome)))
            elif line == 0 and hasHeader:
                ofile.write('"%s","%s","%s","Statistically most possible ' \
                            'outcome"\n' % (row[0], row[1], row[2]))
            if line % 13 == 0:
                sys.stdout.write("\rWrote %d entries to the out file" % line)
                sys.stdout.flush()
            line = line + 1
        print "\rWrote %d entries to the out file" % (line -
                                                      (1 if hasHeader else 0))
        csvfile.close()
        ofile.close()

    except csv.Error:
        print "Error importing %s in line %d" % (args.ifile, line)
    except IOError:
        print "One file is missing. Either %s or %s" % (args.ifile, args.ofile)
Ejemplo n.º 13
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from pychallenge.models import Config, Match1on1, Player, Rank_Elo, Rank_Glicko

if __name__ == "__main__":
    Config.create()
    Match1on1.create()
    Player.create()
    Rank_Elo.create()
    Rank_Glicko.create()
Ejemplo n.º 14
0
 def clear_elo():
     ranks = Rank_Elo.query().all()
     for rank in ranks:
         rank.value = 1500
         rank.save(commit=False)
     Rank_Elo.commit()
Ejemplo n.º 15
0
def predict(args):
    """
    Reads match constellations from an input file and writes the
    results to a specified output file.

    :param args: A list with arguments from the argument parser
    :type args: namespace
    """
    if os.path.abspath(args.ifile) == os.path.abspath(args.ofile):
        print "You tried to overwrite your input with your output file."
        print "Aborted."
        return

    if args.algorithm == "glicko":
        print "Not implemented yet"
        return

    try:
        modes = {True: "incremental", False: "non-incremental"}
        print "Predicting the matches in %s mode" % modes[args.incremental]
        print "Open %s and write into %s..." % (args.ifile, args.ofile)
        csvfile, reader, hasHeader = utils.get_csv(args.ifile)
        ofile = open(args.ofile, 'w')
        line = 0

        if hasHeader:
            print "\tFirst line of csv file is ignored. It seems to be a " \
                  "header row.\n"

        # constants
        conf = utils.get_config(args)
        k = conf["elo.chess.k"]
        func = conf["elo.chess.function"]

        # Query all ratings and store it in a dictionary. This is done for
        # faster access and on-the-fly calculation of new elo values
        ratings = Rank_Elo.query().all()
        rdict = {}
        for r in ratings:
            player = Player.query().get(player_id=r.player_id.value)
            rdict[player.nickname.value] = r

        for row in reader:
            if line != 0 or (line == 0 and not hasHeader):
                ratings = (rdict.get(row[1], None), rdict.get(row[2], None))
                if ratings[0] is None or ratings[1] is None:
                    continue
                value1 = ratings[0].value.value
                value2 = ratings[1].value.value

                if (value1 > value2):
                    outcome = 1
                elif (value1 < value2):
                    outcome = 0
                else:
                    outcome = 0.5

                if args.incremental:
                    result = elo.elo1on1(value1, value2, outcome, k, func)
                    ratings[0].value = result[0]
                    ratings[1].value = result[1]

                ofile.write("%s,%s,%s,%s\n" % (row[0], row[1], row[2],
                    str(outcome)))
            elif line == 0 and hasHeader:
                ofile.write('"%s","%s","%s","Statistically most possible ' \
                            'outcome"\n' % (row[0], row[1], row[2]))
            if line % 13 == 0:
                sys.stdout.write("\rWrote %d entries to the out file" % line)
                sys.stdout.flush()
            line = line + 1
        print "\rWrote %d entries to the out file" % (
            line - (1 if hasHeader else 0))
        csvfile.close()
        ofile.close()

    except csv.Error:
        print "Error importing %s in line %d" % (args.ifile, line)
    except IOError:
        print "One file is missing. Either %s or %s" % (args.ifile, args.ofile)