Example #1
0
def main(args: Namespace):
    load_teams(args.database)
    league = league_register[get_unique_league(args)]
    load_league(args.database, league)

    (row,) = extract_picked_team(args.database, get_unique_team(args), league)
    team = Team.inventory[row[0]]
    seasons = Season.seasons(league)
    this_season = seasons.pop()
    fixtures = get_fixtures(args.database, team, this_season, args.venue)

    if fixtures:
        nrows = 2
        ncols = 1
        fig, axs = plt.subplots(nrows=nrows, ncols=ncols, figsize=(12, 10), squeeze=False, constrained_layout=True)

        team_color = (54 / 255, 104 / 255, 141 / 255)
        other_team_color = (240 / 255, 88 / 255, 55 / 255)
        neutral_color = (1, 1, 1)
        unknown_color = (1, 1, 1)

        create_results_table(axs[0, 0], team, fixtures, team_color, other_team_color, neutral_color, unknown_color)
        create_league_table(axs[1, 0], this_season, team, team_color, neutral_color, args.venue, args.half)

        title = '{} {}: {}'.format(league.country, league.name, team.name)
        if args.venue == Venue.any:
            title = '{} ({} or {})'.format(title, Venue.home.name, Venue.away.name)
        else:
            title = '{} ({} only)'.format(title, args.venue.name)

        fig.suptitle(title, fontweight='bold', fontsize=14)
        plt.show(block=args.block)
    else:
        warning_message("No data to display for {} in {} {}".format(team.name, league.country, league.name))
Example #2
0
def fill_matrix(matrix: np.ndarray, table_map: TableMap, table: LeagueTable,
                predicates: Predicates, half: Half):
    team_fixtures = table.season.fixtures_per_team()
    for position, row in enumerate(table):
        fixtures = team_fixtures[row.TEAM]
        results = []
        for fixture in fixtures:
            if half == Half.both:
                result = fixture.full_time()
            elif half == Half.first:
                result = fixture.first_half()
            elif half == Half.second:
                result = fixture.second_half()
            else:
                assert False

            if result:
                result = fixture.canonicalise_result(row.TEAM, result)
                results.append(result)
            else:
                warning_message('Ignoring {}'.format(fixture))

        totals = {func: 0 for func in predicates.functions}
        for result in results:
            satisfied = False
            for func in predicates.functions:
                if func(result):
                    totals[func] += 1
                    satisfied = True
                if predicates.mutual_exclusion and satisfied:
                    break

        for j, func in enumerate(predicates.functions):
            i = table_map.get_chunk(position)
            matrix[i, j] += totals[func]
Example #3
0
 def find_team(cls, id_: int, name: str) -> "Team" or None:
     try:
         return cls.inventory[id_]
     except KeyError:
         warning_message(
             "No team '{}' with ID {} in the team inventory.".format(
                 name, id_))
Example #4
0
def main(args: Namespace):
    load_teams(args.database)

    leagues = []
    if args.country:
        for country in args.country:
            leagues.extend([
                code for code, league in league_register.items()
                if league.country == country.capitalize()
            ])

    if args.league:
        leagues.extend(list(args.league))

    if not args.country and not args.league:
        leagues.extend(list(league_register.keys()))

    for league_code in leagues:
        league = league_register[league_code]
        load_league(args.database, league)

        seasons = Season.seasons(league)
        if not seasons:
            messages.warning_message("No season data found")
        else:
            if args.history:
                seasons = seasons[-args.history:]

            if seasons[-1].current:
                this_season = seasons.pop()

                if args.team:
                    teams = []
                    for team_name in get_multiple_teams(args):
                        (row, ) = extract_picked_team(args.database, team_name,
                                                      league)
                        team = Team.inventory[row[0]]
                        teams.append(team)
                else:
                    teams = this_season.teams()

                events = [Event.get(event) for event in args.event]
                historical_data = {}
                for event in events:
                    historical_data[event] = DataUnit(Counter(), seasons)
                    for season in seasons:
                        for team in season.teams():
                            count_events(season, team, args.venue, args.half,
                                         event, args.negate,
                                         historical_data[event])

                analyse_teams(args, league, seasons, this_season, teams,
                              historical_data)
            else:
                messages.error_message(
                    "The current season has not yet started")
Example #5
0
def show_results(league: League, season: Season, results: List[str]):
    matched = []
    for fixture in season.fixtures():
        result = fixture.full_time()
        if result:
            for given_result in results:
                left, right = map(int, given_result.split('-'))
                if left == result.left and right == result.right:
                    matched.append(fixture)
        else:
            messages.warning_message('Ignoring {}'.format(fixture))

    if matched:
        table = LeagueTable(season, Half.both)
        print('>' * 40, season.year, '<' * 40)
        for fixture in matched:
            print('{:<2} vs {:<2}: {}'.format(
                table.team_position(fixture.home_team) + 1,
                table.team_position(fixture.away_team) + 1, fixture))
        print()
Example #6
0
def load_fixture_data(league: League, season: Season):
    fixtures_json = get_fixtures_json(season.id)
    if not fixtures_json.exists():
        messages.warning_message("No fixtures available for season {}".format(
            season.id))
    else:
        messages.verbose_message('Season {}'.format(season.year))
        with fixtures_json.open() as in_file:
            json_text = load(in_file)
            for data in json_text['api']['fixtures']:
                home_id, home_name = get_home_team_data(data)
                if not Team.has_team(home_id):
                    team_row = create_team_row(league, home_id, home_name)
                    create_team_from_row(team_row)

                away_id, away_name = get_away_team_data(data)
                if not Team.has_team(away_id):
                    team_row = create_team_row(league, away_id, away_name)
                    create_team_from_row(team_row)

                create_fixture_from_json(data)
