Пример #1
0
    def __setPlayers(self):

        for match in self.matches:

            p1name = match.player1name
            p2name = match.player2name
            p1score = match.player1score
            p2score = match.player2score

            # Add all players to dictionary as unrated Glicko2 player objects
            if p1name not in self.players:
                self.players[p1name] = glicko2.Player()
            if p2name not in self.players:
                self.players[p2name] = glicko2.Player()

            # Update both players ratings and rd's
            # There are no ties in matches
            self.players[p1name].update_player(
                [self.players[p2name].getRating()],
                [self.players[p2name].getRd()], [p1score > p2score])
            self.players[p2name].update_player(
                [self.players[p1name].getRating()],
                [self.players[p1name].getRd()], [p1score < p2score])

            # Update the rating deviation of all other players
            for playerName in self.players:
                if playerName != p1name and playerName != p2name:
                    self.players[playerName].did_not_compete()
Пример #2
0
 def setUp(self):
     # Feb222012 example.
     self.P1 = glicko2.Player()
     self.P1.setRd(200)
     self.P1.update_player([1400, 1550, 1700], [30, 100, 300], [1, 0, 0])
     # Original Ryan example.
     self.Ryan = glicko2.Player()
     self.Ryan.update_player([1400, 1550, 1700], [30, 100, 300], [1, 0, 0])
Пример #3
0
 def __init__(self, name, season, team):
     self.name = name
     self.aliases = set()
     self.wins = 0
     self.rating = 1000
     self.glicko = glicko2.Player()
     # long term glicko rating
     self.glicko_longterm = glicko2.Player()
     self.trueskill = trueskill.Rating()
     self.peak_rating = 1000
     self.games = []
     self.teams = {season: team}
     self.zeroNumber = sys.maxsize
Пример #4
0
def update_ratings(game, white_score, black_score):
    """Update the ratings for both players after a game.  Return a
    Deferrred."""
    wp = glicko2.Player(game.white_rating.glicko2_rating(),
        game.white_rating.glicko2_rd(), game.white_rating.volatility,
        game.white_rating.ltime)
    wp.update_player([game.black_rating.glicko2_rating()],
        [game.black_rating.glicko2_rd()], [white_score])

    bp = glicko2.Player(game.black_rating.glicko2_rating(),
        game.black_rating.glicko2_rd(), game.black_rating.volatility,
        game.black_rating.ltime)
    bp.update_player([game.white_rating.glicko2_rating()],
        [game.white_rating.glicko2_rd()], [black_score])

    white_win = game.white_rating.win
    white_loss = game.white_rating.loss
    white_draw = game.white_rating.draw
    black_win = game.black_rating.win
    black_loss = game.black_rating.loss
    black_draw = game.black_rating.draw
    assert(black_score + white_score == 1.0)
    if white_score == 0.0:
        white_loss += 1
        black_win += 1
    elif white_score == 0.5:
        white_draw += 1
        black_draw += 1
    elif white_score == 1.0:
        white_win += 1
        black_loss += 1
    else:
        raise RuntimeError('rating.update_ratings(): unexpected score')

    white_rating = wp.get_glicko_rating()
    white_rd = wp.get_glicko_rd()
    black_rating = bp.get_glicko_rating()
    black_rd = bp.get_glicko_rd()

    ltime = datetime.datetime.utcnow()

    d1 = game.white.set_rating(game.speed_variant,
        white_rating, white_rd, wp.vol,
        white_win, white_loss, white_draw, ltime)
    d2 = game.black.set_rating(game.speed_variant,
        black_rating, black_rd, bp.vol,
        black_win, black_loss, black_draw, ltime)
    return defer.DeferredList([d1, d2])
