Example #1
0
def newRating(mu=None, sigma=None):
    if mu and sigma:
        return trueskill.Rating(mu=mu, sigma=sigma)
    elif mu:
        return trueskill.Rating(mu=mu, sigma=env.sigma)
    else:
        return env.create_rating()
Example #2
0
def make_matchups(workers_to_match, project_group_id, review_project,
                  inter_task_review, match_group_id, batch_id):
    matched_workers = []
    for index in xrange(0, len(workers_to_match)):
        if workers_to_match[index] not in matched_workers:
            if len(workers_to_match) - len(matched_workers) == 1:
                is_last_worker = True
                start = 0
            else:
                is_last_worker = False
                start = index + 1
            first_worker = workers_to_match[index]
            first_score = trueskill.Rating(mu=first_worker['score'].mu,
                                           sigma=first_worker['score'].sigma)
            best_quality = 0
            second_worker = None
            is_intertask_match = None
            for j in xrange(start, len(workers_to_match)):
                if is_last_worker or workers_to_match[j] not in matched_workers:
                    second_score = trueskill.Rating(
                        mu=workers_to_match[j]['score'].mu,
                        sigma=workers_to_match[j]['score'].sigma)
                    quality = trueskill.quality_1vs1(first_score, second_score)
                    if quality > best_quality:
                        is_intertask_match = False
                        best_quality = quality
                        second_worker = workers_to_match[j]

            if second_worker is not None:
                matched_workers.append(first_worker)
                if not is_intertask_match:
                    matched_workers.append(second_worker)
                create_review_task(first_worker, second_worker, review_project,
                                   match_group_id, batch_id)
Example #3
0
def evaluate_game(game: Game) -> float:
    """
    Returns the expected win probability of the blue team over the red team
    """

    blue_team_ratings = [
        trueskill.Rating(mu=p.trueskill_mu, sigma=p.trueskill_sigma)
        for p in game.teams.BLUE
    ]
    red_team_ratings = [
        trueskill.Rating(mu=p.trueskill_mu, sigma=p.trueskill_sigma)
        for p in game.teams.RED
    ]

    delta_mu = sum(r.mu
                   for r in blue_team_ratings) - sum(r.mu
                                                     for r in red_team_ratings)

    sum_sigma = sum(
        r.sigma**2
        for r in itertools.chain(blue_team_ratings, red_team_ratings))

    size = len(blue_team_ratings) + len(red_team_ratings)

    denominator = math.sqrt(size * (trueskill.BETA * trueskill.BETA) +
                            sum_sigma)

    ts = trueskill.global_env()

    return ts.cdf(delta_mu / denominator)
Example #4
0
def update_trueskill(game: Game, session):
    """
    Updates the player’s rating based on the game’s result
    """
    blue_team_ratings = {
        participant.player.ratings[participant.role]:
        trueskill.Rating(mu=participant.trueskill_mu,
                         sigma=participant.trueskill_sigma)
        for participant in game.teams.BLUE
    }

    red_team_ratings = {
        participant.player.ratings[participant.role]:
        trueskill.Rating(mu=participant.trueskill_mu,
                         sigma=participant.trueskill_sigma)
        for participant in game.teams.RED
    }

    if game.winner == "BLUE":
        new_ratings = trueskill.rate([blue_team_ratings, red_team_ratings])
    else:
        new_ratings = trueskill.rate([red_team_ratings, blue_team_ratings])

    for ratings in new_ratings:
        for player_rating in ratings:
            # This is the PlayerRating object
            player_rating.trueskill_mu = ratings[player_rating].mu
            player_rating.trueskill_sigma = ratings[player_rating].sigma

            session.merge(player_rating)