Example #7
0
def create_fixture_from_json(data: Dict):
    if is_regular_fixture(data['round']):
        id_ = int(data['fixture_id'])
        date = datetime.datetime.fromisoformat(data['event_date'])
        season_id = int(data['league_id'])
        home_id = int(data['homeTeam']['team_id'])
        home_name = data['homeTeam']['team_name']
        home_team = Team.find_team(home_id, home_name)
        away_id = int(data['awayTeam']['team_id'])
        away_name = data['awayTeam']['team_name']
        away_team = Team.find_team(away_id, away_name)
        half_time = data['score']['halftime']
        full_time = data['score']['fulltime']
        finished = True if data['status'] == 'Match Finished' else False

        if home_team and away_team:
            fixture = Fixture(id_, date, season_id, home_team, away_team,
                              half_time, full_time, finished,
                              datetime.datetime.now())
            Fixture.inventory[fixture.id] = fixture
    else:
        messages.warning_message('Ignoring fixture. Round is {}.'.format(
            data['round']))
Example #8
0
def main(args: Namespace):
    load_teams(args.database)

    if args.league:
        league = league_register[get_unique_league(args)]
        load_league(args.database, league)

    nrows = 2
    ncols = 4
    fig, axs = plt.subplots(nrows=nrows,
                            ncols=ncols,
                            figsize=(20, 13.5),
                            squeeze=False,
                            constrained_layout=True)

    left_name, right_name = get_multiple_teams(args)
    (row, ) = extract_picked_team(args.database, left_name, league)
    left_team = Team.inventory[row[0]]
    (row, ) = extract_picked_team(args.database, right_name, league)
    right_team = Team.inventory[row[0]]

    left_team_color = (54 / 255, 104 / 255, 141 / 255)
    right_team_color = (240 / 255, 88 / 255, 55 / 255)
    neutral_color = (1, 1, 1)
    unknown_color = (0, 0, 0)
    halves = [Half.first, Half.second, Half.both]

    left_fixtures = get_fixtures(args.database, left_team, right_team)
    right_fixtures = get_fixtures(args.database, right_team, left_team)

    if not left_fixtures and not right_fixtures:
        warning_message("No head-to-head between {} and {}".format(
            left_team.name, right_team.name))
    else:
        if left_fixtures:
            first_half_stats, second_half_stats, full_time_stats = compute_records(
                left_fixtures)
            data = [first_half_stats, second_half_stats, full_time_stats]
            for i, (half, stats) in enumerate(zip(halves, data)):
                create_single_bar(axs[0, i], left_team, left_team_color,
                                  right_team_color, neutral_color, stats)

            create_results_table(axs[0, ncols - 1], left_fixtures, left_team,
                                 left_team_color, right_team_color,
                                 neutral_color, unknown_color)
        else:
            for i in range(ncols):
                fig.delaxes(axs[0, i])

        if right_fixtures:
            first_half_stats, second_half_stats, full_time_stats = compute_records(
                right_fixtures)
            data = [first_half_stats, second_half_stats, full_time_stats]
            for i, (half, stats) in enumerate(zip(halves, data)):
                create_single_bar(axs[1, i], right_team, right_team_color,
                                  left_team_color, neutral_color, stats)
            create_results_table(axs[1, ncols - 1], right_fixtures, right_team,
                                 right_team_color, left_team_color,
                                 neutral_color, unknown_color)
        else:
            for i in range(ncols):
                fig.delaxes(axs[1, i])

        fig.suptitle('Head-to-head: {} vs {}'.format(left_team.name,
                                                     right_team.name),
                     fontweight='bold',
                     fontsize=14)
        plt.show(block=args.block)
Example #9
0
def count_events(season: Season,
                 team: Team,
                 venue: Venue,
                 half: Half,
                 func: Callable,
                 negate: bool,
                 data: DataUnit):
    fixtures = []
    for fixture in season.fixtures():
        if venue == Venue.any:
            if fixture.home_team == team or fixture.away_team == team:
                fixtures.append(fixture)
        elif venue == Venue.away:
            if fixture.away_team == team:
                fixtures.append(fixture)
        elif venue == Venue.home:
            if fixture.home_team == team:
                fixtures.append(fixture)

    sequence = []
    for fixture in fixtures:
        results = []
        if half == Half.both:
            if fixture.full_time() is not None:
                results.append(fixture.full_time())
        elif half == Half.first:
            if fixture.first_half() is not None:
                results.append(fixture.first_half())
            else:
                warning_message('No 1st half result for fixture {}'.format(fixture))
        elif half == Half.second:
            if fixture.second_half() is not None:
                results.append(fixture.second_half())
            else:
                warning_message('No 2nd half result for fixture {}'.format(fixture))
        elif half == Half.separate:
            if fixture.first_half() is not None:
                results.append(fixture.first_half())
            if fixture.second_half() is not None:
                results.append(fixture.second_half())
        else:
            assert False

        if results:
            for result in results:
                if fixture.home_team != team:
                    result = result.reverse()

                if negate:
                    outcome = not func(result)
                else:
                    outcome = func(result)

                if outcome:
                    sequence.append(fixture)
                else:
                    data.last = len(sequence)
                    data.counter[len(sequence)] += 1
                    sequence = []

    if sequence:
        data.last = len(sequence)
        data.counter[len(sequence)] += 1
    else:
        data.last = None