Пример #5
0
def show_ratings(user, conn):
    rows = db.user_get_ratings(user.id)
    if not rows:
        conn.write(_('%s has not played any rated games.\n\n') % user.name)
    else:
        conn.write(
            _('speed & variant         rating  RD    Volat.    total  best\n'))
        for row in rows:
            ent = {}
            ent['speed_variant'] = str(
                speed_variant.from_ids(row['speed_id'], row['variant_id']))
            r = Rating(row['rating'], row['rd'], row['volatility'],
                       row['ltime'], row['win'], row['loss'], row['draw'])
            p = glicko2.Player(r.glicko2_rating(), r.glicko2_rd(),
                               r.volatility, r.ltime)
            ent['rating'] = p.get_glicko_rating()
            ent['rd'] = p.get_glicko_rd()
            ent['volatility'] = r.volatility
            if row['best'] is None:
                ent['best_str'] = ''
            else:
                ent['best_str'] = '%4d %10s' % (row['best'], row['when_best'])
            ent['total'] = row['total']
            conn.write(
                '%(speed_variant)-24s %(rating)-6d %(rd)-3.0f %(volatility)9.6f %(total)7d %(best_str)s\n'
                % ent)
        conn.write('\n')
Пример #6
0
	def preparePlayerInfo(self, playerList):

		tournamentBonus = 0
		totalPlayer = self.tournament.getTotalPlayer()
		bonusRate = math.log(totalPlayer, 8) ** 0.5

		self.rankingSpread = []

		for player in playerList:
			if not (player["id"] in self.playerDictionary):
				self.playerDictionary[player["id"]] = glicko2.Player()
				self.getPlayer(player["id"]).setInfo(player["gamerTag"], player["id"])
			self.getPlayer(player["id"]).resetResult()
			if self.rankingSpread == [] or (self.rankingSpread != [] and player["standing"] != self.rankingSpread[-1]):
				self.rankingSpread.append(player["standing"])

			tournamentBonus += self.playerDictionary[player["id"]].getPlayerWeight()
			# tournamentBonus += 1

		bonusLine = self.getBonusLine(totalPlayer / 4)

		# counting bonus

		avgPlayerCount = math.floor(totalPlayer * 0.6) 

		for player in playerList:
			standing = player["standing"]
			if (standing == -1): 
				continue
			rankingRate = self.a / self.getLevelRanking(standing) + max(0, self.b * (avgPlayerCount - standing) / 2 / avgPlayerCount)
			self.getPlayer(player["id"]).bonusRating(tournamentBonus * bonusRate * rankingRate - self.getPlayer(player["id"]).getPlayerWeight())
			if (player["gamerTag"] == "eric42"):
				print (player["gamerTag"], ' BONUS: ', tournamentBonus * bonusRate * rankingRate - self.getPlayer(player["id"]).getPlayerWeight())
Пример #7
0
def show_ratings(user, conn, variants):
    out = []
    rows = yield db.user_get_ratings_for_finger(user.id_)

    if not rows:
        out.append(_('%s has not played any rated games.\n\n') % user.name)
    else:
        out.append(_('speed & variant         rating  RD    Volat.    total  best\n'))
        for row in rows:
            sv = speed_variant.from_ids(row['speed_id'], row['variant_id'])
            if variants and sv.variant not in variants:
                continue
            ent = {}
            ent['speed_variant'] = str(sv)
            r = Rating(row['rating'], row['rd'],
                row['volatility'], row['ltime'], row['win'], row['loss'],
                row['draw'])
            p = glicko2.Player(r.glicko2_rating(), r.glicko2_rd(),
                r.volatility, r.ltime)
            ent['rating'] = p.get_glicko_rating()
            ent['rd'] = p.get_glicko_rd()
            ent['volatility'] = r.volatility
            if row['best'] is None:
                ent['best_str'] = ''
            else:
                ent['best_str'] = '%4d %10s' % (row['best'], row['when_best'])
            ent['total'] = row['total']
            out.append('%(speed_variant)-24s %(rating)-6d %(rd)-3.0f %(volatility)9.6f %(total)7d %(best_str)s\n' % ent)
        out.append('\n')

    defer.returnValue(out)