Example #5
0
    def setUp(self):
        self.player_1_id = ObjectId()
        self.player_1_name = 'gaR'
        self.player_1_aliases = ['gar', 'garr', 'garpr']
        self.player_1_rating = {
                'norcal': TrueskillRating(), 
                'texas': TrueskillRating(trueskill_rating=trueskill.Rating(mu=10, sigma=1))
        }
        self.player_1_regions = ['norcal', 'texas']

        self.player_2_id = ObjectId()
        self.player_2_name = 'MIOM | SFAT'
        self.player_2_aliases = ['miom | sfat', 'sfat', 'miom|sfat']
        self.player_2_rating = {'norcal': TrueskillRating(trueskill_rating=trueskill.Rating(mu=30, sigma=2))}
        self.player_2_regions = ['norcal', 'socal']

        self.player_1 = Player(self.player_1_name, self.player_1_aliases, self.player_1_rating, self.player_1_regions, id=self.player_1_id)
        self.player_1_missing_id = Player(self.player_1_name, self.player_1_aliases, self.player_1_rating, self.player_1_regions)
        self.player_2 = Player(self.player_2_name, self.player_2_aliases, self.player_2_rating, self.player_2_regions, id=self.player_2_id)
        
        self.player_1_json_dict = {
                '_id': self.player_1_id,
                'name': self.player_1_name,
                'aliases': self.player_1_aliases,
                'ratings': {region: rating.get_json_dict() for region, rating in self.player_1_rating.iteritems()},
                'regions': self.player_1_regions
        }

        self.player_1_json_dict_missing_id = {
                'name': self.player_1_name,
                'aliases': self.player_1_aliases,
                'ratings': {region: rating.get_json_dict() for region, rating in self.player_1_rating.iteritems()},
                'regions': self.player_1_regions
        }
Example #6
0
def cal_TrueSkill_demo(args):
    data, params, big_zero = args[0], args[1], args[2]
    user = defaultdict(ts.Rating)
    goal = defaultdict(ts.Rating)
    for i in data.iterrows():
        rows = i[1]
        user[rows['uid']] = ts.Rating(rows['u_player'], 3.0)
        goal[rows['gid']] = ts.Rating(rows['g_player'], 3.0)

    for i in data.iterrows():
        idx = i[0]
        item = i[1]
        # 对每一条迭代进来的记录,分别初始化uid和pid的能力值,然后用上式计算。
        u_player = user[item['uid']]
        g_player = goal[item['gid']]

        # 核心句,计算一次做题提交之后,trueskill的变化。根据user做题的对错情况,决定这个delta数值是正还是负。
        data.loc[idx, 'ts_pts'] = (g_player.mu / u_player.mu) * norm_duration(
            item, idx, u_player, g_player, data, params, big_zero)
        # 记录即时的goal与user值,是为了后面计算compensate
        data.loc[idx, 'temp_g'] = g_player.mu
        data.loc[idx, 'temp_u'] = u_player.mu

        if item['corr']:
            u_player, g_player = ts.rate_1vs1(u_player, g_player)
        else:
            g_player, u_player = ts.rate_1vs1(g_player, u_player)

        user[item['uid']] = u_player
        goal[item['gid']] = g_player
    return user, goal, data
Example #7
0
def get_skill(userid, guildid):
    '''
    Returns the TrueSkill rating of a discord user.
    Will initialize skill if none is found.
    :param userid: Discord userid to find
    :return: stored TrueSkill rating object of userid
    '''
    userid = str(userid)
    guildid = str(guildid)

    # check cache first
    if guildid not in ratings_cache:
        ratings_cache[guildid] = {}
    if userid in ratings_cache[guildid]:
        return ratings_cache[guildid][userid]

    print(f'Cache Miss: guildid = {guildid} userid = {userid}')

    with shelve.open(str(guildid), writeback=True) as db:
        if 'ratings' not in db:
            db['ratings'] = {}
        ratings = db['ratings']
        if userid in ratings:
            mu, sigma = ratings[userid]
            return ts.Rating(float(mu), float(sigma))
        new_rating = ts.Rating()
        ratings_cache[guildid][userid] = new_rating
        ratings[userid] = new_rating.mu, new_rating.sigma
        db['ratings'][userid] = new_rating.mu, new_rating.sigma
        return new_rating
