Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

External sources of (league) score data #22

Merged
merged 3 commits into from
Feb 17, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 54 additions & 2 deletions sr/comp/scores.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from . import yaml_loader
from .match_period import Match, MatchType
from .types import (
ExternalScoreData,
GamePoints,
MatchId,
MatchNumber,
Expand Down Expand Up @@ -170,6 +171,12 @@ def load_scores_data(result_dir: Path) -> Iterator[ScoreData]:
yield yaml_loader.load(result_file)


def load_external_scores_data(result_dir: Path) -> Iterator[ExternalScoreData]:
for result_file in result_dir.glob('*.yaml'):
raw = yaml_loader.load(result_file)
yield from raw['scores']


# The scorer that these classes consume should be a class that is compatible
# with libproton in its Proton 2.0.0-rc1 form.
# See https://github.com/PeterJCLaw/proton and
Expand Down Expand Up @@ -318,15 +325,26 @@ def __init__(
teams: Iterable[TLA],
scorer: ScorerType,
num_teams_per_arena: int,
extra: Mapping[TLA, TeamScore] | None = None,
):
super().__init__(scores_data, teams, scorer, num_teams_per_arena)

if extra:
for tla, score in extra.items():
try:
team_score = self.teams[tla]
except KeyError:
raise InvalidTeam(tla, "extra league points data") from None

team_score.add_game_points(score.game_points)
team_score.add_league_points(score.league_points)

# Sum the league scores for each team
for match_id, match in self.ranked_points.items():
for tla, score in match.items():
for tla, points in match.items():
if tla not in self.teams:
raise InvalidTeam(tla, "ranked score for match {}{}".format(*match_id))
self.teams[tla].add_league_points(score)
self.teams[tla].add_league_points(points)

self.positions = self.rank_league(self.teams)
r"""
Expand Down Expand Up @@ -409,6 +427,34 @@ class TiebreakerScores(KnockoutScores):
pass


def load_external_scores(
scores_data: Iterable[ExternalScoreData],
teams: Iterable[TLA],
) -> Mapping[TLA, TeamScore]:
"""
Mechanism to import additional scores from an external source.

This provides flexibility in the sources of score data.
"""

scores = {x: TeamScore() for x in teams}

for entry in scores_data:
tla = TLA(entry['team'])
try:
team_score = scores[tla]
except KeyError:
raise InvalidTeam(tla, "external scores data") from None

game_points = entry.get('game_points')
if game_points:
team_score.add_game_points(GamePoints(game_points))

team_score.add_league_points(LeaguePoints(entry['league_points']))

return scores


class Scores:
"""
A simple class which stores references to the league and knockout scores.
Expand All @@ -422,11 +468,17 @@ def load(
scorer: ScorerType,
num_teams_per_arena: int,
) -> Scores:
external_scores = load_external_scores(
load_external_scores_data(root / 'external'),
teams,
)

league = LeagueScores(
load_scores_data(root / 'league'),
teams,
scorer,
num_teams_per_arena,
extra=external_scores,
)

knockout = KnockoutScores(
Expand Down
11 changes: 11 additions & 0 deletions sr/comp/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,17 @@ def validate(self, extra_data: ScoreOtherData | None) -> None:
ScorerType = Type[Union[ValidatingScorer, SimpleScorer]]


class ExternalScoreData(TypedDict):
"""
The expected YAML data format in "external" scores files is a single root
key 'scores' whose value is a list of mappings compatible with this type.
"""

team: str
game_points: NotRequired[int]
league_points: int
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could start thinking about something like pydantic for validating these data as we read them in based on the types, though that's out of scope here.

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I've been wondering about having some schema stuff.



# Locations within the Venue

RegionName = NewType('RegionName', str)
Expand Down
2 changes: 1 addition & 1 deletion tests/dummy
69 changes: 64 additions & 5 deletions tests/test_league_scores.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,33 @@
from __future__ import annotations

import unittest
from typing import Iterable, List
from typing import Iterable, List, Mapping

from sr.comp.scores import LeagueScores, TeamScore
from sr.comp.types import ScoreData, TLA

from .factories import build_score_data, FakeScorer


def load_data(the_data: ScoreData) -> LeagueScores:
def load_data(
the_data: ScoreData,
extra: Mapping[TLA, TeamScore] | None = None,
) -> LeagueScores:
teams = the_data['teams'].keys()
return load_datas([the_data], teams)
return load_datas([the_data], teams, extra)


def load_datas(the_datas: List[ScoreData], teams: Iterable[TLA]) -> LeagueScores:
def load_datas(
the_datas: List[ScoreData],
teams: Iterable[TLA],
extra: Mapping[TLA, TeamScore] | None = None,
) -> LeagueScores:
scores = LeagueScores(
the_datas,
teams,
FakeScorer,
num_teams_per_arena=4,
extra=extra,
)
return scores

Expand Down Expand Up @@ -61,7 +71,56 @@ def test_league_points(self):

league = leagues[id_]

self.assertEqual({'JMS': 0, 'PAS': 0, 'RUN': 8, 'ICE': 6}, league)
self.assertEqual(
{'JMS': 0, 'PAS': 0, 'RUN': 8, 'ICE': 6},
league,
"Wrong league scores for match {}{}".format(*id_),
)

self.assertEqual(
{
'JMS': TeamScore(0, 4),
'PAS': TeamScore(0, 0),
'RUN': TeamScore(8, 8),
'ICE': TeamScore(6, 2),
},
scores.teams,
"Wrong overall scores",
)

def test_league_points_with_extra(self):
scores = load_data(
get_score_data(),
extra={
TLA('JMS'): TeamScore(league=2),
TLA('RUN'): TeamScore(league=1, game=3),
},
)

leagues = scores.ranked_points
self.assertEqual(1, len(leagues))

id_ = ('A', 123)
self.assertIn(id_, leagues)

league = leagues[id_]

self.assertEqual(
{'JMS': 0, 'PAS': 0, 'RUN': 8, 'ICE': 6},
league,
"Wrong league scores for match {}{}".format(*id_),
)

self.assertEqual(
{
'JMS': TeamScore(league=2, game=4),
'PAS': TeamScore(league=0, game=0),
'RUN': TeamScore(league=9, game=11),
'ICE': TeamScore(league=6, game=2),
},
scores.teams,
"Wrong overall scores",
)

def test_team_points(self):
scores = load_basic_data()
Expand Down