def exampleCase():

    P1 = glicko2.Player()
    P2 = glicko2.Player()

    P1_R = input("P1 rating:")
    P1_D = input("P1 dev: ")
    P1_V = input("P1 vola: ")

    P2_R = input("P2 rating:")
    P2_D = input("P2 dev:")
    P2_V = input("P2 vola: ")

    winner = input("Who won? P1 or P2? :: ")

    if winner == 1:
        a = 1
        b = 0
    else:
        a = 0
        b = 1

    P1 = glicko2.Player(P1_R, P1_D, P1_V)
    P2 = glicko2.Player(P2_R, P2_D, P1_V)

    P1c = P1

    # Following the example at:
    # http://math.bu.edu/people/mg/glicko/glicko2.doc/example.html
    # Pretend Ryan (of rating 1500 and rating deviation 350)
    # plays players of ratings 1400, 1550 and 1700
    # and rating deviations 30, 100 and 300 respectively
    # with outcomes 1, 0 and 0.

    P1.update_player([x for x in [P2.rating]], [x for x in [P2.rd]], [a])

    print("P1 New Rating: " + str(P1.rating))
    print("P1 New Dev: " + str(P1.rd))
    print("P1 New Vol: " + str(P1.vol))

    P2.update_player([x for x in [P1c.rating]], [x for x in [P1c.rd]], [b])

    print("P2 New Rating: " + str(P2.rating))
    print("P2 New Dev: " + str(P2.rd))
    print("P2 New Vol: " + str(P2.vol))
Пример #9
0
def update_after_game(ratings_list, rds_list, T1_won):
    ratings_G = np.array(ratings_list)
    rds_G = np.array(rds_list)
    T_G = int(len(ratings_list) / 2)
    m = 60.24
    vol_4 = 0.2375
    vol_2 = 0.1195
    vol_1 = 0.06
    if T_G == 4:
        vol_p = vol_4
    elif T_G == 2:
        vol_p = vol_2
    else:
        vol_p = vol_1
    ratings_T1 = ratings_G[:T_G]
    ratings_T2 = ratings_G[T_G:]

    r_T1 = np.prod(np.power(ratings_T1, 1 / T_G))
    r_T2 = np.prod(np.power(ratings_T2, 1 / T_G))

    delta_o = (r_T1 - r_T2)

    rds_T1 = rds_G[:T_G]
    rds_T2 = rds_G[T_G:]
    rd_T1 = np.sqrt(np.sum(np.power(rds_T1, 2)))
    rd_T2 = np.sqrt(np.sum(np.power(rds_T2, 2)))

    T1 = glicko2.Player(vol=vol_p)
    T1.setRd(rd_T1)
    T1.setRating(r_T1)

    T2 = glicko2.Player(vol=vol_p)
    T2.setRd(rd_T2)
    T2.setRating(r_T1 - delta_o * T_G)

    T1.update_player([r_T1 - delta_o * T_G], [rd_T2], [T1_won])
    T2.update_player([r_T1], [rd_T1], [1 - T1_won])

    delta_u = 1 / T_G * (T1.getRating() - T2.getRating())
    xi_1 = T1.getRd() / rd_T1
    xi_2 = T2.getRd() / rd_T2
    rds_G_u = update_RD(rds_G, m, xi_1, xi_2)
    ratings_G_u = update_ratings(ratings_G, rds_G, delta_u)
    return UpdateMmrResponseBody(ratings_list=ratings_G_u.tolist(), rds_list=rds_G_u.tolist())
Пример #10
0
def update_ratings(game, white_score, black_score):
    wp = glicko2.Player(game.white_rating.glicko2_rating(),
                        game.white_rating.glicko2_rd(),
                        game.white_rating.volatility, game.white_rating.ltime)
    wp.update_player([game.black_rating.glicko2_rating()],
                     [game.black_rating.glicko2_rd()], [white_score])

    bp = glicko2.Player(game.black_rating.glicko2_rating(),
                        game.black_rating.glicko2_rd(),
                        game.black_rating.volatility, game.black_rating.ltime)
    bp.update_player([game.white_rating.glicko2_rating()],
                     [game.white_rating.glicko2_rd()], [black_score])

    white_win = game.white_rating.win
    white_loss = game.white_rating.loss
    white_draw = game.white_rating.draw
    black_win = game.black_rating.win
    black_loss = game.black_rating.loss
    black_draw = game.black_rating.draw
    assert (black_score + white_score == 1.0)
    if white_score == 0.0:
        white_loss += 1
        black_win += 1
    elif white_score == 0.5:
        white_draw += 1
        black_draw += 1
    elif white_score == 1.0:
        white_win += 1
        black_loss += 1
    else:
        raise RuntimeError('rating.update_ratings(): unexpected score')

    white_rating = wp.get_glicko_rating()
    white_rd = wp.get_glicko_rd()
    black_rating = bp.get_glicko_rating()
    black_rd = bp.get_glicko_rd()

    ltime = datetime.datetime.utcnow()

    game.white.set_rating(game.speed_variant, white_rating, white_rd, wp.vol,
                          white_win, white_loss, white_draw, ltime)
    game.black.set_rating(game.speed_variant, black_rating, black_rd, bp.vol,
                          black_win, black_loss, black_draw, ltime)