Example #8
0
def add_game(session, winner_id, loser_id, submitted_by_id):
    if winner_id == loser_id:
        raise Exception("can't play yourself")

    winner = session.query(User).get(winner_id)
    loser = session.query(User).get(loser_id)
    submitted_by = session.query(User).get(submitted_by_id)

    winner_rating, loser_rating = trueskill.rate_1vs1(
        trueskill.Rating(winner.elo), trueskill.Rating(loser.elo))
    winner_elo, loser_elo = winner_rating.mu, loser_rating.mu

    # verify created at

    new_game = Game(
        winner=winner,
        loser=loser,
        submitted_by=submitted_by,
        winner_elo_score=winner_elo,
        loser_elo_score=loser_elo,
    )

    winner.elo = winner_elo
    loser.elo = loser_elo

    winner.wins = winner.wins + 1
    loser.losses = loser.losses + 1

    session.add_all([new_game, winner, loser])

    return new_game
Example #9
0
    def set_outcome(self, request, league_id, team, pk=None):
        is_admin = User.objects.all().get(username=request.user).is_superuser
        if is_admin:
            try:
                scrimmage = Scrimmage.objects.all().get(pk=pk)
            except:
                return Response({'message': 'Scrimmage does not exist.'},
                                status.HTTP_404_NOT_FOUND)

            if 'status' in request.data:
                sc_status = request.data['status']
                if sc_status == "redwon" or sc_status == "bluewon":
                    scrimmage.status = sc_status

                    if scrimmage.ranked:  # TODO check if ranked
                        # update rankings based on trueskill algoirthm
                        # get team info
                        rteam = self.get_team(league_id, scrimmage.red_team_id)
                        bteam = self.get_team(league_id,
                                              scrimmage.blue_team_id)
                        won = rteam if sc_status == "redwon" else bteam
                        lost = rteam if sc_status == "bluewon" else bteam

                        # store previous mu in scrimmage
                        scrimmage.blue_mu = bteam.mu
                        scrimmage.red_mu = rteam.mu

                        # get mu and sigma
                        muW = won.mu
                        sdW = won.sigma
                        muL = lost.mu
                        sdL = lost.sigma

                        winner = trueskill.Rating(mu=muW, sigma=sdW)
                        loser = trueskill.Rating(mu=muL, sigma=sdL)

                        # applies trueskill algorithm & update teams with new scores
                        wScore, lScore = trueskill.rate_1vs1(winner, loser)
                        won.mu = wScore.mu
                        won.sigma = wScore.sigma
                        lost.mu = lScore.mu
                        lost.sigma = lScore.sigma

                        won.save()
                        lost.save()
                    scrimmage.save()
                    return Response({'status': sc_status}, status.HTTP_200_OK)
                else:
                    return Response(
                        {
                            'message':
                            'Set scrimmage to pending/queued/cancelled with accept/reject/cancel api calls'
                        }, status.HTTP_400_BAD_REQUEST)
            else:
                return Response({'message': 'Status not specified.'},
                                status.HTTP_400_BAD_REQUEST)
        else:
            return Response(
                {'message': 'make this request from server account'},
                status.HTTP_401_UNAUTHORIZED)
Example #10
0
def update_trueskill_by_match(match):
    w_ratings = []
    l_ratings = []
    for p in match.winning_players:
        mu, sigma = p.get_current_trueskill()
        w_ratings.append(ts.Rating(mu, sigma))

    for p in match.losing_players:
        mu, sigma = p.get_current_trueskill()
        l_ratings.append(ts.Rating(mu, sigma))

    rating_groups = [w_ratings, l_ratings]
    new_ratings = ts.rate(rating_groups, ranks=[0, 1])
    players = match.winning_players + match.losing_players
    new_ratings_flat = [item for sublist in new_ratings for item in sublist]
    for player, rating in zip(players, new_ratings_flat):
        r_m = Rating(
            user=player,
            match=match,
            rating_type='trueskill_mu',
            rating_value=rating.mu,
            timestamp=match.timestamp,
        )
        r_s = Rating(
            user=player,
            match=match,
            rating_type='trueskill_sigma',
            rating_value=rating.sigma,
            timestamp=match.timestamp,
        )
        db.session.add_all([r_m, r_s])
        db.session.commit()
