def __init__(self, **kws): super().__init__(**kws) ratings = json.load(open(self.INITIAL_RATINGS_FILENAME)) for name, rating in ratings.items(): self.ratings[name] = Rating(mu=rating['mu'], sigma=rating['sigma']) self.best_rosters = {} self.ratings_history = OrderedDict()
async def test_rating_persistence(semiinitialized_service): # Assumes that game_player_stats has an entry for player 1 in game 1. service = semiinitialized_service game_id = 1 player_id = 1 rating_type = RatingType.GLOBAL rating_type_id = service._rating_type_ids[RatingType.GLOBAL] old_ratings = {player_id: Rating(1000, 500)} after_mean = 1234 new_ratings = {player_id: Rating(after_mean, 400)} outcomes = {player_id: GameOutcome.VICTORY} await service._persist_rating_changes(game_id, rating_type, old_ratings, new_ratings, outcomes) async with service._db.acquire() as conn: sql = select([game_player_stats.c.id, game_player_stats.c.after_mean]).where( and_( game_player_stats.c.gameId == game_id, game_player_stats.c.playerId == player_id, )) results = await conn.execute(sql) gps_row = await results.fetchone() sql = select([leaderboard_rating.c.mean]).where( and_( leaderboard_rating.c.login_id == player_id, leaderboard_rating.c.leaderboard_id == rating_type_id, )) results = await conn.execute(sql) rating_row = await results.fetchone() sql = select([ leaderboard_rating_journal.c.rating_mean_after ]).where(leaderboard_rating_journal.c.game_player_stats_id == gps_row[ game_player_stats.c.id]) results = await conn.execute(sql) journal_row = await results.fetchone() assert gps_row[game_player_stats.c.after_mean] == after_mean assert rating_row[leaderboard_rating.c.mean] == after_mean assert journal_row[ leaderboard_rating_journal.c.rating_mean_after] == after_mean
def getAdjList_Similarity3(self, QuestionList): from trueskill import Rating, rate AdjList = [] ext = '' margin = 4 trainPairs = pd.merge(self.trainPairs, self.pairFeatures, on='PairId') trainPairs["PairId"] = trainPairs["PairId"].apply(lambda x: int(x) - 1) trainPairs["QTag_vector"] = trainPairs["QTags"].apply(lambda x: x.split(",")) trainPairs["QTag_vector"] = trainPairs["QTag_vector"].apply(lambda x: ' '.join(sorted(list(x)))) # compute trueSkill value RatingDict = dict() for i in trainPairs["CommenterId"].drop_duplicates().values.tolist(): RatingDict[i] = (Rating(),) step1 = trainPairs.groupby(["QuestionId"]) for i, j in step1: if int(i) in QuestionList: IdList = j["CommenterId"].values.tolist() rating = j["Credible"].apply(lambda x: 1 - int(x)).values.tolist() for i, j in zip(IdList, rate([RatingDict[x] for x in IdList], ranks=rating)): RatingDict[i] = j trainPairs["Rating"] = trainPairs["CommenterId"] trainPairs["Rating"] = trainPairs["Rating"].apply(lambda x: RatingDict[x][0].mu - 3 * RatingDict[x][0].sigma) trainPairs["Link"] = [0 for i in range(len(trainPairs))] self.Rating = trainPairs[["PairId", "Rating"]] # create clique using trueSkill value step2 = trainPairs.groupby(["QuestionId"]) idxList1 = [] idxList2 = [] for i, j in step2: tempScore = sorted(j["Rating"].values.tolist()) if tempScore[-1] - tempScore[-2] >= margin: idxList1.append(j["Rating"].idxmax()) if tempScore[1] - tempScore[0] >= margin / 2: idxList2.append(j["Rating"].idxmin()) trainPairs.loc[idxList1, "Link"] = 1 trainPairs.loc[idxList2, "Link"] = 2 trainPairs["Credible"] = trainPairs["Credible"].apply(lambda x: int(x)) step3 = trainPairs[trainPairs["Link"].isin([1, 2])].groupby(["CommenterId", "Link"]) for i, j in step3: if len(j) >= 2: for i in combinations(j["PairId"].tolist(), 2): AdjList.append(i) # exit() AdjList = pd.DataFrame(data=AdjList, columns=["Nid1", "Nid2"]) AdjList = AdjList.drop_duplicates() # AdjList = AdjList.sample(500) print("similarity3:", len(AdjList)) edges = AdjList.sort_values(by=["Nid1", "Nid2"], ascending=True).values return edges
async def test_game_outcomes_conflicting(game: Game, players): await game.clear_data() game.state = GameState.LOBBY players.hosting.ladder_rating = Rating(1500, 250) players.joining.ladder_rating = Rating(1500, 250) add_connected_players(game, [players.hosting, players.joining]) await game.launch() await game.add_result(players.hosting, 0, 'victory', 1) await game.add_result(players.joining, 1, 'victory', 0) await game.add_result(players.hosting, 0, 'defeat', 1) await game.add_result(players.joining, 1, 'defeat', 0) game.set_player_option(players.hosting.id, 'Team', 1) game.set_player_option(players.joining.id, 'Team', 1) host_outcome = game.outcome(players.hosting) guest_outcome = game.outcome(players.joining) assert host_outcome is None assert guest_outcome is None
async def test_to_dict(game, create_player): await game.clear_data() game.state = GameState.LOBBY players = [ (create_player(**info), result, team) for info, result, team in [ (dict(login='******', id=1, global_rating=Rating(1500, 250.7)), 0, 1), (dict(login='******', id=2, global_rating=Rating(1700, 120.1)), 0, 1), (dict(login='******', id=3, global_rating=Rating(1200, 72.02)), 0, 2), (dict(login='******', id=4, global_rating=Rating(1200, 72.02)), 0, 2), ] ] add_connected_players(game, [player for player, _, _ in players]) for player, _, team in players: game.set_player_option(player.id, 'Team', team) game.set_player_option(player.id, 'Army', player.id - 1) game.host = players[0][0] await game.launch() data = game.to_dict() expected = { "command": "game_info", "visibility": VisibilityState.to_string(game.visibility), "password_protected": game.password is not None, "uid": game.id, "title": game.name, "state": 'playing', "featured_mod": game.game_mode, "featured_mod_versions": game.getGamemodVersion(), "sim_mods": game.mods, "mapname": game.map_folder_name, "map_file_path": game.map_file_path, "host": game.host.login, "num_players": len(game.players), "game_type": game.gameType, "max_players": game.max_players, "launched_at": game.launched_at, "teams": { team: [player.login for player in game.players if game.get_player_option(player.id, 'Team') == team] for team in game.teams } } assert data == expected
def get_player(self, profile): date_now = timezone.now() playerQuery = Player.objects.filter(judge=self.judge, target=profile) if playerQuery.exists(): player = playerQuery[0] else: newRating = Rating() player = Player(judge=self.judge, target=profile, update_date=date_now, mu=newRating.mu, sigma=newRating.sigma, elo=elo.INITIAL) player.save() return player
async def test_compute_rating_does_not_rate_double_win(game: Game, player_factory): game.state = GameState.LOBBY players = [(player_factory(f"{i}", player_id=i, global_rating=rating), result, team) for i, (rating, result, team) in enumerate([ (Rating(1500, 250), 10, 2), (Rating(1700, 120), 0, 3), ], 1)] add_connected_players(game, [player for player, _, _ in players]) for player, _, team in players: game.set_player_option(player.id, 'Team', team) game.set_player_option(player.id, 'Army', player.id - 1) await game.launch() for player, result, _ in players: await game.add_result(player, player.id - 1, 'victory', result) with pytest.raises(GameRatingError): game.compute_rating()
async def test_rate_game_sum_of_scores_edge_case(custom_game, player_factory): """ For certain scores, compute_rating was determining the winner incorrectly, see issue <https://github.com/FAForever/server/issues/485>. """ rating_service = custom_game.game_service._rating_service win_team = 2 lose_team = 3 rating_list = [Rating(1500, 200)] * 8 team_list = (4 * [lose_team]) + (4 * [win_team]) score_list = [1, 1, 1, -10, 10, -10, 2] players = add_players_with_rating(player_factory, custom_game, rating_list, team_list) await custom_game.launch() await report_results( custom_game, [( player, player._test_army, "victory" if team == win_team else "defeat", score, ) for (player, team), score in zip(players, score_list)], ) custom_game.enforce_rating = True await custom_game.on_game_end() await rating_service._join_rating_queue() results = get_persisted_results(rating_service) assert results.rating_type is RatingType.GLOBAL for player, team in players: if team == win_team: assert results.ratings[player.id] > Rating( *player.ratings[RatingType.GLOBAL]) assert results.outcomes[player.id] is GameOutcome.VICTORY else: assert results.ratings[player.id] < Rating( *player.ratings[RatingType.GLOBAL]) assert results.outcomes[player.id] is GameOutcome.DEFEAT
def test_get_rating_groups(): p1, p2 = MockPlayer(), MockPlayer() players_by_team = {2: [p1], 3: [p2]} outcome_py_player = {p1: GameOutcome.VICTORY, p2: GameOutcome.DEFEAT} rater = GameRater(players_by_team, outcome_py_player) rating_groups = rater._get_rating_groups() assert len(rating_groups) == 2 assert {p1: Rating(1500, 500)} in rating_groups
def initalise_ratings(df): Red_fighters = list(df['R_fighter'].values) Blue_fighters = list(df['B_fighter'].values) All_fighters = Red_fighters + Blue_fighters unique_fighters = list(set(All_fighters)) inital_rating = [Rating()] * len(unique_fighters) return (dict(zip(unique_fighters, inital_rating)))
def test_compute_rating(): p1, p2 = MockPlayer(), MockPlayer() players_by_team = {2: [p1], 3: [p2]} outcome_py_player = {p1: GameOutcome.VICTORY, p2: GameOutcome.DEFEAT} rater = GameRater(players_by_team, outcome_py_player) result = rater.compute_rating() for team in result: for player, new_rating in team.items(): assert new_rating != Rating(*player.ratings[RatingType.GLOBAL])
def compute_rating(self, rating='global'): """ Compute new ratings :param rating: 'global' or 'ladder' :return: rating groups of the form: >>> p1,p2,p3,p4 = Player() >>> [{p1: p1.rating, p2: p2.rating}, {p3: p3.rating, p4: p4.rating}] """ assert self.state == GameState.LIVE or self.state == GameState.ENDED team_scores = {} ffa_scores = [] for player in sorted(self.players, key=lambda p: self.get_player_option(p.id, 'Army') or -1): team = self.get_player_option(player.id, 'Team') army = self.get_player_option(player.id, 'Army') if army < 0: self._logger.debug("Skipping %s", player) continue if not team: raise GameError("Missing team for player id: {}".format(player.id)) if team != 1: if team not in team_scores: team_scores[team] = 0 try: team_scores[team] += self.get_army_score(army) except KeyError: team_scores[team] += 0 self._logger.warn("Missing game result for %s: %s", army, player) elif team == 1: ffa_scores.append((player, self.get_army_score(army))) ranks = [-score for team, score in sorted(team_scores.items(), key=lambda t: t[0])] rating_groups = [] for team in sorted(self.teams): if team != 1: rating_groups += [{player: Rating(*getattr(player, '{}_rating'.format(rating))) for player in self.players if self.get_player_option(player.id, 'Team') == team}] for player, score in sorted(ffa_scores, key=lambda x: self.get_player_option(x[0].id, 'Army')): rating_groups += [{player: Rating(*getattr(player, '{}_rating'.format(rating)))}] ranks.append(-score) self._logger.debug("Rating groups: %s", rating_groups) self._logger.debug("Ranks: %s", ranks) return trueskill.rate(rating_groups, ranks)
def analyze_teams(player_blue_offense, player_blue_defense, player_red_offense, player_red_defense): ts = TrueSkill(mu=MU, sigma=SIGMA, beta=BETA, tau=TAU, draw_probability=DRAW_PROB) player_blue_offense_rating = Rating(mu=player_blue_offense.rating_mu_offense, sigma=player_blue_offense.rating_sigma_offense) if player_blue_offense is not None else None player_blue_defense_rating = Rating(mu=player_blue_defense.rating_mu_defense, sigma=player_blue_defense.rating_sigma_defense) if player_blue_defense is not None else None player_red_offense_rating = Rating(mu=player_red_offense.rating_mu_offense, sigma=player_red_offense.rating_sigma_offense) if player_red_offense is not None else None player_red_defense_rating = Rating(mu=player_red_defense.rating_mu_defense, sigma=player_red_defense.rating_sigma_defense) if player_red_defense is not None else None blue_team = _build_team(player_blue_offense_rating, player_blue_defense_rating) red_team = _build_team(player_red_offense_rating, player_red_defense_rating) match_balance = ts.quality([blue_team, red_team]) win_prob = win_probability(ts, blue_team, red_team) return {"match_balance": match_balance, "predicted_win_prob_for_blue": win_prob}
def update_scores(team_a_score, team_b_score, win_key, result_id): """ Updates scores according to TrueSkill Rating Args: :param team_a_score: object of model class Scores representing Team A score :param team_b_score: object of model class Scores representing Team B score :param win_key: name of the winning team or 'Draw' :param result_id: Foreign key of DSCIV_result table """ rating_team_a = Rating(mu=team_a_score.mu, sigma=team_a_score.sigma) rating_team_b = Rating(mu=team_b_score.mu, sigma=team_b_score.sigma) if 'Draw' in win_key: new_rating_team_a, new_rating_team_b = rate_1vs1(rating1=rating_team_a, rating2=rating_team_b, drawn=True) elif team_a_score.team_id in win_key: new_rating_team_a, new_rating_team_b = rate_1vs1(rating1=rating_team_a, rating2=rating_team_b) elif team_b_score.team_id in win_key: new_rating_team_b, new_rating_team_a = rate_1vs1(rating1=rating_team_b, rating2=rating_team_a) else: new_rating_team_a = '' new_rating_team_b = '' print("Could not assign new ratings.") # Update Mu and Sigma ratings team_a_score.mu, team_a_score.sigma = new_rating_team_a.mu, new_rating_team_a.sigma team_b_score.mu, team_b_score.sigma = new_rating_team_b.mu, new_rating_team_b.sigma # Update results ids team_a_score.result_id = result_id team_b_score.result_id = result_id # Update nr of queries team_a_score.nr_of_queries += 1 team_b_score.nr_of_queries += 1 # Save results team_a_score.save() team_b_score.save()
def addSingleEntry(team1, team2): if not teamNames.__contains__(team1[0]): teamNames.append(team1[0]) teams[team1[0]] = [Rating()] teams_home_prob[team1[0]] = [0, 0] teams_away_prob[team1[0]] = [0, 0] if not teamNames.__contains__(team2[0]): teamNames.append(team2[0]) teams[team2[0]] = [Rating()] teams_home_prob[team2[0]] = [0, 0] teams_away_prob[team2[0]] = [0, 0] if team1[1] > team2[1]: (new_r1, ), (new_r2, ) = trueskill.rate( [teams[team1[0]], teams[team2[0]]], ranks=[0, 1]) teams[team1[0]] = [new_r1] teams[team2[0]] = [new_r2] teams_home_prob[team2[0]] = [ teams_home_prob[team2[0]][0], teams_home_prob[team2[0]][1] + 1 ] teams_away_prob[team1[0]] = [ teams_away_prob[team1[0]][0] + 1, teams_away_prob[team1[0]][1] + 1 ] if team1[1] < team2[1]: (new_r1, ), (new_r2, ) = trueskill.rate( [teams[team1[0]], teams[team2[0]]], ranks=[1, 0]) teams[team1[0]] = [new_r1] teams[team2[0]] = [new_r2] teams_home_prob[team2[0]] = [ teams_home_prob[team2[0]][0] + 1, teams_home_prob[team2[0]][1] + 1 ] teams_away_prob[team1[0]] = [ teams_away_prob[team1[0]][0], teams_away_prob[team1[0]][1] + 1 ] if team1[1] == team2[1]: (new_r1, ), (new_r2, ) = trueskill.rate( [teams[team1[0]], teams[team2[0]]], ranks=[0, 0]) teams[team1[0]] = [new_r1] teams[team2[0]] = [new_r2]
def calc_new_ranks(cls, report : DB.RankedMatch, old_ranks : List[Rating]) -> List[Rating]: try: if report.scrapped: return [Rating(mu=i.mu-20, sigma=i.sigma) for i in old_ranks] new_ranks = cls.to_1d( cls.env.rate([(i,) for i in old_ranks], ranks=[pos for pos in report.players_pos.values()]) ) except ValueError as e: logger.error(f"{type(e).__name__}: {e}") return old_ranks return new_ranks
def playDoubles_score(self, name1, name2, name3, name4, winner_score, loser_score): t1 = (self.ratings[name1], self.ratings[name2]) t2 = (self.ratings[name3], self.ratings[name4]) newt1, newt2 = self.env.rate([t1, t2]) name1_average = newt1[0].mu name1_sigma = newt1[0].sigma name2_average = newt1[1].mu name2_sigma = newt1[1].sigma name3_average = newt2[0].mu name3_sigma = newt2[0].sigma name4_average = newt2[1].mu name4_sigma = newt2[1].sigma self.ratings[name1] = Rating() self.ratings[name2] = Rating() self.ratings[name3] = Rating() self.ratings[name4] = Rating() self.ratings[name1], self.ratings[name2] = newt1 self.ratings[name3], self.ratings[name4] = newt2
def add_player(self, player_id: int, player_name: str, mu: float = None, sigma: float = None): if mu is None: mu = self.ts.mu if sigma is None: sigma = self.ts.sigma self.players[player_id] = TrueSkillMatchmaker.Player( player_id, player_name, Rating(mu=mu, sigma=sigma))
def update_players(self): date_now = timezone.now() winnerTrueskillExistingRating = Rating(mu=self.winner.mu, sigma=self.winner.sigma) loserTrueskillExistingRating = Rating(mu=self.loser.mu, sigma=self.loser.sigma) winnerTrueskillUpdatedRating, loserTrueskillUpdatedRating = rate_1vs1(winnerTrueskillExistingRating, loserTrueskillExistingRating) elo_result = elo.rate_1vs1(self.winner.elo, self.loser.elo) self.winner.mu = winnerTrueskillUpdatedRating.mu self.winner.sigma = winnerTrueskillUpdatedRating.sigma self.winner.elo = elo_result[0] self.winner.save() self.loser.mu = loserTrueskillUpdatedRating.mu self.loser.sigma = loserTrueskillUpdatedRating.sigma self.loser.elo = elo_result[1] self.loser.save() return self.winner, self.loser
def get(player_name): try: player = players[player_name] player["rating"] = Rating(mu=player["skill"], sigma=player["skill_sigma"]) except KeyError: # New/unrecognized player player = { "n_games": 0, "opponent_score_share": 0.5, "skill": TRUE_SKILL_BASE, "rating": Rating(), "n_wins": 0, "win_rate": 0, "score_share": 0, "skill_rank": None, "skill_rank_pct": None, "years": [] } return player
def Get_rating(xp1content): users = db.child("players").child(xp1content).get() xmu = db.child("players").child(xp1content).child('mu').get() xsigma = db.child("players").child(xp1content).child('sigma').get() x = users.val() sigma = xsigma.val() mu = xmu.val() d,y = float(mu),float(sigma) r1 = Rating(d,y) return r1
def test_compute_rating_of_two_player_ffa_match_if_none_chose_a_team(): FFA_TEAM = 1 p1, p2 = MockPlayer(), MockPlayer() players_by_team = {FFA_TEAM: [p1, p2]} outcome_py_player = {p1: GameOutcome.VICTORY, p2: GameOutcome.DEFEAT} rater = GameRater(players_by_team, outcome_py_player) result = rater.compute_rating() for team in result: for player, new_rating in team.items(): assert new_rating != Rating(*player.ratings[RatingType.GLOBAL])
async def test_compute_rating_only_one_surviver(game: Game, player_factory): """ When a player dies their score is reported as "defeat", but this does not necessarily mean they lost the game, if their team mates went on and later reported a "victory". """ game.state = GameState.LOBBY win_team = 2 lose_team = 3 players = [(player_factory(login=f"{i}", player_id=i, global_rating=Rating(1500, 200), with_lobby_connection=False), outcome, result, team) for i, (outcome, result, team) in enumerate([ ("defeat", -10, lose_team), ("defeat", -10, lose_team), ("defeat", -10, lose_team), ("defeat", -10, lose_team), ("defeat", -10, win_team), ("defeat", -10, win_team), ("defeat", -10, win_team), ("victory", 10, win_team), ], 1)] add_connected_players(game, [player for player, _, _, _ in players]) for player, _, _, team in players: game.set_player_option(player.id, 'Team', team) game.set_player_option(player.id, 'Army', player.id - 1) await game.launch() for player, outcome, result, team in players: await game.add_result(player, player.id - 1, outcome, result) result = game.compute_rating() for team in result: for player, new_rating in team.items(): old_rating = Rating(*player.ratings[RatingType.GLOBAL]) # `team` index in result might not coincide with `team` index in players if player.id > 4: assert new_rating > old_rating else: assert new_rating < old_rating
async def test_to_dict(game, player_factory): game.state = GameState.LOBBY players = [(player_factory(f"{i}", player_id=i, global_rating=rating), result, team) for i, (rating, result, team) in enumerate([ (Rating(1500, 250), 0, 1), (Rating(1700, 120), 0, 1), (Rating(1200, 72), 0, 2), (Rating(1200, 72), 0, 2), ], 1)] add_connected_players(game, [player for player, _, _ in players]) for player, _, team in players: game.set_player_option(player.id, 'Team', team) game.set_player_option(player.id, 'Army', player.id - 1) game.host = players[0][0] await game.launch() data = game.to_dict() expected = { "command": "game_info", "visibility": VisibilityState.to_string(game.visibility), "password_protected": game.password is not None, "uid": game.id, "title": game.sanitize_name(game.name), "state": 'playing', "featured_mod": game.game_mode, "sim_mods": game.mods, "mapname": game.map_folder_name, "map_file_path": game.map_file_path, "host": game.host.login, "num_players": len(game.players), "max_players": game.max_players, "launched_at": game.launched_at, "teams": { team: [ player.login for player in game.players if game.get_player_option(player.id, 'Team') == team ] for team in game.teams } } assert data == expected
def update_board(request, winner=None, match_pk=None): if winner == None or match_pk == None: messages.error(request, 'Resource not found for update_board') return HttpResponseRedirect('/') match = get_object_or_404(Match, pk=match_pk) match.state = 2 match.save() record = MatchRecord() record.match = match record.winner_number = winner record.save() rate_1 = Rating(mu=match.bot1.mu, sigma=match.bot1.sigma) rate_2 = Rating(mu=match.bot2.mu, sigma=match.bot2.sigma) if record.winner_number == 1: record.match.bot1.w += 1 record.match.bot2.l += 1 rate_1, rate_2 = rate_1vs1(rate_1, rate_2) elif record.winner_number == 2: record.match.bot2.w += 1 record.match.bot1.l += 1 rate_2, rate_1 = rate_1vs1(rate_2, rate_1) else: record.match.bot1.d += 1 record.match.bot2.d += 1 rate_1, rate_2 = rate_1vs1(rate_1, rate_2, drawn=True) print(rate_1, rate_2) record.match.bot1.mu = rate_1.mu record.match.bot1.sigma = rate_1.sigma record.match.bot1.score = rate_1.mu - 3 * rate_1.sigma record.match.bot1.games_played = record.match.bot1.games_played + 1 record.match.bot2.mu = rate_2.mu record.match.bot2.sigma = rate_2.sigma record.match.bot2.score = rate_2.mu - 3 * rate_2.sigma record.match.bot2.games_played = record.match.bot2.games_played + 1 record.match.bot1.last_played = timezone.now() record.match.bot2.last_played = timezone.now() record.match.bot1.save() record.match.bot2.save() return HttpResponseRedirect( reverse('board:viewBoard', kwargs={'game_id': match.game.id}))
def skill_to_rating_array(sorted_elo_dict): ''' Strips values from dictionary keys 'mu' & 'sigma'. Stripping preserves order. Returns array of stripped values ''' rating_array = [] for key, item in sorted_elo_dict.items(): rating_array.append(Rating(mu=item[0], sigma=item[1])) return rating_array
def set_player_ratings_after_match(df_, fname_, lname_, college_, position_,k_factor_, rating_): player_idx = df_[(df_.first_name == fname_) \ & (df_.last_name == lname_) \ & (df_.college == college_)].index df_.iloc[player_idx, df_.columns.get_loc('mu')] = rating_.mu + k_factor_[int(position_)-1] #df_.iloc[player_idx, df_.columns.get_loc('mu')] = rating_.mu df_.iloc[player_idx, df_.columns.get_loc('sigma')] = rating_.sigma my_mu = df_.iloc[player_idx.item(), df_.columns.get_loc('mu')] my_sigma = df_.iloc[player_idx.item(), df_.columns.get_loc('sigma')] my_rating = Rating(mu=my_mu, sigma=my_sigma) return my_rating
def set_default_player_rating(df_, div_='DI', dict_start_rating_ = None): df_players_ = df_.loc[:, ['division', 'college', 'first_name', 'last_name', 'mu', 'sigma']].copy() \ .drop_duplicates() df_players_ = strip_all_strings_in_df(df_players_, ['division', 'college', 'first_name', 'last_name']) df_players_ = df_players_[df_players_.division == div_] df_players_.loc[:,'mu'] = Rating().mu df_players_['sigma'] = Rating().sigma # if dict_start_rating_ != None: df_players_['name'] = df_players_['first_name'] + " " + df_players_['last_name'] df_players_['rating'] = df_players_['name'].replace(dict_start_ratings) df_players_['mu'] = df_players_['rating'].where(df_players_['rating'].isin([25,26,27,28,29])).fillna(25) # df_players_ = df_players_.sort_values(['last_name', 'first_name', 'college'], ascending=True) \ .drop_duplicates() \ .reset_index() \ .loc[:, ['division', 'college', 'first_name', 'last_name', 'mu', 'sigma']] return df_players_
async def test_get_player_rating_legacy(semiinitialized_service): service = semiinitialized_service # Player 51 should have no leaderboard_rating entry # but entries in the legacy global_rating and ladder1v1_rating tables player_id = 51 legacy_global_rating = Rating(1201, 250) legacy_ladder_rating = Rating(1301, 400) db_ratings = await get_all_ratings(service._db, player_id) assert len(db_ratings) == 0 # no new rating entries yet rating = await service._get_player_rating(player_id, RatingType.GLOBAL) assert rating == legacy_global_rating rating = await service._get_player_rating(player_id, RatingType.LADDER_1V1) assert rating == legacy_ladder_rating db_ratings = await get_all_ratings(service._db, player_id) assert len(db_ratings) == 2 # new rating entries were created assert db_ratings[0]["mean"] == 1201 assert db_ratings[1]["mean"] == 1301
def get_team_skill(self, team): """ Average all mu values for the total team skill. Lower confidence a lot, since we're not sure about this at all. TODO: How much to lower the confidence? """ team_skills = [self.get_player_skill(p) for p in team] avg_mu = sum(r.mu for r in team_skills) / len(team) # mu_dist = max([r.mu for r in team_skills]) - min([r.mu for r in team_skills]) avg_sigma = sum(r.sigma for r in team_skills) / len(team) avg_sigma = avg_sigma * 2 # Increase uncertainty in averaged team skills team_skill = Rating(mu=avg_mu, sigma=avg_sigma) return team_skill