Пример #11
0
def exampleCase():
    # Create a player called Ryan
    Ryan = glicko2.Player("Ryan")
    p1 = glicko2.Player("p1")
    p1.rating = 1300
    p1.rd = 50
    p2 = glicko2.Player("p2")
    p2.rating = 2000
    p2.rd = 500
    p3 = glicko2.Player("p3")
    p3.rating = 1900
    p3.rd = 300
    Ryan.addMatch(p1, 0)
    Ryan.addMatch(p2, 1)
    Ryan.addMatch(p2, 0)
    Ryan.addMatch(p3, 0)

    # Following the example at:
    # http://math.bu.edu/people/mg/glicko/glicko2.doc/example.html
    # Pretend Ryan (of rating 1500 and rating deviation 350)
    # plays players of ratings 1400, 1550 and 1700
    # and rating deviations 30, 100 and 300 respectively
    # with outcomes 1, 0 and 0.
    print("Old Rating: " + str(Ryan.rating))
    print("Old Rating Deviation: " + str(Ryan.rd))
    print("Old Volatility: " + str(Ryan.vol))
    Ryan.update_player()
    print("New Rating: " + str(Ryan.rating))
    print("New Rating Deviation: " + str(Ryan.rd))
    print("New Volatility: " + str(Ryan.vol))
    # Ryan.addMatch(p2, 1)
    Ryan.update_player()
    Ryan.did_not_compete()
    print("New Rating: " + str(Ryan.rating))
    print("New Rating Deviation: " + str(Ryan.rd))
    print("New Volatility: " + str(Ryan.vol))
Пример #12
0
def exampleCase():
    # Create a player called Ryan
    Ryan = glicko2.Player()
    # Following the example at:
    # http://math.bu.edu/people/mg/glicko/glicko2.doc/example.html
    # Pretend Ryan (of rating 1500 and rating deviation 350)
    # plays players of ratings 1400, 1550 and 1700
    # and rating deviations 30, 100 and 300 respectively
    # with outcomes 1, 0 and 0.
    #sprint "Old Rating: " + str(Ryan.rating)
    print("Old Rating Deviation: " + str(Ryan.rd))
    print("Old Volatility: " + str(Ryan.vol))
    Ryan.update_player([x for x in [1400, 1550, 1700]],
        [x for x in [30, 100, 300]], [1, 0, 0])
    print("New Rating: " + str(Ryan.rating))
    print("New Rating Deviation: " + str(Ryan.rd))
    print("New Volatility: " + str(Ryan.vol))
Пример #13
0
    def rate(self, winners, losers, draw=False):
        score_w = 0.5 if draw else 1
        score_l = 0.5 if draw else 0
        print("Scores:")
        print(score_l, score_w)

        avg_w = [
            [int(sum((p['rating']
                      for p in winners)) / len(winners))],  # average rating
            [int(sum((p['deviation']
                      for p in winners)) / len(winners))],  # average deviation
            [score_l]
        ]
        avg_l = [
            [int(sum((p['rating']
                      for p in losers)) / len(losers))],  # average rating
            [int(sum((p['deviation']
                      for p in losers)) / len(losers))],  # average deviation
            [score_w]
        ]

        po = glicko2.Player()
        results = []
        for p in winners:
            po.setRating(p['rating'])
            po.setRd(p['deviation'])
            po.update_player(*avg_l)
            new = self._scale_changes(p,
                                      po.getRating() - p['rating'],
                                      po.getRd() - p['deviation'])
            results.append(new)

        for p in losers:
            po.setRating(p['rating'])
            po.setRd(p['deviation'])
            po.update_player(*avg_w)
            new = self._scale_changes(p,
                                      po.getRating() - p['rating'],
                                      po.getRd() - p['deviation'])
            results.append(new)

        return results