Example #11
0
 def add_new_player(self, name, token_id, is_admin, is_hidden):
     self.database.execute(
         "INSERT INTO players (name, token_id, skill_mu, skill_sigma, is_admin, is_hidden) VALUES(?, ?, ?, ?, ?, ?)",
         (name, token_id, trueskill.Rating().mu, trueskill.Rating().sigma,
          is_admin, is_hidden))
     self.database.commit()
     print("Added new player: " + name)
Example #12
0
def compute_player_skills(rounds: [RoundRow], teams: [dict],
        current_ratings: {int: trueskill.Rating} = None) \
        -> ({int: trueskill.Rating}, [SkillHistory]):
    ratings = {}
    if current_ratings is not None:
        ratings.update(current_ratings)
    skill_history = []

    for round in rounds:
        rating_groups = (
            {
                player_id: ratings.get(player_id, trueskill.Rating())
                for player_id in teams[round.winner]
            },
            {
                player_id: ratings.get(player_id, trueskill.Rating())
                for player_id in teams[round.loser]
            },
        )
        new_ratings = trueskill.rate(rating_groups)
        for rating in new_ratings:
            ratings.update(rating)
            for player_id, skill in rating.items():
                skill_history.append(
                    SkillHistory(round_id=round.round_id,
                                 player_id=player_id,
                                 skill=skill))

    return ratings, skill_history
Example #13
0
    def calculate_mmr(self, r):
        if not r:
            return None
        #get current rating
        mmr_team0 = OrderedDict(
        )  # key = account | val = list(current_mmr, new_mmr)
        mmr_team1 = OrderedDict()
        for player in r.team0.memberList:
            mmr_team0[r.players[player]][0] = trueskill.Rating(
                self.get_mmr(r.players[player].toonHandle))

        for player in r.team1.memberList:
            mmr_team1[r.players[player]][0] = trueskill.Rating(
                self.get_mmr(r.players[player].toonHandle))

        ratings = trueskill.rate([[x for x in mmr_team0.itervalues()],
                                  [x for x in mmr_team1.itervalues()]],
                                 ranks=[r.team0.isLoser, r.team0.isWinner])
        for player in r.team0.memberList:
            mmr_team0[player][1] = ratings[player]
        for player in r.team1.memberList:
            mmr_team1[player][1] = ratings[player + len(r.team0.memberList) -
                                           1]

        return mmr_team0, mmr_team1
Example #14
0
def compute_ratings(matches):
    ratings = {}
    histories = {}
    new_player_history = []
    stats = {}
    new_player_stats = []

    for _, match in matches.iterrows():
        for name in set(itertools.chain(stats.keys(), match['player_stats'])):
            stats.setdefault(name, new_player_stats[:])
            if name in match['player_stats']:
                stats[name].append(match['player_stats'][name])
            else:
                stats[name].append(None)
        new_player_stats.append(None)

        new_ratings = trueskill.rate((
            {
                name: ratings.get(name, trueskill.Rating())
                for name in match["win"]
            },
            {
                name: ratings.get(name, trueskill.Rating())
                for name in match["loss"]
            },
        ))
        for new_rating in new_ratings:
            ratings.update(new_rating)

        new_player_history.append(trueskill.Rating())
        for name in ratings:
            histories.setdefault(name, new_player_history[:])
            histories[name].append(ratings[name])

    rows = [(name, rating, stats[name], histories[name])
            for name, rating in ratings.items()]
    ratings = pd.DataFrame.from_records(
        rows,
        columns=["Name", "trueskill.Rating", "stats", "history"],
        index="Name")
    ratings.index.name = None

    boundaries = compute_division_boundaries()
    ratings["μ"] = ratings["trueskill.Rating"].apply(lambda rating: rating.mu)
    ratings["σ"] = ratings["trueskill.Rating"].apply(
        lambda rating: rating.sigma)
    ratings["Rating"] = ratings["trueskill.Rating"].apply(
        lambda rating: trueskill.expose(rating))
    ratings["Rank"] = ratings["Rating"].apply(
        lambda rating: find_division(boundaries, rating))
    ratings["Record"] = ratings["stats"].apply(
        lambda stats: compute_record(stats))
    ratings["Streak"] = ratings["stats"].apply(
        lambda stats: compute_streak(stats))
    ratings["Champs"] = ratings["stats"].apply(
        lambda stats: tuple(game["champ"] for game in stats if game))
    ratings.sort_values("Rating", ascending=False, inplace=True)

    return ratings
Example #15
0
 def rate2p(self, r_a, r_b, score):
     (r_a2, r_b2)\
         = super(BoundedTrueSkillSystem, self).rate2p(r_a, r_b, score)
     if r_a2.mu < self.mu_lower_bound:
         r_a2 = trueskill.Rating(self.mu_lower_bound, r_a2.sigma)
     if r_b2.mu < self.mu_lower_bound:
         r_b2 = trueskill.Rating(self.mu_lower_bound, r_b2.sigma)
     return (r_a2, r_b2)
Example #16
0
def rankEvent(roster, year, event):
    testurl = BWurl + str(year) + codeToBW[event]

    origSeed = {}

    for i in range(len(roster), 64):
        print("only should hit this if below 64 teams")
        roster[i + 1] = [Player(0, 'Bye', 0, 0.001).db()] * 4

    for i in range(1, len(roster) + 1):
        origSeed[i] = i

    # add logic for >64 teams, day 1 stuff

    print('Eval...', testurl)
    r1 = requests.get(testurl)
    soup = BeautifulSoup(r1.content, 'html.parser')
    soup_rows = soup.find_all('div', class_='bw_ko_match')

    winnerList = []

    for div in soup_rows:
        winner = div.find_all('div', attrs={'class': 'winner'})
        win = [i['seed'] for i in winner]
        #print(win[0],div['low_seed'], div['high_seed'],'\n')
        #win[0] = input(div['low_seed'] + ' vs. ' + div['high_seed'])
        winnerList.append((win[0], div['low_seed'], div['high_seed']))

    for i in winnerList:  # tuple of winner, low seed, high seed
        #print('yes! ', i)
        upset = (i[0] != i[1])
        winlose = [1, 0] if upset else [0, 1]

        # original seeds
        o1 = int(origSeed[int(i[1])])
        o2 = int(origSeed[int(i[2])])

        #print(roster[o1],roster[o2])

        # iterate over	 rosters, get player TS info
        list1 = [ts.Rating(x['mu'], x['sigma']) for x in roster[o1]]
        list2 = [ts.Rating(x['mu'], x['sigma']) for x in roster[o2]]
        try:
            #print(i,list1,list2)

            newRanks = ts.rate((list1, list2), winlose)
            #print('----got here----', newRanks)
            addToDB(newRanks, roster[o1], roster[o2])
        except KeyError:
            print('keyerror', i, list1, list2)
            pass
        except ValueError:
            print(
                'Team with no players due to bogus player numbers. Ignoring.')

        if upset:
            origSeed[int(i[1])] = int(i[0])
Example #17
0
def parse_rating(score):
    if not score:
        score = trueskill.Rating()
    else:
        score = json.loads(score)
        _ = trueskill.Rating(mu=score['mu'], sigma=score['sigma'])

        score = _
    return score