Пример #14
0
def update_glicko():

    event = json_data["event"]
    person_list = json_data["event"]["participation"]["person"]

    players_dci = []
    players_ratings = []

    players_newrating = []

    for player in db_fetch_players():
        players_dci.append(player[0])
        players_info = (player[1], player[2], player[3])
        players_ratings.append(players_info)

    players = dict(zip(players_dci, players_ratings))

    current_players = []

    for player in person_list:
        current_players.append(int(player["@id"]))

    # print(players)
    # print(current_players)

    # TO DO: Fetch players match data (outcome, player 1, player 2 and opponents rating, rd and vol)

    matches = []

    for round in db_fetch_rounds(str(event["@eventguid"])):
        for match in db_fetch_matches(round[0]):
            matches.append(match)

    # print(matches)

    for player in players:

        # print(f"{player} se začne")
        hasplayed = [ None for match in matches if player in match ]

        temp_player = glicko2.Player(
            rating = players.get(player)[0],
            rd = players.get(player)[1],
            vol = players.get(player)[2]
        )

        if not hasplayed:
            # print(f"Player {player} hasn't played in the current tournament")
            # print("Old Rating: " + str(players.get(player)[0]))
            # print("Old Rating Deviation: " + str(players.get(player)[1]))
            # print("Old Volatility: " + str(players.get(player)[2]))
            temp_player.did_not_compete()
            newrating = (temp_player.rating, temp_player.rd, temp_player.vol)
            players_newrating.append(newrating)
            # print("New Rating: " + str(temp_player.rating))
            # print("New Rating Deviation: " + str(temp_player.rd))
            # print("New Volatility: " + str(temp_player.vol))
        else:

            if player in current_players:

                opponents_rating = []
                opponents_rd = []
                outcomes = []

                # print(f"Player {player} has played in the current tournament")
                # print("Old Rating: " + str(players.get(player)[0]))
                # print("Old Rating Deviation: " + str(players.get(player)[1]))
                # print("Old Volatility: " + str(players.get(player)[2]))

                for match in matches:
                    if match[1] == None:
                        continue
                    elif match[0] == player:
                        if match[5] == 2:
                            # print("Draw "+str(match))
                            opponents_rating.append(players[match[1]][0])
                            opponents_rd.append(players[match[1]][1])
                            outcomes.append(int(0.5))
                        else:
                            # print("Win "+str(match))
                            opponents_rating.append(players[match[1]][0])
                            opponents_rd.append(players[match[1]][1])
                            outcomes.append(int(1))
                    elif match[1] == player:
                        if match[5] == 2:
                            # print("Draw "+str(match))
                            opponents_rating.append(players[match[0]][0])
                            opponents_rd.append(players[match[0]][1])
                            outcomes.append(int(0.5))
                        else:
                            # print("Loss "+str(match))
                            opponents_rating.append(players[match[0]][0])
                            opponents_rd.append(players[match[0]][1])
                            outcomes.append(int(0))


                temp_player.update_player([x for x in opponents_rating],
                    [x for x in opponents_rd], outcomes)
                newrating = (temp_player.rating, temp_player.rd, temp_player.vol)
                players_newrating.append(newrating)
                # print("New Rating: " + str(temp_player.rating))
                # print("New Rating Deviation: " + str(temp_player.rd))
                # print("New Volatility: " + str(temp_player.vol))


        # print(f"{player} se konča")



    newplayers = dict(zip(players_dci, players_newrating))

    # print(players_newrating)

    for player in newplayers:
        db_update_glicko(
            int(player),
            str(newplayers.get(player)[0]),
            str(newplayers.get(player)[1]),
            str(newplayers.get(player)[2])
        )
Пример #15
0
                return (teams)
        # stage playoffs
        teams, current_week = eval_matchlist(stage['matches'][-7:], teams)
        if current_week:
            return (teams)
    return (teams)


# create teams dict
teams_resp = requests.get(TEAMSURL)
teams_data = teams_resp.json()
teams = dict()
for competitor in teams_data['competitors']:
    name = competitor['competitor']['name']
    teams[name] = {
        'glicko2': glicko2.Player(),
        'last_matches':
        ([], [], []),  # opponent's rating, opponent's rd, win/loss
        'rating_hist': [
            1500,
        ],
        'rd_hist': [
            350,
        ],
        'color': '#' + competitor['competitor']['primaryColor']
    }
# import match data
resp = requests.get(SCHEDULEURL)
data = resp.json()
data = data['data']
# evaluate all played matches of season 2 so far
Пример #16
0
	def __setChallongeMatches(self, tournamentId):
		
		APIkey = "2tyMsGrcQanAq3EQeMytrsGrdMMFutDDz0BxNAAh"
		tournamentsURL = "https://*****:*****@api.challonge.com/v1/tournaments/"
		
		# Create cursor to execute queries
		cur = self.db.cursor()

		# Construct list of Match objects from all tournaments


		#
		#
		#
		# Don't do it if you already have the tournament in the database ugh
		#
		#

		# Add the tournament to the database
		tournament_name = ''

		if('-' in tournamentId):
			tournament_name = tournamentId.split('-')[1].lower()
			q = (0, tournament_name, stripNum(tournament_name), 'Ann Arbor')	
			cur.execute("INSERT INTO tournaments (id, name, series, location, date) VALUES (%s, %s, %s, %s, default);", q)
		else:
			tournament_name = tournamentId
			q = (0, tournamentId, stripNum(tournamentId), 'Ann Arbor')	
			cur.execute("INSERT INTO tournaments (id, name, series, location, date) VALUES (%s, %s, %s, %s, default);", q)


		# A tournament participant is object w/ player id for this tournament
		participantsInTournament = requests.get(tournamentsURL + tournamentId + "/participants.json").json()

		# Maps player Ids to player names
		IdToPlayerName = {}
		partSize = 0
		# Compile id:name map

		cur.execute("SELECT id FROM tournaments WHERE name = %s;", [tournament_name])
		tournament_id = cur.fetchone()[0]
		for p in participantsInTournament:
			# Get playername
			partSize += 1
			playerName = p["participant"]["display_name"]
			playerName = playerName.lower()
			playerName = playerName.replace(" ", "")
			playerName = playerName.replace("\t", "")
			playerName = playerName.replace("(unpaid)", "")


			if ('|') in playerName:
				playerName = playerName.split('|')[-1]

			re.sub(r"[^\\x00-\\x7f]", "", playerName)
			playerName.replace(u"\u2122", '')
			#print playerName
			# Add to map
			IdToPlayerName[p["participant"]["id"]] = playerName



			cur.execute("SELECT id FROM players WHERE tag = %s;", [playerName])
			p1_id = cur.fetchone()

			if not p1_id:
				self.players[playerName] = glicko2.Player()
				p1 = (0, playerName)	
				cur.execute("INSERT INTO players (id, tag, sponsor, skill) VALUES (%s, %s, null, default);", p1)
							

			cur.execute("SELECT id FROM players WHERE tag = %s;", [playerName])
			player_id = cur.fetchone()[0]
			

			cur.execute("INSERT INTO attended (id, player_id, tournament_id) VALUES (%s, %s, %s);", [0, player_id, tournament_id])
			self.db.commit()
		self.bracket_size = partSize	
		# Dictionary from int index to json match objects
		jsonMatchesDict = requests.get(tournamentsURL + tournamentId + "/matches.json").json()
		
		# Turn the dict into a list
		jsonMatches = []
		for i in range(0, len(jsonMatchesDict)):
			jsonMatches.append(jsonMatchesDict[i]["match"])
		
		# Scores must be of the format ">-<"
		scoreFormat = re.compile("\d+-\d+")
		
		# Compile the list of Match objects
		for jsonMatch in jsonMatches:

			# Some scores are not of the right format, so skip these
			scoreStr = jsonMatch["scores_csv"]
			if not scoreFormat.match(scoreStr):
				return
			
			# Extract scores
			separatorIndex = scoreStr.index("-")
			player1score = int(scoreStr[:separatorIndex])
			player2score = int(scoreStr[separatorIndex+1:])
			
			# Extract names
			player1name = IdToPlayerName[jsonMatch["player1_id"]].lower()
			player2name = IdToPlayerName[jsonMatch["player2_id"]].lower()


			# Add all players to dictionary as unrated Glicko2 player objects, as well as the database

			
			newMatch = Match(player1name, player1score, player2name, player2score)
			self.matches.append(newMatch)

		

			# Use all the SQL you like


		# print all the first cell of all the rows
		self.db.commit()
		cur.close()