Example #18
0
def evaluate(players,
             board_size,
             depths=[4, 4],
             amount=1,
             t_run=7.2,
             N=1e9,
             cp=1):
    """
    Evaluation between two methods in players, based on TrueSkill evaluation
    """

    #initialize rating
    if len(players) == 2:
        r1 = ts.Rating()
        r2 = ts.Rating()

        print()
        print('rating 1: ', r1)
        print('rating 2: ', r2)
        print()

        r1, r2, save = match(players, board_size, depths, r1, r2, amount,
                             t_run, N, cp)

        print()
        print('rating 1: ', r1)
        print('rating 2: ', r2)
        print()

    elif len(players) == 3:
        r1 = ts.Rating()
        r2 = ts.Rating()
        r3 = ts.Rating()

        print("Evaluating players: {} {} width depth: {} {}".format(
            players[0], players[1], depths[0], depths[1]))
        r1, r2, save_1 = match([players[0], players[1]], board_size, depths,
                               r1, r2, amount, t_run, N, cp)
        print("Evaluating players: {} {} width depth: {} {}".format(
            players[0], players[2], depths[0], depths[2]))
        r1, r3, save_2 = match([players[0], players[2]], board_size, depths,
                               r1, r3, amount, t_run, N, cp)
        print("Evaluating players: {} {} width depth: {} {}".format(
            players[1], players[2], depths[1], depths[2]))
        r2, r3, save_3 = match([players[1], players[2]], board_size, depths,
                               r2, r3, amount, t_run, N, cp)

        print()
        print('rating 1: ', r1)
        print('rating 2: ', r2)
        print('rating 3: ', r3)
        print()

        save = np.hstack((r1, r2, r3))

    return save
Example #19
0
 def rate2p(self, r_a, r_b, score):
     (r_a2, r_b2) = super(NoisyTrueSkillSystem,
                          self).rate2p(r_a, r_b, score)
     rand_a = 2 * self.noise_factor * (random.random() - 0.5) * (r_a2.mu -
                                                                 r_a.mu)
     rand_b = 2 * self.noise_factor * (random.random() - 0.5) * (r_b2.mu -
                                                                 r_b.mu)
     r_a2 = trueskill.Rating(r_a2.mu + rand_a, r_a2.sigma)
     r_b2 = trueskill.Rating(r_b2.mu + rand_b, r_b2.sigma)
     return (r_a2, r_b2)
Example #20
0
 def check_players(match, racers_dict):
     winner = match.winner.name
     loser = match.loser.name
     if winner not in racers_dict:
         racers_dict[winner]['rating'] = trueskill.Rating(25)
         racers_dict[winner]['matches_played'] = 0
         racers_dict[winner]['tournaments_played'] = 0
     if loser not in racers_dict:
         racers_dict[loser]['rating'] = trueskill.Rating(25)
         racers_dict[loser]['matches_played'] = 0
         racers_dict[loser]['tournaments_played'] = 0
def load_ratings(
        path: str,
        clients: List[Tuple[str,
                            Client]]) -> List[Tuple[str, Client, ts.Rating]]:
    ratings = {}
    if os.path.exists(path):
        with open(path, 'r') as f:
            for name, (mu, sigma) in json.load(f).items():
                ratings[name] = ts.Rating(mu, sigma)
    for name, _ in clients:
        if name not in ratings:
            ratings[name] = ts.Rating()
    return [(n, c, ratings[n]) for (n, c) in clients]
Example #22
0
    def __init__(self, run_folder, self_play):
        self.run_folder = run_folder

        # Server from SEPIA
        self.server = EnvironmentServiceImpl(self.env_callback,
                                             self.winner_callback)

        # Which two agents are currently being played against each other
        self.active_agents = [0, 0]

        # List of agents in tournament. Will be ~50MB total
        self.agents = []

        # List of agent associated data, such as names, used for saving later
        self.agents_data = []

        # Trueskill ratings for each agent
        self.ratings = []

        # How many times each agent as been played against each other
        self.trials = 0

        # How many total trials to do before we are done
        self.num_trials = 200

        # True if player 1 is a sepia agent, not another one of our agents
        self.playing_against_sepia = not self_play

        # How many game steps have occurred
        self.iterations = 0

        # Start time of run
        self.start_time = time.time()

        # Load agents from disk
        self.load_agents()

        # Wins, losses, ties
        self.win_stats = np.zeros((len(self.agents), 3))

        # Set up the trueskill environment and make it a global env
        env = trueskill.TrueSkill(mu=25.0,
                                  sigma=8.33,
                                  beta=4.17,
                                  tau=0,
                                  draw_probability=0.05)
        env.make_as_global()

        # Initialize ratings to be all the same
        self.ratings = [trueskill.Rating() for _ in range(len(self.agents))]
        self.sepia_rating = trueskill.Rating(30, 0.00000000001)
Example #23
0
def _get_player_ratings_from_ddb(table, names):
    players = []
    for player in names:
        result = table.get_item(table,
                                TableName=PLAYER_TABLE_NAME,
                                Key={"PlayerName": player})

        if "Item" in result:
            players.append(
                trueskill.Rating(float(result["Item"]["mu"]),
                                 float(result["Item"]["sigma"])))
        else:
            players.append(trueskill.Rating())
    return players
Example #24
0
def test_3_player_draw():
    r1 = trueskill.Rating()
    r2 = trueskill.Rating()
    r3 = trueskill.Rating()
    sigma0 = r1.sigma
    [(r1, ), (r2, ), (r3, )] = trueskill.transform_ratings([(r1, ), (r2, ),
                                                            (r3, )],
                                                           ranks=(1, 1, 3))
    # We would hope it would be zero, but trueskill isn't that accurate.
    assert abs(r1.mu - r2.mu) < 0.01
    assert r1.mu > r3.mu
    assert r2.mu > r3.mu
    for rating in [r1, r2, r3]:
        assert rating.sigma < sigma0
Example #25
0
def bayes_func(unratePer):#, days):#, par=400, inf=True):
    global ratingDfMain, ratingDf
    df = pd.read_csv('../data/csgoEloDS.csv', sep=';')
    
#    print df.describe()
    df['date'] = df['date'].apply(lambda x: dt.datetime.strptime(x, "%Y-%m-%d %H:%M:%S"))
    #                df = df.sort_values('date').reset_index(drop=True)
    #df['difScore'] = df['difScore'].apply(lambda x: 0.5 if x==0 else 0 if x<0 else 1)
    df.loc[~df.isnull().any(axis=1), 'difScore'] = df.loc[~df.isnull().any(axis=1), 'difScore']/32.0 + 0.5
#    df['difScore'] = df['difScore']/32.0 + 0.5
    
    df['ratingA'] = 25
    df['ratingB'] = 25
    df['rdA'] = 6.458
    df['rdB'] = 6.458
    #df['sigmaA'] = 0.06
    #df['sigmaB'] = 0.06
    
    #print df.info()
#    params = 7
#    unratePer = 112
#    print df.describe()
#    raise 'sdfsdf'
    #        ratePer = 8
    #                params = [df, winBonus, params*unratePer, tau, params*ratePer]
    params = [df, unratePer, True]
    
    teamIds = np.unique(np.append(df['teamAId'].value_counts().index.values, df['teamBId'].value_counts().index.values))
    ratingDfMain = {}
#    mindate = df['date'].min()
#    maxdate = df['date'].max()
#    lcldate = mindate
#    print maxdate
    for ids in teamIds:
        ratingDfMain[ids] = [trueskill.Rating(25, 6.458), 0, trueskill.Rating(25, 6.458)]
    
#    params = 
    print dt.datetime.today()
    print params[1:]
    tm = time.time()
    dc = ratingCalculation(*params)
    print 'time', time.time() - tm, dt.datetime.today()
    print dc
    
#    df['probA'] = np.round(df.apply(lambda x: win_probability1(x), axis=1).values, 6)
#    df['probB'] = 1 - df['probA'].values
    
    
    return dc['acc']
    return -dc['error']
Example #26
0
def add_match(conn, bots, results):
    winner = None
    for id_str, stats in results['stats'].items():
        if stats['rank'] == 1:
            winner = int(id_str)

    if winner is None:
        raise ValueError('Could not detect winner of game')

    query = 'insert into games (datetime, winner, participants, results) values (?, ?, ?, ?)'
    del results['final_snapshot']
    current_time = datetime.datetime.now().isoformat()
    conn.execute(query, (current_time, bots[winner]['id'], json.dumps(bots),
                         json.dumps(results)))

    for bot in bots:
        history_query = 'insert into rank_history (bot_id, datetime, rank, mu, sigma) values (?, ?, ?, ?, ?)'
        conn.execute(
            history_query,
            (bot['id'], current_time, bot['rank'], bot['mu'], bot['sigma']))
        games_played_query = 'update bots set games_played=games_played + 1 where id = ?'
        conn.execute(games_played_query, (bot['id'], ))

    trueskill.setup(tau=0.008, draw_probability=0.001)
    teams = [[trueskill.Rating(mu=bot["mu"], sigma=bot["sigma"])]
             for bot in bots]
    ranks = [results["stats"][str(b)]["rank"] - 1 for b in range(len(bots))]
    new_ratings = trueskill.rate(teams, ranks)

    update_query = 'update bots set mu=?, sigma=? where id=?'
    for bot, rating in zip(bots, new_ratings):
        conn.execute(update_query, (rating[0].mu, rating[0].sigma, bot['id']))

    rerank_bots(conn)
Example #27
0
    def __init__(self, rating_agents, config):
        super(ApprenticeHandleDone, self).__init__(
            rating_agents,
            config
        )

        board_size = int(config["GLOBAL"]["board_size"])
        log_dir = config["GLOBAL"]["log_dir"]
        mcts_dir = config["mctsEval"]["dir"]
        mcts_dir = mcts_dir.format(board_size=board_size)
        mcts_rating_file = config["mctsEval"]["eval_file"]
        mcts_rating_file = "/".join([log_dir, mcts_dir, mcts_rating_file])
        with open(mcts_rating_file, "r") as ratings_f:
            mcts_ratings = json.load(ratings_f)

        self.mcts_ratings = {
            player.WHITE: dict(),
            player.BLACK: dict()
        }

        for key in self.mcts_ratings:
            mus = mcts_ratings[str(int(key))]["mu"]
            sigmas = mcts_ratings[str(int(key))]["sigma"]
            depths = mcts_ratings[str(int(key))]["depth"]
            for mu, sigma, depth in zip(mus, sigmas, depths):
                self.mcts_ratings[key][depth] = trueskill.Rating(
                    mu=mu, sigma=sigma)
Example #28
0
def main(games_file: str, ratings_file: str):
    # Load data.
    players = defaultdict(lambda: ts.Rating())
    games = pd.read_csv(games_file)

    # Sort data based on date.
    games.sort_values(by=[DATE_COLUMN], inplace=True)
    games.fillna("", inplace=True)

    for _, (date, pl1, pl2, sc1, sc2, pl3, pl4) in games.iterrows():
        team1 = []
        skills1 = []

        team2 = []
        skills2 = []

        team1, skills1 = append(pl1, players, team1, skills1)
        team1, skills1 = append(pl2, players, team1, skills1)

        team2, skills2 = append(pl3, players, team2, skills2)
        team2, skills2 = append(pl4, players, team2, skills2)

        ranks = compute_rank(sc1, sc2)

        ratings1, ratings2 = ts.rate([skills1, skills2], ranks=ranks)
        update(players, team1, ratings1)
        update(players, team2, ratings2)

    # Save ratings.
    result = []
    for name, rating in players.items():
        result.append({"Name": name, "Mu": rating.mu, "Sigma": rating.sigma})

    df = pd.DataFrame(result)
    df.to_csv(ratings_file, index=False)
Example #29
0
 def rate(self, ratings, ranks):
     ratings2 = super(BoundedTrueSkillSystem, self).rate(ratings, ranks)
     for i in range(len(ratings2)):
         if ratings2[i].mu < self.mu_lower_bound:
             ratings2[i] = trueskill.Rating(self.mu_lower_bound,
                                            ratings2[i].sigma)
     return ratings2
Example #30
0
 def set_current_robotic_player(self, id):
     self.current_robotic_player_record = self.db.get_robotic_player(id)[0]
     self.current_robotic_player_rating = trueskill.Rating(
         self.current_robotic_player_record[3],
         self.current_robotic_player_record[4])
     print("Robot database row {}".format(
         self.current_robotic_player_record))