Пример #17
0
	def __setSmashGGMatches(self, url):
		cur = self.db.cursor()
			#Smash.gg wrapper
		smash = pysmash.SmashGG()

		# Get tournament name

		tournament_name = url.split("/tournament/")[1].split("/")[0]


		#
		#
		# Ann Arbor should be replaced by region use tourney information to find venue address and get State from there. 
		#
		#
		p = (0, tournament_name, stripNum(tournament_name), 'Ann Arbor')	
		cur.execute("INSERT INTO tournaments (id, name, series, location, date) VALUES (%s, %s, %s, %s, default);", p)

		players = smash.tournament_show_players(tournament_name, 'melee-singles')


		# Add all players to database if they're not in there already
		for player in players:

			# Santitize tag of fuckery
			tag = player['tag'].lower()
			tag = tag.replace(" ", "")
			re.sub(r"[^\\x00-\\x7f]", "", tag)
			tag.replace(u"\u2122", '')
			#tag = str(tag.encode('ascii', 'replace'))
			cur.execute("SELECT * FROM players WHERE tag = %s;", [tag])
			result = cur.fetchone()

			# Add player to database
			if not result:	
				self.players[tag] = glicko2.Player()
				p = (0, tag, player['entrant_id'])	
				cur.execute("INSERT INTO players (id, tag, sponsor, smashgg_id, skill) VALUES (%s, %s, null, %s, default);", p)				
			else:
				p = (player['entrant_id'], tag)
				cur.execute("UPDATE players SET smashgg_id = %s WHERE tag = %s;", p)

			self.db.commit()
			cur.execute("SELECT id FROM players WHERE tag = %s;", [tag])
			player_id = cur.fetchone()[0]
			cur.execute("SELECT id FROM tournaments WHERE name = %s;", [tournament_name])
			tournament_id = cur.fetchone()[0]

			cur.execute("INSERT INTO attended (id, player_id, tournament_id) VALUES (%s, %s, %s);", [0, player_id, tournament_id])
		self.db.commit()

		# Split this into another function 
		sets = smash.tournament_show_sets(tournament_name, 'melee-singles')

		for match in sets:
			entrant1Id = match['entrant_1_id']
			entrant2Id = match['entrant_2_id']
			winner_id = match['winner_id']
			loser_id = match['loser_id']
			entrant1_tag = ''
			entrant2_tag = ''
			winner_tag = ''
			loser_tag = ''
			winner_set_count = 0
			loser_set_count = 0
			entrant1Score = match['entrant_1_score']
			entrant2Score = match['entrant_2_score']
			cur.execute("SELECT tag FROM players WHERE smashgg_id = %s;", [entrant1Id])
			entrant1_tag = cur.fetchone()[0]
			cur.execute("SELECT tag FROM players WHERE smashgg_id = %s;", [entrant2Id])
			entrant2_tag = cur.fetchone()[0]
	
			if entrant1_tag and entrant2_tag:
				entrant1_tag = entrant1_tag.lower()
				entrant1_tag = entrant1_tag.replace(" ", "")
				entrant2_tag = entrant2_tag.lower()
				entrant2_tag = entrant2_tag.replace(" ", "")
				newMatch = Match(entrant1_tag, entrant1Score, entrant2_tag, entrant2Score)
				self.matches.append(newMatch)
		
		self.db.commit()
		cur.close()

		return len(players)
Пример #18
0
out = '/output'

list_dir = os.listdir(os.getcwd() + out)

list_score = {}
for path in list_dir:
    score = pd.read_csv(os.getcwd() + out + '/' + path + '/' +
                        'score_total.csv',
                        index_col=0)
    list_score[path] = score.to_dict()['Score']

names = list(list_score[path].keys())
clf_player = {}
import glicko2
for i in names:
    clf_player[i] = glicko2.Player()

old_rating = {}
old_rd = {}
c_score = {}
rating_matriz = {}
for i in clf_player:
    rating_matriz[i] = []

for dataset in list_dir:
    for x in clf_player:
        old_rating[x] = clf_player[x].rating
        old_rd[x] = clf_player[x].rd
        c_score[x] = list_score[dataset][x]

    for clf in names: