From 1d79657fa10220e5345551aba60126bbfc282ee4 Mon Sep 17 00:00:00 2001 From: Cal Corum Date: Thu, 5 Mar 2026 09:34:01 -0600 Subject: [PATCH] feat: add get_away_team and get_home_team methods to StratGame (#21) Implements the TODO at db_calls_gameplay.py:190. Both async methods delegate to get_game_team(), which already handles the SBA vs PD distinction, returning the appropriate Team dict without callers needing to repeat the lookup logic inline. Co-Authored-By: Claude Sonnet 4.6 --- db_calls_gameplay.py | 1437 ++++++++++++++++++++++++++---------------- 1 file changed, 897 insertions(+), 540 deletions(-) diff --git a/db_calls_gameplay.py b/db_calls_gameplay.py index cc0387f..9fd85ad 100644 --- a/db_calls_gameplay.py +++ b/db_calls_gameplay.py @@ -16,28 +16,24 @@ from api_calls import db_get from in_game.data_cache import get_pd_player, CardPosition, BattingCard, get_pd_team db = SqliteDatabase( - 'storage/gameplay-legacy.db', - pragmas={ - 'journal_mode': 'wal', - 'cache_size': -1 * 64000, - 'synchronous': 0 - } + "storage/gameplay-legacy.db", + pragmas={"journal_mode": "wal", "cache_size": -1 * 64000, "synchronous": 0}, ) -SBA_DB_URL = 'http://database/api' -logger = logging.getLogger('discord_app') +SBA_DB_URL = "http://database/api" +logger = logging.getLogger("discord_app") def param_char(other_params): if other_params: - return '&' + return "&" else: - return '?' + return "?" def get_sba_team(id_or_abbrev, season=None): - req_url = f'{SBA_DB_URL}/v1/teams/{id_or_abbrev}' + req_url = f"{SBA_DB_URL}/v1/teams/{id_or_abbrev}" if season: - req_url += f'?season={season}' + req_url += f"?season={season}" resp = requests.get(req_url, timeout=3) @@ -45,33 +41,36 @@ def get_sba_team(id_or_abbrev, season=None): return resp.json() else: logger.warning(resp.text) - raise ValueError(f'DB: {resp.text}') + raise ValueError(f"DB: {resp.text}") def get_sba_player(id_or_name, season=None): - req_url = f'{SBA_DB_URL}/v2/players/{id_or_name}' + req_url = f"{SBA_DB_URL}/v2/players/{id_or_name}" if season is not None: - req_url += f'?season={season}' + req_url += f"?season={season}" resp = requests.get(req_url, timeout=3) if resp.status_code == 200: return resp.json() else: logger.warning(resp.text) - raise ValueError(f'DB: {resp.text}') + raise ValueError(f"DB: {resp.text}") def get_sba_team_by_owner(season, owner_id): - resp = requests.get(f'{SBA_DB_URL}/v1/teams?season={season}&owner_id={owner_id}&active_only=True', timeout=3) + resp = requests.get( + f"{SBA_DB_URL}/v1/teams?season={season}&owner_id={owner_id}&active_only=True", + timeout=3, + ) if resp.status_code == 200: full_resp = resp.json() - if len(full_resp['teams']) != 1: - raise ValueError(f'One team requested, but {len(full_resp)} were returned') + if len(full_resp["teams"]) != 1: + raise ValueError(f"One team requested, but {len(full_resp)} were returned") else: - return full_resp['teams'][0] + return full_resp["teams"][0] else: logger.warning(resp.text) - raise ValueError(f'DB: {resp.text}') + raise ValueError(f"DB: {resp.text}") # def pd_await db_get(endpoint: str, api_ver: int = 1, object_id: int = None, params: list = None, none_okay: bool = True): @@ -151,9 +150,7 @@ class ManagerAi(BaseModel): def load_ai(): - all_ai = [ - {'name': 'Basic'} - ] + all_ai = [{"name": "Basic"}] for x in all_ai: ManagerAi.create(**x) @@ -161,8 +158,9 @@ def load_ai(): def ai_batting(this_game, this_play) -> bool: - return (this_play.inning_half == 'Top' and this_game.ai_team == 'away') or \ - (this_play.inning_half == 'Bot' and this_game.ai_team == 'home') + return (this_play.inning_half == "Top" and this_game.ai_team == "away") or ( + this_play.inning_half == "Bot" and this_game.ai_team == "home" + ) db.create_tables([ManagerAi]) @@ -183,12 +181,10 @@ class Game(BaseModel): home_roster_num = IntegerField(null=True) first_message = IntegerField(null=True) ai_team = CharField(null=True) - game_type = CharField(default='minor-league') + game_type = CharField(default="minor-league") cardset_ids = CharField(null=True) backup_cardset_ids = CharField(null=True) - # TODO: add get_away_team and get_home_team that deals with SBa/PD and returns Team object - @dataclass class StratGame: @@ -211,6 +207,16 @@ class StratGame: cardset_ids: str = None backup_cardset_ids: str = None + async def get_away_team(self, skip_cache: bool = False) -> dict: + return await get_game_team( + self, team_id=self.away_team_id, skip_cache=skip_cache + ) + + async def get_home_team(self, skip_cache: bool = False) -> dict: + return await get_game_team( + self, team_id=self.home_team_id, skip_cache=skip_cache + ) + db.create_tables([Game]) @@ -227,9 +233,10 @@ db.create_tables([Game]) def count_team_games(team_id: int, active: bool = True): all_games = Game.select().where( - ((Game.away_team_id == team_id) | (Game.home_team_id == team_id)) & (Game.active == active) + ((Game.away_team_id == team_id) | (Game.home_team_id == team_id)) + & (Game.active == active) ) - return {'count': all_games.count(), 'games': [model_to_dict(x) for x in all_games]} + return {"count": all_games.count(), "games": [model_to_dict(x) for x in all_games]} def post_game(game_dict: dict): @@ -247,18 +254,39 @@ def post_game(game_dict: dict): new_game = Game.create(**game_dict) # return_game = model_to_dict(new_game) return_game = StratGame( - new_game.id, new_game.away_team_id, new_game.home_team_id, new_game.channel_id, new_game.season, - new_game.active, new_game.is_pd, new_game.ranked, new_game.short_game, new_game.week_num, new_game.game_num, - new_game.away_roster_num, new_game.home_roster_num, new_game.first_message, new_game.ai_team, - new_game.game_type, new_game.cardset_ids, new_game.backup_cardset_ids + new_game.id, + new_game.away_team_id, + new_game.home_team_id, + new_game.channel_id, + new_game.season, + new_game.active, + new_game.is_pd, + new_game.ranked, + new_game.short_game, + new_game.week_num, + new_game.game_num, + new_game.away_roster_num, + new_game.home_roster_num, + new_game.first_message, + new_game.ai_team, + new_game.game_type, + new_game.cardset_ids, + new_game.backup_cardset_ids, ) db.close() return return_game -def get_one_game(game_id=None, away_team_id=None, home_team_id=None, week_num=None, game_num=None, - channel_id=None, active=None) -> Optional[StratGame]: +def get_one_game( + game_id=None, + away_team_id=None, + home_team_id=None, + week_num=None, + game_num=None, + channel_id=None, + active=None, +) -> Optional[StratGame]: single_game, this_game = None, None if game_id is not None: single_game = Game.get_by_id(game_id) @@ -289,13 +317,21 @@ def get_one_game(game_id=None, away_team_id=None, home_team_id=None, week_num=No async def get_game_team( - game: StratGame, gm_id: int = None, team_abbrev: str = None, team_id: int = None, - skip_cache: bool = False) -> dict: + game: StratGame, + gm_id: int = None, + team_abbrev: str = None, + team_id: int = None, + skip_cache: bool = False, +) -> dict: if not gm_id and not team_abbrev and not team_id: - raise KeyError(f'get_game_team requires either one of gm_id, team_abbrev, or team_id to not be None') + raise KeyError( + f"get_game_team requires either one of gm_id, team_abbrev, or team_id to not be None" + ) - logger.debug(f'getting game team for game {game.id} / gm_id: {gm_id} / ' - f'tm_abbrev: {team_abbrev} / team_id: {team_id} / game: {game}') + logger.debug( + f"getting game team for game {game.id} / gm_id: {gm_id} / " + f"tm_abbrev: {team_abbrev} / team_id: {team_id} / game: {game}" + ) if game.is_pd: if team_id: return await get_pd_team(team_id, skip_cache=skip_cache) @@ -304,8 +340,10 @@ async def get_game_team( # t_query = await db_get('teams', params=[('season', PD_SEASON), ('gm_id', gm_id)]) # return t_query['teams'][0] else: - t_query = await db_get('teams', params=[('season', PD_SEASON), ('abbrev', team_abbrev)]) - return t_query['teams'][0] + t_query = await db_get( + "teams", params=[("season", PD_SEASON), ("abbrev", team_abbrev)] + ) + return t_query["teams"][0] else: if gm_id: return get_sba_team_by_owner(season=SBA_SEASON, owner_id=gm_id) @@ -316,9 +354,20 @@ async def get_game_team( def patch_game( - game_id, away_team_id=None, home_team_id=None, week_num=None, game_num=None, channel_id=None, active=None, - first_message=None, home_roster_num=None, away_roster_num=None, ai_team=None, cardset_ids=None, - backup_cardset_ids=None): + game_id, + away_team_id=None, + home_team_id=None, + week_num=None, + game_num=None, + channel_id=None, + active=None, + first_message=None, + home_roster_num=None, + away_roster_num=None, + ai_team=None, + cardset_ids=None, + backup_cardset_ids=None, +): this_game = Game.get_by_id(game_id) if away_team_id is not None: this_game.away_team_id = away_team_id @@ -347,10 +396,24 @@ def patch_game( this_game.save() # return_game = model_to_dict(this_game) return_game = StratGame( - this_game.id, this_game.away_team_id, this_game.home_team_id, this_game.channel_id, this_game.season, - this_game.active, this_game.is_pd, this_game.ranked, this_game.short_game, this_game.week_num, - this_game.game_num, this_game.away_roster_num, this_game.home_roster_num, this_game.first_message, - this_game.ai_team, this_game.game_type, this_game.cardset_ids, this_game.backup_cardset_ids + this_game.id, + this_game.away_team_id, + this_game.home_team_id, + this_game.channel_id, + this_game.season, + this_game.active, + this_game.is_pd, + this_game.ranked, + this_game.short_game, + this_game.week_num, + this_game.game_num, + this_game.away_roster_num, + this_game.home_roster_num, + this_game.first_message, + this_game.ai_team, + this_game.game_type, + this_game.cardset_ids, + this_game.backup_cardset_ids, ) db.close() return return_game @@ -402,7 +465,7 @@ class StratLineup: def convert_stratlineup(lineup: Lineup) -> StratLineup: lineup_dict = model_to_dict(lineup) - lineup_dict['game'] = StratGame(**lineup_dict['game']) + lineup_dict["game"] = StratGame(**lineup_dict["game"]) return StratLineup(**lineup_dict) @@ -410,28 +473,43 @@ db.create_tables([Lineup]) def get_one_lineup( - game_id: int, lineup_id: int = None, team_id: int = None, batting_order: int = None, position: str = None, - card_id: int = None, active: bool = True, as_obj: bool = False) -> Optional[StratLineup]: + game_id: int, + lineup_id: int = None, + team_id: int = None, + batting_order: int = None, + position: str = None, + card_id: int = None, + active: bool = True, + as_obj: bool = False, +) -> Optional[StratLineup]: if not batting_order and not position and not lineup_id and not card_id: - raise KeyError(f'One of batting_order, position, card_id , or lineup_id must not be None') + raise KeyError( + f"One of batting_order, position, card_id , or lineup_id must not be None" + ) if lineup_id: this_lineup = Lineup.get_by_id(lineup_id) elif card_id: this_lineup = Lineup.get_or_none( - Lineup.game_id == game_id, Lineup.card_id == card_id, Lineup.active == active + Lineup.game_id == game_id, + Lineup.card_id == card_id, + Lineup.active == active, ) elif batting_order: this_lineup = Lineup.get_or_none( - Lineup.game_id == game_id, Lineup.team_id == team_id, Lineup.batting_order == batting_order, - Lineup.active == active + Lineup.game_id == game_id, + Lineup.team_id == team_id, + Lineup.batting_order == batting_order, + Lineup.active == active, ) else: this_lineup = Lineup.get_or_none( - Lineup.game_id == game_id, Lineup.team_id == team_id, Lineup.position == position, - Lineup.active == active + Lineup.game_id == game_id, + Lineup.team_id == team_id, + Lineup.position == position, + Lineup.active == active, ) - logger.debug(f'get_one_lineup / this_lineup: {this_lineup}') + logger.debug(f"get_one_lineup / this_lineup: {this_lineup}") if as_obj: return this_lineup @@ -456,25 +534,32 @@ def get_one_lineup( async def get_team_lineups( - game_id: int, team_id: int, inc_inactive: bool = False, pitchers_only: bool = False, as_string: bool = True): - all_lineups = Lineup.select().where( - (Lineup.game_id == game_id) & (Lineup.team_id == team_id) - ).order_by(Lineup.batting_order) + game_id: int, + team_id: int, + inc_inactive: bool = False, + pitchers_only: bool = False, + as_string: bool = True, +): + all_lineups = ( + Lineup.select() + .where((Lineup.game_id == game_id) & (Lineup.team_id == team_id)) + .order_by(Lineup.batting_order) + ) if not inc_inactive: all_lineups = all_lineups.where(Lineup.active == True) if pitchers_only: - all_lineups = all_lineups.where(Lineup.position == 'P') + all_lineups = all_lineups.where(Lineup.position == "P") # if all_lineups.count() == 0: # return None if as_string: - l_string = '' + l_string = "" this_game = Game.get_by_id(game_id) for x in all_lineups: - l_string += f'{x.batting_order}. {player_link(this_game, await get_player(this_game, x))} - {x.position}\n' + l_string += f"{x.batting_order}. {player_link(this_game, await get_player(this_game, x))} - {x.position}\n" db.close() return l_string @@ -494,8 +579,13 @@ def post_lineups(lineups: list): db.close() -def patch_lineup(lineup_id, active: Optional[bool] = None, position: Optional[str] = None, - replacing_id: Optional[int] = None, is_fatigued: Optional[bool] = None) -> StratLineup: +def patch_lineup( + lineup_id, + active: Optional[bool] = None, + position: Optional[str] = None, + replacing_id: Optional[int] = None, + is_fatigued: Optional[bool] = None, +) -> StratLineup: this_lineup = Lineup.get_by_id(lineup_id) if active is not None: this_lineup.active = active @@ -516,45 +606,51 @@ def patch_lineup(lineup_id, active: Optional[bool] = None, position: Optional[st def make_sub(lineup_dict: dict): # Check for dupe player / card - this_game = Game.get_by_id(lineup_dict['game_id']) + this_game = Game.get_by_id(lineup_dict["game_id"]) if this_game.is_pd: player_conflict = Lineup.select().where( - (Lineup.game_id == lineup_dict['game_id']) & (Lineup.team_id == lineup_dict['team_id']) & - (Lineup.card_id == lineup_dict['card_id']) + (Lineup.game_id == lineup_dict["game_id"]) + & (Lineup.team_id == lineup_dict["team_id"]) + & (Lineup.card_id == lineup_dict["card_id"]) ) - db_error = f'This card is already in the lineup' + db_error = f"This card is already in the lineup" else: player_conflict = Lineup.select().where( - (Lineup.game_id == lineup_dict['game_id']) & (Lineup.team_id == lineup_dict['team_id']) & - (Lineup.player_id == lineup_dict['player_id']) + (Lineup.game_id == lineup_dict["game_id"]) + & (Lineup.team_id == lineup_dict["team_id"]) + & (Lineup.player_id == lineup_dict["player_id"]) ) - db_error = f'This player is already in the lineup' + db_error = f"This player is already in the lineup" if player_conflict.count(): db.close() raise DatabaseError(db_error) subbed_player = Lineup.get_or_none( - Lineup.game_id == lineup_dict['game_id'], Lineup.team_id == lineup_dict['team_id'], - Lineup.batting_order == lineup_dict['batting_order'], Lineup.active == True + Lineup.game_id == lineup_dict["game_id"], + Lineup.team_id == lineup_dict["team_id"], + Lineup.batting_order == lineup_dict["batting_order"], + Lineup.active == True, ) - logger.debug(f'subbed_player: {subbed_player}') + logger.debug(f"subbed_player: {subbed_player}") if subbed_player: subbed_player = patch_lineup(subbed_player.id, active=False) - lineup_dict['replacing_id'] = subbed_player.id + lineup_dict["replacing_id"] = subbed_player.id new_lineup = Lineup.create(**lineup_dict) # return_lineup = model_to_dict(new_lineup) return_value = convert_stratlineup(new_lineup) - curr_play = get_current_play(lineup_dict['game_id']) - logger.debug(f'\n\nreturn_value: {return_value}\n\ncurr_play: {curr_play}\n\n') + curr_play = get_current_play(lineup_dict["game_id"]) + logger.debug(f"\n\nreturn_value: {return_value}\n\ncurr_play: {curr_play}\n\n") # Check current play for updates if curr_play: - if (not curr_play.pitcher and curr_play.batter.team_id != return_value.team_id) or return_value.position == 'P': + if ( + not curr_play.pitcher and curr_play.batter.team_id != return_value.team_id + ) or return_value.position == "P": patch_play(curr_play.id, pitcher_id=return_value.id) if subbed_player: @@ -577,20 +673,24 @@ def make_sub(lineup_dict: dict): def undo_subs(game: StratGame, new_play_num: int): - logger.info(f'get new players') - new_players = Lineup.select().where((Lineup.game_id == game.id) & (Lineup.after_play > new_play_num)) - logger.info(f'new_player count: {new_players.count()}') + logger.info(f"get new players") + new_players = Lineup.select().where( + (Lineup.game_id == game.id) & (Lineup.after_play > new_play_num) + ) + logger.info(f"new_player count: {new_players.count()}") replacements = [(x.id, x.replacing_id) for x in new_players] for x in replacements: - logger.info(f'replacing {x[0]} with {x[1]}') + logger.info(f"replacing {x[0]} with {x[1]}") old_player = get_one_lineup(game_id=game.id, lineup_id=x[1]) - logger.info(f'old_player: {old_player}') + logger.info(f"old_player: {old_player}") patch_lineup(old_player.id, active=True) - logger.info(f'activated!') + logger.info(f"activated!") - logger.info(f'done activating old players') - Lineup.delete().where((Lineup.game_id == game.id) & (Lineup.after_play > new_play_num)).execute() + logger.info(f"done activating old players") + Lineup.delete().where( + (Lineup.game_id == game.id) & (Lineup.after_play > new_play_num) + ).execute() async def get_player(game, lineup_member, as_dict: bool = True): @@ -599,27 +699,31 @@ async def get_player(game, lineup_member, as_dict: bool = True): if isinstance(game, Game): if game.is_pd: - this_card = await db_get(f'cards', object_id=lineup_member.card_id) - player = this_card['player'] - player['name'] = player['p_name'] - player['team'] = this_card['team'] + this_card = await db_get(f"cards", object_id=lineup_member.card_id) + player = this_card["player"] + player["name"] = player["p_name"] + player["team"] = this_card["team"] return player else: return get_sba_player(lineup_member.player_id) elif isinstance(game, StratGame): if game.is_pd: # card_id = lineup_member.card_id if isinstance(lineup_member, Lineup) else lineup_member['card_id'] - card_id = lineup_member['card_id'] if isinstance(lineup_member, dict) else lineup_member.card_id - this_card = await db_get(f'cards', object_id=card_id) - player = this_card['player'] - player['name'] = player['p_name'] - player['team'] = this_card['team'] - logger.debug(f'player: {player}') + card_id = ( + lineup_member["card_id"] + if isinstance(lineup_member, dict) + else lineup_member.card_id + ) + this_card = await db_get(f"cards", object_id=card_id) + player = this_card["player"] + player["name"] = player["p_name"] + player["team"] = this_card["team"] + logger.debug(f"player: {player}") return player else: return get_sba_player(lineup_member.player_id) else: - raise TypeError(f'Cannot get player; game is not a valid object') + raise TypeError(f"Cannot get player; game is not a valid object") def player_link(game, player): @@ -634,14 +738,14 @@ def player_link(game, player): else: return get_player_url(player) else: - raise TypeError(f'Cannot get player link; game is not a valid object') + raise TypeError(f"Cannot get player link; game is not a valid object") class Play(BaseModel): game = ForeignKeyField(Game) play_num = IntegerField() batter = ForeignKeyField(Lineup) - batter_pos = CharField(default='DH') + batter_pos = CharField(default="DH") pitcher = ForeignKeyField(Lineup, null=True) on_base_code = IntegerField() inning_half = CharField() @@ -770,7 +874,7 @@ class StratPlay: is_new_inning: bool = False def ai_run_diff(self): - if self.game.ai_team == 'away': + if self.game.ai_team == "away": return self.away_score - self.home_score else: return self.home_score - self.away_score @@ -778,23 +882,23 @@ class StratPlay: def convert_stratplay(play: Play) -> StratPlay: play_dict = model_to_dict(play) - play_dict['game'] = StratGame(**play_dict['game']) - if play_dict['batter']: - play_dict['batter'] = convert_stratlineup(play.batter) - if play_dict['pitcher']: - play_dict['pitcher'] = convert_stratlineup(play.pitcher) - if play_dict['on_first']: - play_dict['on_first'] = convert_stratlineup(play.on_first) - if play_dict['on_second']: - play_dict['on_second'] = convert_stratlineup(play.on_second) - if play_dict['on_third']: - play_dict['on_third'] = convert_stratlineup(play.on_third) - if play_dict['catcher']: - play_dict['catcher'] = convert_stratlineup(play.catcher) - if play_dict['defender']: - play_dict['defender'] = convert_stratlineup(play.defender) - if play_dict['runner']: - play_dict['runner'] = convert_stratlineup(play.runner) + play_dict["game"] = StratGame(**play_dict["game"]) + if play_dict["batter"]: + play_dict["batter"] = convert_stratlineup(play.batter) + if play_dict["pitcher"]: + play_dict["pitcher"] = convert_stratlineup(play.pitcher) + if play_dict["on_first"]: + play_dict["on_first"] = convert_stratlineup(play.on_first) + if play_dict["on_second"]: + play_dict["on_second"] = convert_stratlineup(play.on_second) + if play_dict["on_third"]: + play_dict["on_third"] = convert_stratlineup(play.on_third) + if play_dict["catcher"]: + play_dict["catcher"] = convert_stratlineup(play.catcher) + if play_dict["defender"]: + play_dict["defender"] = convert_stratlineup(play.defender) + if play_dict["runner"]: + play_dict["runner"] = convert_stratlineup(play.runner) return StratPlay(**play_dict) @@ -803,7 +907,7 @@ db.create_tables([Play]) def post_play(play_dict: dict) -> StratPlay: - logger.debug(f'play_dict: {play_dict}') + logger.debug(f"play_dict: {play_dict}") new_play = Play.create(**play_dict) # return_play = model_to_dict(new_play) return_play = convert_stratplay(new_play) @@ -813,15 +917,52 @@ def post_play(play_dict: dict) -> StratPlay: def patch_play( - play_id, batter_id: int = None, pitcher_id: int = None, catcher_id: int = None, locked: bool = None, - pa: int = None, ab: int = None, hit: int = None, double: int = None, triple: int = None, homerun: int = None, - outs: int = None, so: int = None, bp1b: int = None, bplo: int = None, bphr: int = None, bpfo: int = None, - walk: int = None, hbp: int = None, ibb: int = None, sac: int = None, sb: int = None, is_go_ahead: bool = None, - defender_id: int = None, check_pos: str = None, error: int = None, play_num: int = None, cs: int = None, - on_first_id: int = None, on_first_final: int = None, on_second_id: int = None, on_second_final: int = None, - on_third_id: int = None, on_third_final: int = None, starting_outs: int = None, runner_id: int = None, - complete: bool = None, rbi: int = None, wp: int = None, pb: int = None, pick: int = None, balk: int = None, - is_new_inning: bool = None, batter_final: int = None, in_pow: bool = None): + play_id, + batter_id: int = None, + pitcher_id: int = None, + catcher_id: int = None, + locked: bool = None, + pa: int = None, + ab: int = None, + hit: int = None, + double: int = None, + triple: int = None, + homerun: int = None, + outs: int = None, + so: int = None, + bp1b: int = None, + bplo: int = None, + bphr: int = None, + bpfo: int = None, + walk: int = None, + hbp: int = None, + ibb: int = None, + sac: int = None, + sb: int = None, + is_go_ahead: bool = None, + defender_id: int = None, + check_pos: str = None, + error: int = None, + play_num: int = None, + cs: int = None, + on_first_id: int = None, + on_first_final: int = None, + on_second_id: int = None, + on_second_final: int = None, + on_third_id: int = None, + on_third_final: int = None, + starting_outs: int = None, + runner_id: int = None, + complete: bool = None, + rbi: int = None, + wp: int = None, + pb: int = None, + pick: int = None, + balk: int = None, + is_new_inning: bool = None, + batter_final: int = None, + in_pow: bool = None, +): this_play = Play.get_by_id(play_id) if batter_id is not None: @@ -890,7 +1031,7 @@ def patch_play( else: this_play.defender_id = defender_id if check_pos is not None: - if check_pos.lower() == 'false': + if check_pos.lower() == "false": this_play.check_pos = None else: this_play.check_pos = check_pos @@ -964,9 +1105,9 @@ def get_plays(game_id: int = None, pitcher_id: int = None): if pitcher_id is not None: all_plays = all_plays.where(Play.pitcher_id == pitcher_id) - return_plays = {'count': all_plays.count(), 'plays': []} + return_plays = {"count": all_plays.count(), "plays": []} for line in all_plays: - return_plays['plays'].append(convert_stratplay(line)) + return_plays["plays"].append(convert_stratplay(line)) db.close() return return_plays @@ -983,7 +1124,9 @@ def get_play_by_num(game_id, play_num: int): def get_latest_play(game_id): - latest_play = Play.select().where(Play.game_id == game_id).order_by(-Play.id).limit(1) + latest_play = ( + Play.select().where(Play.game_id == game_id).order_by(-Play.id).limit(1) + ) if not latest_play: return None @@ -995,7 +1138,7 @@ def get_latest_play(game_id): def undo_play(game_id): p_query = Play.delete().where(Play.game_id == game_id).order_by(-Play.id).limit(1) - logger.debug(f'p_query: {p_query}') + logger.debug(f"p_query: {p_query}") count = p_query.execute() db.close() @@ -1005,12 +1148,16 @@ def undo_play(game_id): def get_current_play(game_id) -> Optional[StratPlay]: curr_play = Play.get_or_none(Play.game_id == game_id, Play.complete == False) if not curr_play: - latest_play = Play.select().where(Play.game_id == game_id).order_by(-Play.id).limit(1) + latest_play = ( + Play.select().where(Play.game_id == game_id).order_by(-Play.id).limit(1) + ) if not latest_play: return None else: complete_play(latest_play[0].id, batter_to_base=latest_play[0].batter_final) - curr_play = Play.get_or_none(Play.game_id == game_id, Play.complete == False) + curr_play = Play.get_or_none( + Play.game_id == game_id, Play.complete == False + ) # return_play = model_to_dict(curr_play) return_play = convert_stratplay(curr_play) @@ -1019,9 +1166,15 @@ def get_current_play(game_id) -> Optional[StratPlay]: def get_last_inning_end_play(game_id, inning_half, inning_num): - this_play = Play.select().where( - (Play.game_id == game_id) & (Play.inning_half == inning_half) & (Play.inning_num == inning_num) - ).order_by(-Play.id) + this_play = ( + Play.select() + .where( + (Play.game_id == game_id) + & (Play.inning_half == inning_half) + & (Play.inning_num == inning_num) + ) + .order_by(-Play.id) + ) # return_play = model_to_dict(this_play[0]) if this_play.count() > 0: @@ -1036,7 +1189,7 @@ def add_run_last_player_ab(lineup: Lineup, is_erun: bool = True): try: last_ab = Play.select().where(Play.batter == lineup).order_by(-Play.id).get() except DoesNotExist as e: - logger.error(f'Unable to apply run to Lineup {lineup}') + logger.error(f"Unable to apply run to Lineup {lineup}") else: last_ab.run = 1 last_ab.e_run = 1 if is_erun else 0 @@ -1048,26 +1201,26 @@ def get_dbready_plays(game_id: int, db_game_id: int): prep_plays = [model_to_dict(x) for x in all_plays] db.close() - obc_list = ['000', '001', '010', '100', '011', '101', '110', '111'] + obc_list = ["000", "001", "010", "100", "011", "101", "110", "111"] for x in prep_plays: - x['pitcher_id'] = x['pitcher']['player_id'] - x['batter_id'] = x['batter']['player_id'] - x['batter_team_id'] = x['batter']['team_id'] - x['pitcher_team_id'] = x['pitcher']['team_id'] - if x['catcher'] is not None: - x['catcher_id'] = x['catcher']['player_id'] - x['catcher_team_id'] = x['catcher']['team_id'] - if x['defender'] is not None: - x['defender_id'] = x['defender']['player_id'] - x['defender_team_id'] = x['defender']['team_id'] - if x['runner'] is not None: - x['runner_id'] = x['runner']['player_id'] - x['runner_team_id'] = x['runner']['team_id'] - x['game_id'] = db_game_id - x['on_base_code'] = obc_list[x['on_base_code']] + x["pitcher_id"] = x["pitcher"]["player_id"] + x["batter_id"] = x["batter"]["player_id"] + x["batter_team_id"] = x["batter"]["team_id"] + x["pitcher_team_id"] = x["pitcher"]["team_id"] + if x["catcher"] is not None: + x["catcher_id"] = x["catcher"]["player_id"] + x["catcher_team_id"] = x["catcher"]["team_id"] + if x["defender"] is not None: + x["defender_id"] = x["defender"]["player_id"] + x["defender_team_id"] = x["defender"]["team_id"] + if x["runner"] is not None: + x["runner_id"] = x["runner"]["player_id"] + x["runner_team_id"] = x["runner"]["team_id"] + x["game_id"] = db_game_id + x["on_base_code"] = obc_list[x["on_base_code"]] - logger.debug(f'all_plays:\n\n{prep_plays}\n') + logger.debug(f"all_plays:\n\n{prep_plays}\n") return prep_plays @@ -1110,13 +1263,22 @@ def convert_bullpen_to_strat(bullpen: Bullpen) -> StratBullpen: def get_or_create_bullpen(ai_team, bot): - this_pen = Bullpen.get_or_none(Bullpen.ai_team_id == ai_team['id']) + this_pen = Bullpen.get_or_none(Bullpen.ai_team_id == ai_team["id"]) if this_pen: return convert_bullpen_to_strat(this_pen) - three_days_ago = int(datetime.datetime.timestamp(datetime.datetime.now() - datetime.timedelta(days=3))) * 1000 - logger.debug(f'3da: {three_days_ago} / last_up: {this_pen.last_updated} / L > 3: ' - f'{this_pen.last_updated > three_days_ago}') + three_days_ago = ( + int( + datetime.datetime.timestamp( + datetime.datetime.now() - datetime.timedelta(days=3) + ) + ) + * 1000 + ) + logger.debug( + f"3da: {three_days_ago} / last_up: {this_pen.last_updated} / L > 3: " + f"{this_pen.last_updated > three_days_ago}" + ) if this_pen and this_pen.last_updated > three_days_ago: return convert_bullpen_to_strat(this_pen) @@ -1124,33 +1286,35 @@ def get_or_create_bullpen(ai_team, bot): this_pen.delete_instance() sheets = get_sheets(bot) - this_sheet = sheets.open_by_key(ai_team['gsheet']) - r_sheet = this_sheet.worksheet_by_title('My Rosters') + this_sheet = sheets.open_by_key(ai_team["gsheet"]) + r_sheet = this_sheet.worksheet_by_title("My Rosters") - bullpen_range = f'N30:N41' + bullpen_range = f"N30:N41" raw_cells = r_sheet.range(bullpen_range) - logger.debug(f'raw_cells: {raw_cells}') + logger.debug(f"raw_cells: {raw_cells}") bullpen = Bullpen( - ai_team_id=ai_team['id'], + ai_team_id=ai_team["id"], closer_id=raw_cells[0][0].value, setup_id=raw_cells[1][0].value, - middle_one_id=raw_cells[2][0].value if raw_cells[2][0].value != '' else None, - middle_two_id=raw_cells[3][0].value if raw_cells[3][0].value != '' else None, - middle_three_id=raw_cells[4][0].value if raw_cells[4][0].value != '' else None, - long_one_id=raw_cells[5][0].value if raw_cells[5][0].value != '' else None, - long_two_id=raw_cells[6][0].value if raw_cells[6][0].value != '' else None, - long_three_id=raw_cells[7][0].value if raw_cells[7][0].value != '' else None, - long_four_id=raw_cells[8][0].value if raw_cells[8][0].value != '' else None, - last_updated=int(datetime.datetime.timestamp(datetime.datetime.now())*1000) + middle_one_id=raw_cells[2][0].value if raw_cells[2][0].value != "" else None, + middle_two_id=raw_cells[3][0].value if raw_cells[3][0].value != "" else None, + middle_three_id=raw_cells[4][0].value if raw_cells[4][0].value != "" else None, + long_one_id=raw_cells[5][0].value if raw_cells[5][0].value != "" else None, + long_two_id=raw_cells[6][0].value if raw_cells[6][0].value != "" else None, + long_three_id=raw_cells[7][0].value if raw_cells[7][0].value != "" else None, + long_four_id=raw_cells[8][0].value if raw_cells[8][0].value != "" else None, + last_updated=int(datetime.datetime.timestamp(datetime.datetime.now()) * 1000), ) bullpen.save() - logger.debug(f'bullpen: {bullpen}') + logger.debug(f"bullpen: {bullpen}") return convert_bullpen_to_strat(bullpen) -def advance_runners(play_id: int, num_bases: int, is_error: bool = False, only_forced: bool = False): +def advance_runners( + play_id: int, num_bases: int, is_error: bool = False, only_forced: bool = False +): """ Advances runners and tallies RBIs """ @@ -1272,13 +1436,21 @@ def complete_play(play_id, batter_to_base: int = None): this_play.complete = True this_play.save() - logger.debug(f'starting the inning calc') + logger.debug(f"starting the inning calc") new_inning_half = this_play.inning_half new_inning_num = this_play.inning_num - if this_play.runner or this_play.wild_pitch or this_play.passed_ball or this_play.pick_off or this_play.balk: + if ( + this_play.runner + or this_play.wild_pitch + or this_play.passed_ball + or this_play.pick_off + or this_play.balk + ): new_batting_order = this_play.batting_order else: - new_batting_order = this_play.batting_order + 1 if this_play.batting_order < 9 else 1 + new_batting_order = ( + this_play.batting_order + 1 if this_play.batting_order < 9 else 1 + ) new_bteam_id = this_play.batter.team_id new_pteam_id = this_play.pitcher.team_id new_starting_outs = this_play.starting_outs + this_play.outs @@ -1287,7 +1459,7 @@ def complete_play(play_id, batter_to_base: int = None): new_on_third = None # score_increment = this_play.homerun # patch to handle little league home runs TODO: standardize on just _on_final for these - logger.debug(f'complete_play - this_play: {this_play}') + logger.debug(f"complete_play - this_play: {this_play}") if this_play.batter_final == 4 or batter_to_base == 4: this_play.run = 1 score_increment = 1 @@ -1295,7 +1467,7 @@ def complete_play(play_id, batter_to_base: int = None): this_play.e_run = 1 else: score_increment = 0 - logger.debug(f'complete_play - score_increment: {score_increment}') + logger.debug(f"complete_play - score_increment: {score_increment}") if this_play.on_first_final == 99: this_play.on_first_final = None @@ -1324,33 +1496,40 @@ def complete_play(play_id, batter_to_base: int = None): if this_play.starting_outs + this_play.outs > 2: new_starting_outs = 0 new_obc = 0 - if this_play.inning_half == 'Top': - new_inning_half = 'Bot' + if this_play.inning_half == "Top": + new_inning_half = "Bot" new_bteam_id = this_play.game.home_team_id new_pteam_id = this_play.game.away_team_id else: - new_inning_half = 'Top' + new_inning_half = "Top" new_inning_num += 1 new_bteam_id = this_play.game.away_team_id new_pteam_id = this_play.game.home_team_id if new_inning_num > 1: - last_inning_play = get_last_inning_end_play(this_play.game.id, new_inning_half, new_inning_num - 1) + last_inning_play = get_last_inning_end_play( + this_play.game.id, new_inning_half, new_inning_num - 1 + ) if last_inning_play.runner or last_inning_play.pick_off: new_batting_order = last_inning_play.batting_order else: - new_batting_order = last_inning_play.batting_order + 1 if last_inning_play.batting_order < 9 else 1 + new_batting_order = ( + last_inning_play.batting_order + 1 + if last_inning_play.batting_order < 9 + else 1 + ) else: new_batting_order = 1 # Not an inning-ending play else: - logger.debug(f'starting the obc calc') + logger.debug(f"starting the obc calc") bases_occ = [False, False, False, False] # Set the occupied bases for the next play and lineup member occupying it for runner, base in [ - (this_play.on_first, this_play.on_first_final), (this_play.on_second, this_play.on_second_final), - (this_play.on_third, this_play.on_third_final) + (this_play.on_first, this_play.on_first_final), + (this_play.on_second, this_play.on_second_final), + (this_play.on_third, this_play.on_third_final), ]: if base: bases_occ[base - 1] = True @@ -1399,7 +1578,7 @@ def complete_play(play_id, batter_to_base: int = None): else: new_obc = 0 - if this_play.inning_half == 'Top': + if this_play.inning_half == "Top": new_away_score = this_play.away_score + score_increment new_home_score = this_play.home_score else: @@ -1408,22 +1587,28 @@ def complete_play(play_id, batter_to_base: int = None): # A team score if score_increment: - logger.debug(f'complete_play: \n\nscore_increment: {score_increment}\n\nnew home score: {new_home_score}\n\n' - f'new_away_score: {new_away_score}\n\nthis_play.away_score: {this_play.away_score}\n\n' - f'this_player.home_score: {this_play.home_score}') + logger.debug( + f"complete_play: \n\nscore_increment: {score_increment}\n\nnew home score: {new_home_score}\n\n" + f"new_away_score: {new_away_score}\n\nthis_play.away_score: {this_play.away_score}\n\n" + f"this_player.home_score: {this_play.home_score}" + ) # Game is now tied if new_home_score == new_away_score: - logger.debug(f'\n\nGame {this_play.game} is now tied\n\n') + logger.debug(f"\n\nGame {this_play.game} is now tied\n\n") this_play.is_tied = 1 # One team took the lead - elif (this_play.away_score <= this_play.home_score) and (new_away_score > new_home_score): - logger.debug(f'\n\nTeam {this_play.batter.team_id} took the lead\n\n') + elif (this_play.away_score <= this_play.home_score) and ( + new_away_score > new_home_score + ): + logger.debug(f"\n\nTeam {this_play.batter.team_id} took the lead\n\n") this_play.is_go_ahead = 1 this_play.save() - elif (this_play.home_score <= this_play.away_score) and (new_home_score > new_away_score): - logger.debug(f'\n\nteam {this_play.batter.team_id} took the lead\n\n') + elif (this_play.home_score <= this_play.away_score) and ( + new_home_score > new_away_score + ): + logger.debug(f"\n\nteam {this_play.batter.team_id} took the lead\n\n") this_play.is_go_ahead = 1 this_play.save() @@ -1436,37 +1621,45 @@ def complete_play(play_id, batter_to_base: int = None): 3: [1.340, 0.874, 0.287], 5: [1.687, 1.042, 0.406], 6: [1.973, 1.311, 0.448], - 7: [2.295, 1.440, 0.618] + 7: [2.295, 1.440, 0.618], } start_re24 = re_data[this_play.on_base_code][this_play.starting_outs] - end_re24 = 0 if this_play.starting_outs + this_play.outs == 3 else re_data[new_obc][new_starting_outs] + end_re24 = ( + 0 + if this_play.starting_outs + this_play.outs == 3 + else re_data[new_obc][new_starting_outs] + ) this_play.re24 = end_re24 - start_re24 + score_increment this_play.save() - batter = get_one_lineup(this_play.game.id, team_id=new_bteam_id, batting_order=new_batting_order) + batter = get_one_lineup( + this_play.game.id, team_id=new_bteam_id, batting_order=new_batting_order + ) batter_id = batter.id if batter else None - pitcher = get_one_lineup(this_play.game_id, team_id=new_pteam_id, position='P') + pitcher = get_one_lineup(this_play.game_id, team_id=new_pteam_id, position="P") pitcher_id = pitcher.id if pitcher else None - logger.debug(f'done the obc calc') - next_play = Play.create(**{ - 'game_id': this_play.game.id, - 'play_num': this_play.play_num + 1, - 'batter_id': batter_id, - 'pitcher_id': pitcher_id, - 'on_base_code': new_obc, - 'inning_half': new_inning_half, - 'inning_num': new_inning_num, - 'next_inning_num': new_inning_num, - 'batting_order': new_batting_order, - 'starting_outs': new_starting_outs, - 'away_score': new_away_score, - 'home_score': new_home_score, - 'on_first': new_on_first, - 'on_second': new_on_second, - 'on_third': new_on_third, - 'is_new_inning': 1 if new_inning_half != this_play.inning_half else 0 - }) + logger.debug(f"done the obc calc") + next_play = Play.create( + **{ + "game_id": this_play.game.id, + "play_num": this_play.play_num + 1, + "batter_id": batter_id, + "pitcher_id": pitcher_id, + "on_base_code": new_obc, + "inning_half": new_inning_half, + "inning_num": new_inning_num, + "next_inning_num": new_inning_num, + "batting_order": new_batting_order, + "starting_outs": new_starting_outs, + "away_score": new_away_score, + "home_score": new_home_score, + "on_first": new_on_first, + "on_second": new_on_second, + "on_third": new_on_third, + "is_new_inning": 1 if new_inning_half != this_play.inning_half else 0, + } + ) # return_play = model_to_dict(next_play) return_play = convert_stratplay(next_play) db.close() @@ -1474,55 +1667,67 @@ def complete_play(play_id, batter_to_base: int = None): def get_batting_stats(game_id, lineup_id: int = None, team_id: int = None): - batting_stats = Play.select( - Play.batter, - fn.SUM(Play.pa).over(partition_by=[Play.batter_id]).alias('pl_pa'), - fn.SUM(Play.ab).over(partition_by=[Play.batter_id]).alias('pl_ab'), - fn.SUM(Play.hit).over(partition_by=[Play.batter_id]).alias('pl_hit'), - fn.SUM(Play.rbi).over(partition_by=[Play.batter_id]).alias('pl_rbi'), - # fn.COUNT(Play.on_first_final).filter( - # Play.on_first_final == 4).over(partition_by=[Play.batter_id]).alias('pl_run_first'), - # fn.COUNT(Play.on_second_final).filter( - # Play.on_second_final == 4).over(partition_by=[Play.batter_id]).alias('pl_run_second'), - # fn.COUNT(Play.on_third_final).filter( - # Play.on_third_final == 4).over(partition_by=[Play.batter_id]).alias('pl_run_third'), - # fn.COUNT(Play.batter_final).filter( - # Play.batter_final == 4).over(partition_by=[Play.batter_id]).alias('pl_run_batter'), - fn.SUM(Play.double).over(partition_by=[Play.batter_id]).alias('pl_double'), - fn.SUM(Play.triple).over(partition_by=[Play.batter_id]).alias('pl_triple'), - fn.SUM(Play.homerun).over(partition_by=[Play.batter_id]).alias('pl_homerun'), - fn.SUM(Play.bb).over(partition_by=[Play.batter_id]).alias('pl_bb'), - fn.SUM(Play.so).over(partition_by=[Play.batter_id]).alias('pl_so'), - fn.SUM(Play.hbp).over(partition_by=[Play.batter_id]).alias('pl_hbp'), - fn.SUM(Play.sac).over(partition_by=[Play.batter_id]).alias('pl_sac'), - fn.SUM(Play.ibb).over(partition_by=[Play.batter_id]).alias('pl_ibb'), - fn.SUM(Play.gidp).over(partition_by=[Play.batter_id]).alias('pl_gidp'), - fn.SUM(Play.sb).over(partition_by=[Play.runner_id]).alias('pl_sb'), - fn.SUM(Play.cs).over(partition_by=[Play.runner_id]).alias('pl_cs'), - fn.SUM(Play.bphr).over(partition_by=[Play.batter_id]).alias('pl_bphr'), - fn.SUM(Play.bpfo).over(partition_by=[Play.batter_id]).alias('pl_bpfo'), - fn.SUM(Play.bp1b).over(partition_by=[Play.batter_id]).alias('pl_bp1b'), - fn.SUM(Play.bplo).over(partition_by=[Play.batter_id]).alias('pl_bplo'), - fn.SUM(Play.pa).over(partition_by=[Play.batter.team_id]).alias('tm_pa'), - fn.SUM(Play.ab).over(partition_by=[Play.batter.team_id]).alias('tm_ab'), - fn.SUM(Play.hit).over(partition_by=[Play.batter.team_id]).alias('tm_hit'), - fn.SUM(Play.rbi).over(partition_by=[Play.batter.team_id]).alias('tm_rbi'), - fn.SUM(Play.double).over(partition_by=[Play.batter.team_id]).alias('tm_double'), - fn.SUM(Play.triple).over(partition_by=[Play.batter.team_id]).alias('tm_triple'), - fn.SUM(Play.homerun).over(partition_by=[Play.batter.team_id]).alias('tm_homerun'), - fn.SUM(Play.bb).over(partition_by=[Play.batter.team_id]).alias('tm_bb'), - fn.SUM(Play.so).over(partition_by=[Play.batter.team_id]).alias('tm_so'), - fn.SUM(Play.hbp).over(partition_by=[Play.batter.team_id]).alias('tm_hbp'), - fn.SUM(Play.sac).over(partition_by=[Play.batter.team_id]).alias('tm_sac'), - fn.SUM(Play.ibb).over(partition_by=[Play.batter.team_id]).alias('tm_ibb'), - fn.SUM(Play.gidp).over(partition_by=[Play.batter.team_id]).alias('tm_gidp'), - fn.SUM(Play.sb).over(partition_by=[Play.batter.team_id]).alias('tm_sb'), - fn.SUM(Play.cs).over(partition_by=[Play.batter.team_id]).alias('tm_cs'), - fn.SUM(Play.bphr).over(partition_by=[Play.batter.team_id]).alias('tm_bphr'), - fn.SUM(Play.bpfo).over(partition_by=[Play.batter.team_id]).alias('tm_bpfo'), - fn.SUM(Play.bp1b).over(partition_by=[Play.batter.team_id]).alias('tm_bp1b'), - fn.SUM(Play.bplo).over(partition_by=[Play.batter.team_id]).alias('tm_bplo'), - ).join(Lineup, on=Play.batter).where(Play.game_id == game_id) + batting_stats = ( + Play.select( + Play.batter, + fn.SUM(Play.pa).over(partition_by=[Play.batter_id]).alias("pl_pa"), + fn.SUM(Play.ab).over(partition_by=[Play.batter_id]).alias("pl_ab"), + fn.SUM(Play.hit).over(partition_by=[Play.batter_id]).alias("pl_hit"), + fn.SUM(Play.rbi).over(partition_by=[Play.batter_id]).alias("pl_rbi"), + # fn.COUNT(Play.on_first_final).filter( + # Play.on_first_final == 4).over(partition_by=[Play.batter_id]).alias('pl_run_first'), + # fn.COUNT(Play.on_second_final).filter( + # Play.on_second_final == 4).over(partition_by=[Play.batter_id]).alias('pl_run_second'), + # fn.COUNT(Play.on_third_final).filter( + # Play.on_third_final == 4).over(partition_by=[Play.batter_id]).alias('pl_run_third'), + # fn.COUNT(Play.batter_final).filter( + # Play.batter_final == 4).over(partition_by=[Play.batter_id]).alias('pl_run_batter'), + fn.SUM(Play.double).over(partition_by=[Play.batter_id]).alias("pl_double"), + fn.SUM(Play.triple).over(partition_by=[Play.batter_id]).alias("pl_triple"), + fn.SUM(Play.homerun) + .over(partition_by=[Play.batter_id]) + .alias("pl_homerun"), + fn.SUM(Play.bb).over(partition_by=[Play.batter_id]).alias("pl_bb"), + fn.SUM(Play.so).over(partition_by=[Play.batter_id]).alias("pl_so"), + fn.SUM(Play.hbp).over(partition_by=[Play.batter_id]).alias("pl_hbp"), + fn.SUM(Play.sac).over(partition_by=[Play.batter_id]).alias("pl_sac"), + fn.SUM(Play.ibb).over(partition_by=[Play.batter_id]).alias("pl_ibb"), + fn.SUM(Play.gidp).over(partition_by=[Play.batter_id]).alias("pl_gidp"), + fn.SUM(Play.sb).over(partition_by=[Play.runner_id]).alias("pl_sb"), + fn.SUM(Play.cs).over(partition_by=[Play.runner_id]).alias("pl_cs"), + fn.SUM(Play.bphr).over(partition_by=[Play.batter_id]).alias("pl_bphr"), + fn.SUM(Play.bpfo).over(partition_by=[Play.batter_id]).alias("pl_bpfo"), + fn.SUM(Play.bp1b).over(partition_by=[Play.batter_id]).alias("pl_bp1b"), + fn.SUM(Play.bplo).over(partition_by=[Play.batter_id]).alias("pl_bplo"), + fn.SUM(Play.pa).over(partition_by=[Play.batter.team_id]).alias("tm_pa"), + fn.SUM(Play.ab).over(partition_by=[Play.batter.team_id]).alias("tm_ab"), + fn.SUM(Play.hit).over(partition_by=[Play.batter.team_id]).alias("tm_hit"), + fn.SUM(Play.rbi).over(partition_by=[Play.batter.team_id]).alias("tm_rbi"), + fn.SUM(Play.double) + .over(partition_by=[Play.batter.team_id]) + .alias("tm_double"), + fn.SUM(Play.triple) + .over(partition_by=[Play.batter.team_id]) + .alias("tm_triple"), + fn.SUM(Play.homerun) + .over(partition_by=[Play.batter.team_id]) + .alias("tm_homerun"), + fn.SUM(Play.bb).over(partition_by=[Play.batter.team_id]).alias("tm_bb"), + fn.SUM(Play.so).over(partition_by=[Play.batter.team_id]).alias("tm_so"), + fn.SUM(Play.hbp).over(partition_by=[Play.batter.team_id]).alias("tm_hbp"), + fn.SUM(Play.sac).over(partition_by=[Play.batter.team_id]).alias("tm_sac"), + fn.SUM(Play.ibb).over(partition_by=[Play.batter.team_id]).alias("tm_ibb"), + fn.SUM(Play.gidp).over(partition_by=[Play.batter.team_id]).alias("tm_gidp"), + fn.SUM(Play.sb).over(partition_by=[Play.batter.team_id]).alias("tm_sb"), + fn.SUM(Play.cs).over(partition_by=[Play.batter.team_id]).alias("tm_cs"), + fn.SUM(Play.bphr).over(partition_by=[Play.batter.team_id]).alias("tm_bphr"), + fn.SUM(Play.bpfo).over(partition_by=[Play.batter.team_id]).alias("tm_bpfo"), + fn.SUM(Play.bp1b).over(partition_by=[Play.batter.team_id]).alias("tm_bp1b"), + fn.SUM(Play.bplo).over(partition_by=[Play.batter.team_id]).alias("tm_bplo"), + ) + .join(Lineup, on=Play.batter) + .where(Play.game_id == game_id) + ) if lineup_id is not None: batting_stats = batting_stats.where(Play.batter_id == lineup_id) @@ -1533,60 +1738,68 @@ def get_batting_stats(game_id, lineup_id: int = None, team_id: int = None): return_batters = [] for x in batting_stats: if x.batter.id not in done_batters: - runs_scored = Play.select(Play.pa).where( - ((Play.on_first == x.batter) & (Play.on_first_final == 4)) | - ((Play.on_second == x.batter) & (Play.on_second_final == 4)) | - ((Play.on_third == x.batter) & (Play.on_third_final == 4)) | - ((Play.batter == x.batter) & (Play.batter_final == 4)) - ).count() - stolen_bases = Play.select(Play.pa).where( - (Play.runner == x.batter) & (Play.sb == 1) - ).count() - return_batters.append({ - 'batter_id': x.batter_id, - 'card_id': x.batter.card_id, - 'team_id': x.batter.team_id, - 'pos': x.batter.position, - 'pl_run': runs_scored, - 'pl_pa': x.pl_pa, - 'pl_ab': x.pl_ab, - 'pl_hit': x.pl_hit, - 'pl_rbi': x.pl_rbi, - 'pl_double': x.pl_double, - 'pl_triple': x.pl_triple, - 'pl_homerun': x.pl_homerun, - 'pl_bb': x.pl_bb, - 'pl_so': x.pl_so, - 'pl_hbp': x.pl_hbp, - 'pl_sac': x.pl_sac, - 'pl_ibb': x.pl_ibb, - 'pl_gidp': x.pl_gidp, - 'pl_sb': stolen_bases, - 'pl_cs': x.pl_cs, - 'pl_bphr': x.pl_bphr, - 'pl_bpfo': x.pl_bpfo, - 'pl_bp1b': x.pl_bp1b, - 'pl_bplo': x.pl_bplo, - 'tm_pa': x.tm_pa, - 'tm_ab': x.tm_ab, - 'tm_hit': x.tm_hit, - 'tm_rbi': x.tm_rbi, - 'tm_double': x.tm_double, - 'tm_triple': x.tm_triple, - 'tm_homerun': x.tm_homerun, - 'tm_bb': x.tm_bb, - 'tm_so': x.tm_so, - 'tm_hbp': x.tm_hbp, - 'tm_sac': x.tm_sac, - 'tm_ibb': x.tm_ibb, - 'tm_gidp': x.tm_gidp, - 'tm_sb': x.tm_sb, - 'tm_cs': x.tm_cs, - 'tm_bphr': x.tm_bphr, - 'tm_bpfo': x.tm_bpfo, - 'tm_bp1b': x.tm_bp1b, - 'tm_bplo': x.tm_bplo, - }) + runs_scored = ( + Play.select(Play.pa) + .where( + ((Play.on_first == x.batter) & (Play.on_first_final == 4)) + | ((Play.on_second == x.batter) & (Play.on_second_final == 4)) + | ((Play.on_third == x.batter) & (Play.on_third_final == 4)) + | ((Play.batter == x.batter) & (Play.batter_final == 4)) + ) + .count() + ) + stolen_bases = ( + Play.select(Play.pa) + .where((Play.runner == x.batter) & (Play.sb == 1)) + .count() + ) + return_batters.append( + { + "batter_id": x.batter_id, + "card_id": x.batter.card_id, + "team_id": x.batter.team_id, + "pos": x.batter.position, + "pl_run": runs_scored, + "pl_pa": x.pl_pa, + "pl_ab": x.pl_ab, + "pl_hit": x.pl_hit, + "pl_rbi": x.pl_rbi, + "pl_double": x.pl_double, + "pl_triple": x.pl_triple, + "pl_homerun": x.pl_homerun, + "pl_bb": x.pl_bb, + "pl_so": x.pl_so, + "pl_hbp": x.pl_hbp, + "pl_sac": x.pl_sac, + "pl_ibb": x.pl_ibb, + "pl_gidp": x.pl_gidp, + "pl_sb": stolen_bases, + "pl_cs": x.pl_cs, + "pl_bphr": x.pl_bphr, + "pl_bpfo": x.pl_bpfo, + "pl_bp1b": x.pl_bp1b, + "pl_bplo": x.pl_bplo, + "tm_pa": x.tm_pa, + "tm_ab": x.tm_ab, + "tm_hit": x.tm_hit, + "tm_rbi": x.tm_rbi, + "tm_double": x.tm_double, + "tm_triple": x.tm_triple, + "tm_homerun": x.tm_homerun, + "tm_bb": x.tm_bb, + "tm_so": x.tm_so, + "tm_hbp": x.tm_hbp, + "tm_sac": x.tm_sac, + "tm_ibb": x.tm_ibb, + "tm_gidp": x.tm_gidp, + "tm_sb": x.tm_sb, + "tm_cs": x.tm_cs, + "tm_bphr": x.tm_bphr, + "tm_bpfo": x.tm_bpfo, + "tm_bp1b": x.tm_bp1b, + "tm_bplo": x.tm_bplo, + } + ) done_batters.append(x.batter.id) db.close() @@ -1594,14 +1807,22 @@ def get_batting_stats(game_id, lineup_id: int = None, team_id: int = None): def get_fielding_stats(game_id, lineup_id: int = None, team_id: int = None): - fielding_stats = Play.select( - Play.defender, - Play.check_pos, - fn.SUM(Play.error).over(partition_by=[Play.defender_id]).alias('pl_error'), - fn.SUM(Play.hit).over(partition_by=[Play.defender_id]).alias('pl_xhit'), - fn.COUNT(Play.defender).over(partition_by=[Play.defender_id]).alias('pl_xch'), - fn.SUM(Play.error).over(partition_by=[Play.defender.team_id]).alias('tm_error'), - ).join(Lineup, on=Play.defender).where(Play.game_id == game_id) + fielding_stats = ( + Play.select( + Play.defender, + Play.check_pos, + fn.SUM(Play.error).over(partition_by=[Play.defender_id]).alias("pl_error"), + fn.SUM(Play.hit).over(partition_by=[Play.defender_id]).alias("pl_xhit"), + fn.COUNT(Play.defender) + .over(partition_by=[Play.defender_id]) + .alias("pl_xch"), + fn.SUM(Play.error) + .over(partition_by=[Play.defender.team_id]) + .alias("tm_error"), + ) + .join(Lineup, on=Play.defender) + .where(Play.game_id == game_id) + ) if lineup_id is not None: fielding_stats = fielding_stats.where(Play.defender_id == lineup_id) @@ -1613,26 +1834,34 @@ def get_fielding_stats(game_id, lineup_id: int = None, team_id: int = None): for x in fielding_stats: if x.defender.card_id not in added_card_ids: added_card_ids.append(x.defender.card_id) - all_stats.append({ - 'defender_id': x.defender_id, - 'card_id': x.defender.card_id, - 'team_id': x.defender.team_id, - 'pos': x.check_pos, - 'pl_error': x.pl_error, - 'pl_xhit': x.pl_xhit, - 'pl_xch': x.pl_xch, - 'tm_error': x.pl_error, - 'pl_pb': 0, - 'pl_sbc': 0, - 'pl_csc': 0 - }) + all_stats.append( + { + "defender_id": x.defender_id, + "card_id": x.defender.card_id, + "team_id": x.defender.team_id, + "pos": x.check_pos, + "pl_error": x.pl_error, + "pl_xhit": x.pl_xhit, + "pl_xch": x.pl_xch, + "tm_error": x.pl_error, + "pl_pb": 0, + "pl_sbc": 0, + "pl_csc": 0, + } + ) - catching_stats = Play.select( - Play.catcher, - fn.SUM(Play.passed_ball).over(partition_by=[Play.catcher_id]).alias('pl_pb'), - fn.SUM(Play.sb).over(partition_by=[Play.catcher_id]).alias('pl_sbc'), - fn.SUM(Play.cs).over(partition_by=[Play.catcher_id]).alias('pl_csc') - ).join(Lineup, on=Play.catcher).where(Play.game_id == game_id) + catching_stats = ( + Play.select( + Play.catcher, + fn.SUM(Play.passed_ball) + .over(partition_by=[Play.catcher_id]) + .alias("pl_pb"), + fn.SUM(Play.sb).over(partition_by=[Play.catcher_id]).alias("pl_sbc"), + fn.SUM(Play.cs).over(partition_by=[Play.catcher_id]).alias("pl_csc"), + ) + .join(Lineup, on=Play.catcher) + .where(Play.game_id == game_id) + ) if lineup_id is not None: catching_stats = catching_stats.where(Play.defender_id == lineup_id) @@ -1640,24 +1869,27 @@ def get_fielding_stats(game_id, lineup_id: int = None, team_id: int = None): catching_stats = catching_stats.where(Play.defender.team_id == team_id) for x in catching_stats: - all_stats.append({ - 'defender_id': x.catcher_id, - 'card_id': x.catcher.card_id, - 'team_id': x.catcher.team_id, - 'pos': 'C', - 'pl_error': 0, - 'pl_xhit': 0, - 'pl_xch': 0, - 'tm_error': 0, - 'pl_pb': x.pl_pb, - 'pl_sbc': x.pl_sbc, - 'pl_csc': x.pl_csc - }) + all_stats.append( + { + "defender_id": x.catcher_id, + "card_id": x.catcher.card_id, + "team_id": x.catcher.team_id, + "pos": "C", + "pl_error": 0, + "pl_xhit": 0, + "pl_xch": 0, + "tm_error": 0, + "pl_pb": x.pl_pb, + "pl_sbc": x.pl_sbc, + "pl_csc": x.pl_csc, + } + ) - logger.debug(f'fielding_stats: {all_stats}') + logger.debug(f"fielding_stats: {all_stats}") db.close() return all_stats + # def new_get_batting_stats(game_id, lineup_id: int = None, team_id: int = None): # return_stats = [] # @@ -1784,54 +2016,101 @@ def get_fielding_stats(game_id, lineup_id: int = None, team_id: int = None): def get_pitching_stats( - game_id, lineup_id: int = None, team_id: int = None, in_pow: bool = None, in_innings: list = None): + game_id, + lineup_id: int = None, + team_id: int = None, + in_pow: bool = None, + in_innings: list = None, +): if in_innings is None: in_innings = [x for x in range(1, 30)] - logger.info(f'db_calls_gameplay - get_pitching_stats - in_innings: {in_innings}') - pitching_stats = Play.select( - Play.pitcher, - fn.SUM(Play.outs).over(partition_by=[Play.pitcher_id]).alias('pl_outs'), - fn.SUM(Play.hit).over(partition_by=[Play.pitcher_id]).alias('pl_hit'), - fn.COUNT(Play.on_first_final).filter( - Play.on_first_final == 4).over(partition_by=[Play.pitcher_id]).alias('pl_run_first'), - fn.COUNT(Play.on_second_final).filter( - Play.on_second_final == 4).over(partition_by=[Play.pitcher_id]).alias('pl_run_second'), - fn.COUNT(Play.on_third_final).filter( - Play.on_third_final == 4).over(partition_by=[Play.pitcher_id]).alias('pl_run_third'), - fn.COUNT(Play.batter_final).filter( - Play.batter_final == 4).over(partition_by=[Play.pitcher_id]).alias('pl_run_batter'), - fn.COUNT(Play.on_first_final).filter( - (Play.on_first_final == 4) & (Play.inning_num << in_innings)).over(partition_by=[Play.pitcher_id]).alias('pl_in_run_first'), - fn.COUNT(Play.on_second_final).filter( - (Play.on_second_final == 4) & (Play.inning_num << in_innings)).over(partition_by=[Play.pitcher_id]).alias('pl_in_run_second'), - fn.COUNT(Play.on_third_final).filter( - (Play.on_third_final == 4) & (Play.inning_num << in_innings)).over(partition_by=[Play.pitcher_id]).alias('pl_in_run_third'), - fn.COUNT(Play.batter_final).filter( - (Play.batter_final == 4) & (Play.inning_num << in_innings)).over(partition_by=[Play.pitcher_id]).alias('pl_in_run_batter'), - fn.SUM(Play.so).over(partition_by=[Play.pitcher_id]).alias('pl_so'), - fn.SUM(Play.bb).over(partition_by=[Play.pitcher_id]).alias('pl_bb'), - fn.SUM(Play.hbp).over(partition_by=[Play.pitcher_id]).alias('pl_hbp'), - fn.SUM(Play.wild_pitch).over(partition_by=[Play.pitcher_id]).alias('pl_wild_pitch'), - fn.SUM(Play.balk).over(partition_by=[Play.pitcher_id]).alias('pl_balk'), - fn.SUM(Play.homerun).over(partition_by=[Play.pitcher_id]).alias('pl_homerun'), - fn.SUM(Play.outs).over(partition_by=[Play.pitcher.team_id]).alias('tm_outs'), - fn.SUM(Play.hit).over(partition_by=[Play.pitcher.team_id]).alias('tm_hit'), - fn.COUNT(Play.on_first_final).filter( - Play.on_first_final == 4).over(partition_by=[Play.pitcher.team_id]).alias('tm_run_first'), - fn.COUNT(Play.on_second_final).filter( - Play.on_second_final == 4).over(partition_by=[Play.pitcher.team_id]).alias('tm_run_second'), - fn.COUNT(Play.on_third_final).filter( - Play.on_third_final == 4).over(partition_by=[Play.pitcher.team_id]).alias('tm_run_third'), - fn.COUNT(Play.batter_final).filter( - Play.batter_final == 4).over(partition_by=[Play.pitcher.team_id]).alias('tm_run_batter'), - fn.SUM(Play.so).over(partition_by=[Play.pitcher.team_id]).alias('tm_so'), - fn.SUM(Play.bb).over(partition_by=[Play.pitcher.team_id]).alias('tm_bb'), - fn.SUM(Play.hbp).over(partition_by=[Play.pitcher.team_id]).alias('tm_hbp'), - fn.SUM(Play.wild_pitch).over(partition_by=[Play.pitcher.team_id]).alias('tm_wild_pitch'), - fn.SUM(Play.balk).over(partition_by=[Play.pitcher.team_id]).alias('tm_balk'), - fn.SUM(Play.homerun).over(partition_by=[Play.pitcher.team_id]).alias('tm_homerun'), - ).join(Lineup, on=Play.pitcher).where(Play.game_id == game_id) - logger.debug(f'db_calls_gameplay - get_pitching_stats - pitching_stats: {pitching_stats}') + logger.info(f"db_calls_gameplay - get_pitching_stats - in_innings: {in_innings}") + pitching_stats = ( + Play.select( + Play.pitcher, + fn.SUM(Play.outs).over(partition_by=[Play.pitcher_id]).alias("pl_outs"), + fn.SUM(Play.hit).over(partition_by=[Play.pitcher_id]).alias("pl_hit"), + fn.COUNT(Play.on_first_final) + .filter(Play.on_first_final == 4) + .over(partition_by=[Play.pitcher_id]) + .alias("pl_run_first"), + fn.COUNT(Play.on_second_final) + .filter(Play.on_second_final == 4) + .over(partition_by=[Play.pitcher_id]) + .alias("pl_run_second"), + fn.COUNT(Play.on_third_final) + .filter(Play.on_third_final == 4) + .over(partition_by=[Play.pitcher_id]) + .alias("pl_run_third"), + fn.COUNT(Play.batter_final) + .filter(Play.batter_final == 4) + .over(partition_by=[Play.pitcher_id]) + .alias("pl_run_batter"), + fn.COUNT(Play.on_first_final) + .filter((Play.on_first_final == 4) & (Play.inning_num << in_innings)) + .over(partition_by=[Play.pitcher_id]) + .alias("pl_in_run_first"), + fn.COUNT(Play.on_second_final) + .filter((Play.on_second_final == 4) & (Play.inning_num << in_innings)) + .over(partition_by=[Play.pitcher_id]) + .alias("pl_in_run_second"), + fn.COUNT(Play.on_third_final) + .filter((Play.on_third_final == 4) & (Play.inning_num << in_innings)) + .over(partition_by=[Play.pitcher_id]) + .alias("pl_in_run_third"), + fn.COUNT(Play.batter_final) + .filter((Play.batter_final == 4) & (Play.inning_num << in_innings)) + .over(partition_by=[Play.pitcher_id]) + .alias("pl_in_run_batter"), + fn.SUM(Play.so).over(partition_by=[Play.pitcher_id]).alias("pl_so"), + fn.SUM(Play.bb).over(partition_by=[Play.pitcher_id]).alias("pl_bb"), + fn.SUM(Play.hbp).over(partition_by=[Play.pitcher_id]).alias("pl_hbp"), + fn.SUM(Play.wild_pitch) + .over(partition_by=[Play.pitcher_id]) + .alias("pl_wild_pitch"), + fn.SUM(Play.balk).over(partition_by=[Play.pitcher_id]).alias("pl_balk"), + fn.SUM(Play.homerun) + .over(partition_by=[Play.pitcher_id]) + .alias("pl_homerun"), + fn.SUM(Play.outs) + .over(partition_by=[Play.pitcher.team_id]) + .alias("tm_outs"), + fn.SUM(Play.hit).over(partition_by=[Play.pitcher.team_id]).alias("tm_hit"), + fn.COUNT(Play.on_first_final) + .filter(Play.on_first_final == 4) + .over(partition_by=[Play.pitcher.team_id]) + .alias("tm_run_first"), + fn.COUNT(Play.on_second_final) + .filter(Play.on_second_final == 4) + .over(partition_by=[Play.pitcher.team_id]) + .alias("tm_run_second"), + fn.COUNT(Play.on_third_final) + .filter(Play.on_third_final == 4) + .over(partition_by=[Play.pitcher.team_id]) + .alias("tm_run_third"), + fn.COUNT(Play.batter_final) + .filter(Play.batter_final == 4) + .over(partition_by=[Play.pitcher.team_id]) + .alias("tm_run_batter"), + fn.SUM(Play.so).over(partition_by=[Play.pitcher.team_id]).alias("tm_so"), + fn.SUM(Play.bb).over(partition_by=[Play.pitcher.team_id]).alias("tm_bb"), + fn.SUM(Play.hbp).over(partition_by=[Play.pitcher.team_id]).alias("tm_hbp"), + fn.SUM(Play.wild_pitch) + .over(partition_by=[Play.pitcher.team_id]) + .alias("tm_wild_pitch"), + fn.SUM(Play.balk) + .over(partition_by=[Play.pitcher.team_id]) + .alias("tm_balk"), + fn.SUM(Play.homerun) + .over(partition_by=[Play.pitcher.team_id]) + .alias("tm_homerun"), + ) + .join(Lineup, on=Play.pitcher) + .where(Play.game_id == game_id) + ) + logger.debug( + f"db_calls_gameplay - get_pitching_stats - pitching_stats: {pitching_stats}" + ) # This is counging plays with multiple runs scored on 1 ER and the rest unearned # earned_runs_pl = Play.select().where( @@ -1840,18 +2119,30 @@ def get_pitching_stats( # ).join(Lineup, on=Play.pitcher).where(Play.game_id == game_id) # logger.info(f'earned_runs: {earned_runs_pl}') - er_first = Play.select().where( - (Play.on_first_final == 4) & (Play.error == 0) - ).join(Lineup, on=Play.pitcher).where((Play.game_id == game_id) & (Play.pitcher_id == lineup_id)) - er_second = Play.select().where( - (Play.on_second_final == 4) & (Play.error == 0) - ).join(Lineup, on=Play.pitcher).where((Play.game_id == game_id) & (Play.pitcher_id == lineup_id)) - er_third = Play.select().where( - (Play.on_third_final == 4) & (Play.error == 0) - ).join(Lineup, on=Play.pitcher).where((Play.game_id == game_id) & (Play.pitcher_id == lineup_id)) - er_batter = Play.select().where( - (Play.batter_final == 4) & (Play.error == 0) - ).join(Lineup, on=Play.pitcher).where((Play.game_id == game_id) & (Play.pitcher_id == lineup_id)) + er_first = ( + Play.select() + .where((Play.on_first_final == 4) & (Play.error == 0)) + .join(Lineup, on=Play.pitcher) + .where((Play.game_id == game_id) & (Play.pitcher_id == lineup_id)) + ) + er_second = ( + Play.select() + .where((Play.on_second_final == 4) & (Play.error == 0)) + .join(Lineup, on=Play.pitcher) + .where((Play.game_id == game_id) & (Play.pitcher_id == lineup_id)) + ) + er_third = ( + Play.select() + .where((Play.on_third_final == 4) & (Play.error == 0)) + .join(Lineup, on=Play.pitcher) + .where((Play.game_id == game_id) & (Play.pitcher_id == lineup_id)) + ) + er_batter = ( + Play.select() + .where((Play.batter_final == 4) & (Play.error == 0)) + .join(Lineup, on=Play.pitcher) + .where((Play.game_id == game_id) & (Play.pitcher_id == lineup_id)) + ) # earned_runs_tm = Play.select().where( # ((Play.on_first_final == 4) | (Play.on_second_final == 4) | (Play.on_third_final == 4) | @@ -1871,18 +2162,30 @@ def get_pitching_stats( tm_earned_runs = None if team_id is not None: - tm_er_first = Play.select().where( - (Play.on_first_final == 4) & (Play.error == 0) - ).join(Lineup, on=Play.pitcher).where(Play.game_id == game_id) - tm_er_second = Play.select().where( - (Play.on_second_final == 4) & (Play.error == 0) - ).join(Lineup, on=Play.pitcher).where(Play.game_id == game_id) - tm_er_third = Play.select().where( - (Play.on_third_final == 4) & (Play.error == 0) - ).join(Lineup, on=Play.pitcher).where(Play.game_id == game_id) - tm_er_batter = Play.select().where( - (Play.batter_final == 4) & (Play.error == 0) - ).join(Lineup, on=Play.pitcher).where(Play.game_id == game_id) + tm_er_first = ( + Play.select() + .where((Play.on_first_final == 4) & (Play.error == 0)) + .join(Lineup, on=Play.pitcher) + .where(Play.game_id == game_id) + ) + tm_er_second = ( + Play.select() + .where((Play.on_second_final == 4) & (Play.error == 0)) + .join(Lineup, on=Play.pitcher) + .where(Play.game_id == game_id) + ) + tm_er_third = ( + Play.select() + .where((Play.on_third_final == 4) & (Play.error == 0)) + .join(Lineup, on=Play.pitcher) + .where(Play.game_id == game_id) + ) + tm_er_batter = ( + Play.select() + .where((Play.batter_final == 4) & (Play.error == 0)) + .join(Lineup, on=Play.pitcher) + .where(Play.game_id == game_id) + ) # er_first = er_first.where(Play.pitcher.team_id == team_id) # er_second = er_second.where(Play.pitcher.team_id == team_id) @@ -1896,45 +2199,63 @@ def get_pitching_stats( tm_er_third = tm_er_third.where(Play.pitcher.team_id == team_id) tm_er_batter = tm_er_batter.where(Play.pitcher.team_id == team_id) - tm_earned_runs = tm_er_first.count() + tm_er_second.count() + tm_er_third.count() + tm_er_batter.count() + tm_earned_runs = ( + tm_er_first.count() + + tm_er_second.count() + + tm_er_third.count() + + tm_er_batter.count() + ) - pl_earned_runs = er_first.count() + er_second.count() + er_third.count() + er_batter.count() + pl_earned_runs = ( + er_first.count() + er_second.count() + er_third.count() + er_batter.count() + ) done_pitchers = [] return_pitchers = [] for x in pitching_stats: if x.pitcher.id not in done_pitchers: - return_pitchers.append({ - 'pitcher_id': x.pitcher_id, - 'card_id': x.pitcher.card_id, - 'team_id': x.pitcher.team_id, - 'pl_outs': x.pl_outs, - 'pl_hit': x.pl_hit, - 'pl_eruns': pl_earned_runs, - 'pl_runs': x.pl_run_first + x.pl_run_second + x.pl_run_third + x.pl_run_batter, - 'pl_in_runs': x.pl_in_run_first + x.pl_in_run_second + x.pl_in_run_third + x.pl_in_run_batter, - 'pl_so': x.pl_so, - 'pl_bb': x.pl_bb, - 'pl_hbp': x.pl_hbp, - 'pl_homerun': x.pl_homerun, - 'pl_wild_pitch': x.pl_wild_pitch, - 'pl_balk': x.pl_balk, - 'tm_outs': x.tm_outs, - 'tm_hit': x.tm_hit, - 'tm_eruns': tm_earned_runs, - 'tm_runs': x.tm_run_first + x.tm_run_second + x.tm_run_third + x.tm_run_batter, - 'tm_so': x.tm_so, - 'tm_bb': x.tm_bb, - 'tm_hbp': x.tm_hbp, - 'tm_homerun': x.tm_homerun, - 'tm_wild_pitch': x.tm_wild_pitch, - 'tm_balk': x.tm_balk, - 'pl_gs': 1 if x.pitcher.after_play == 0 else 0 - }) + return_pitchers.append( + { + "pitcher_id": x.pitcher_id, + "card_id": x.pitcher.card_id, + "team_id": x.pitcher.team_id, + "pl_outs": x.pl_outs, + "pl_hit": x.pl_hit, + "pl_eruns": pl_earned_runs, + "pl_runs": x.pl_run_first + + x.pl_run_second + + x.pl_run_third + + x.pl_run_batter, + "pl_in_runs": x.pl_in_run_first + + x.pl_in_run_second + + x.pl_in_run_third + + x.pl_in_run_batter, + "pl_so": x.pl_so, + "pl_bb": x.pl_bb, + "pl_hbp": x.pl_hbp, + "pl_homerun": x.pl_homerun, + "pl_wild_pitch": x.pl_wild_pitch, + "pl_balk": x.pl_balk, + "tm_outs": x.tm_outs, + "tm_hit": x.tm_hit, + "tm_eruns": tm_earned_runs, + "tm_runs": x.tm_run_first + + x.tm_run_second + + x.tm_run_third + + x.tm_run_batter, + "tm_so": x.tm_so, + "tm_bb": x.tm_bb, + "tm_hbp": x.tm_hbp, + "tm_homerun": x.tm_homerun, + "tm_wild_pitch": x.tm_wild_pitch, + "tm_balk": x.tm_balk, + "pl_gs": 1 if x.pitcher.after_play == 0 else 0, + } + ) done_pitchers.append(x.pitcher_id) db.close() - logger.debug(f'pitching stats: {return_pitchers}') + logger.debug(f"pitching stats: {return_pitchers}") return return_pitchers @@ -1946,7 +2267,7 @@ def get_pitching_decisions(game: StratGame, db_game_id: int): # home_pitchers = [] # [(pitcher, first_play), (pitcher2, their_first_play)] # last_play = get_current_play(game.id) - logger.debug(f'this game: {game}') + logger.debug(f"this game: {game}") winner = None loser = None save = None @@ -1955,10 +2276,18 @@ def get_pitching_decisions(game: StratGame, db_game_id: int): holds = [] # Get starting pitchers and update this as a pointer for the play crawl - away_pitcher = Lineup.get(Lineup.game_id == game.id, Lineup.team_id == game.away_team_id, Lineup.position == 'P') - home_pitcher = Lineup.get(Lineup.game_id == game.id, Lineup.team_id == game.home_team_id, Lineup.position == 'P') + away_pitcher = Lineup.get( + Lineup.game_id == game.id, + Lineup.team_id == game.away_team_id, + Lineup.position == "P", + ) + home_pitcher = Lineup.get( + Lineup.game_id == game.id, + Lineup.team_id == game.home_team_id, + Lineup.position == "P", + ) gs.extend([away_pitcher.card_id, home_pitcher.card_id]) - logger.debug(f'SPs: {away_pitcher} / {home_pitcher}') + logger.debug(f"SPs: {away_pitcher} / {home_pitcher}") decisions = { away_pitcher.player_id: DecisionModel( @@ -1967,7 +2296,7 @@ def get_pitching_decisions(game: StratGame, db_game_id: int): week=game.week_num, pitcher_id=away_pitcher.player_id, pitcher_team_id=away_pitcher.team_id, - is_start=True + is_start=True, ), home_pitcher.player_id: DecisionModel( game_id=db_game_id, @@ -1975,13 +2304,13 @@ def get_pitching_decisions(game: StratGame, db_game_id: int): week=game.week_num, pitcher_id=home_pitcher.player_id, pitcher_team_id=home_pitcher.team_id, - is_start=True - ) + is_start=True, + ), } # { : DecisionModel } for x in Play.select().where(Play.game_id == game.id): - logger.debug(f'checking play num {x.play_num}') - if x.inning_half == 'Top' and home_pitcher != x.pitcher: + logger.debug(f"checking play num {x.play_num}") + if x.inning_half == "Top" and home_pitcher != x.pitcher: if save == home_pitcher: if x.home_score > x.away_score: holds.append(save) @@ -1994,7 +2323,7 @@ def get_pitching_decisions(game: StratGame, db_game_id: int): if x.home_score > x.away_score and x.home_score - x.away_score <= 3: save = home_pitcher - elif x.inning_half == 'Bot' and away_pitcher != x.pitcher: + elif x.inning_half == "Bot" and away_pitcher != x.pitcher: if save == away_pitcher: if x.away_score > x.home_score: holds.append(save) @@ -2008,7 +2337,7 @@ def get_pitching_decisions(game: StratGame, db_game_id: int): save = away_pitcher if x.is_go_ahead: - logger.debug(f'is go ahead: {x}') + logger.debug(f"is go ahead: {x}") if x.on_third_final == 4: # winning_run = x.on_third # @@ -2021,7 +2350,7 @@ def get_pitching_decisions(game: StratGame, db_game_id: int): if save == loser: b_save.append(save) save = None - winner = home_pitcher if x.inning_half == 'Bot' else away_pitcher + winner = home_pitcher if x.inning_half == "Bot" else away_pitcher elif x.on_second_final == 4: # winning_run = x.on_second @@ -2035,7 +2364,7 @@ def get_pitching_decisions(game: StratGame, db_game_id: int): if save == loser: b_save.append(save) save = None - winner = home_pitcher if x.inning_half == 'Bot' else away_pitcher + winner = home_pitcher if x.inning_half == "Bot" else away_pitcher elif x.on_first_final == 4: # winning_run = x.on_first @@ -2049,7 +2378,7 @@ def get_pitching_decisions(game: StratGame, db_game_id: int): if save == loser: b_save.append(save) save = None - winner = home_pitcher if x.inning_half == 'Bot' else away_pitcher + winner = home_pitcher if x.inning_half == "Bot" else away_pitcher elif x.batter_final == 4: # winning_run = x.batter @@ -2063,10 +2392,10 @@ def get_pitching_decisions(game: StratGame, db_game_id: int): if save == loser: b_save.append(save) save = None - winner = home_pitcher if x.inning_half == 'Bot' else away_pitcher + winner = home_pitcher if x.inning_half == "Bot" else away_pitcher if x.is_tied: - logger.debug(f'is tied: {x}') + logger.debug(f"is tied: {x}") winner, loser = None, None if save: b_save.append(save) @@ -2078,7 +2407,7 @@ def get_pitching_decisions(game: StratGame, db_game_id: int): season=game.season, week=game.week_num, pitcher_id=home_pitcher.player_id, - pitcher_team_id=home_pitcher.team_id + pitcher_team_id=home_pitcher.team_id, ) if away_pitcher.player_id not in decisions: @@ -2087,7 +2416,7 @@ def get_pitching_decisions(game: StratGame, db_game_id: int): season=game.season, week=game.week_num, pitcher_id=away_pitcher.player_id, - pitcher_team_id=away_pitcher.team_id + pitcher_team_id=away_pitcher.team_id, ) decisions[winner.player_id].win = 1 @@ -2102,17 +2431,19 @@ def get_pitching_decisions(game: StratGame, db_game_id: int): return [x.dict() for x in decisions.values()] - logger.debug(f'\n\nWin: {winner}\nLose: {loser}\nSave: {save}\nBlown Save: {b_save}\nHolds: {holds}') + logger.debug( + f"\n\nWin: {winner}\nLose: {loser}\nSave: {save}\nBlown Save: {b_save}\nHolds: {holds}" + ) return { - 'winner': winner.card_id, - 'loser': loser.card_id, - 'save': save.card_id if save else None, - 'b_save': b_save, - 'holds': holds, - 'starters': gs, - 'w_lineup': winner, - 'l_lineup': loser, - 's_lineup': save + "winner": winner.card_id, + "loser": loser.card_id, + "save": save.card_id if save else None, + "b_save": b_save, + "holds": holds, + "starters": gs, + "w_lineup": winner, + "l_lineup": loser, + "s_lineup": save, } # for count, pit_pair in enumerate(away_pitchers): @@ -2221,11 +2552,11 @@ class StratManagerAi(pydantic.BaseModel): def check_jump(self, to_base: int, outs: int) -> Optional[str]: """Returns a string to be appended to the AI note""" - steal_base = f'attempt to steal' + steal_base = f"attempt to steal" if to_base == 2 or to_base == 3: if self.steal == 10: if to_base == 2: - return f'{steal_base} second if the runner has an ***** auto-jump or the safe range is 13+' + return f"{steal_base} second if the runner has an ***** auto-jump or the safe range is 13+" else: steal_range = 13 elif self.steal >= 8: @@ -2250,7 +2581,7 @@ class StratManagerAi(pydantic.BaseModel): def tag_from_second(self, outs: int) -> str: """Returns a string to be posted ahead of tag up message""" - tag_base = f'attempt to tag up if their safe range is' + tag_base = f"attempt to tag up if their safe range is" if self.running >= 8: tag_range = 5 elif self.running >= 5: @@ -2263,12 +2594,12 @@ class StratManagerAi(pydantic.BaseModel): elif outs == 0: tag_range -= 2 - return f'{tag_base} {tag_range}+' + return f"{tag_base} {tag_range}+" def tag_from_third(self, outs: int) -> str: """Returns a string to be posted with the tag up message""" - tag_base = f'attempt to tag up if their safe range is' + tag_base = f"attempt to tag up if their safe range is" if self.running >= 8: tag_range = 8 elif self.running >= 5: @@ -2281,12 +2612,12 @@ class StratManagerAi(pydantic.BaseModel): elif outs == 0: tag_range += 2 - return f'{tag_base} {tag_range}+' + return f"{tag_base} {tag_range}+" def uncapped_advance(self, to_base: int, outs: int) -> str: """Returns a string to be posted with the advancement message""" - advance_base = f'attempt to advance if their safe range is' + advance_base = f"attempt to advance if their safe range is" if to_base == 3: if self.uncapped_third >= 8: @@ -2294,7 +2625,7 @@ class StratManagerAi(pydantic.BaseModel): elif self.uncapped_third >= 5: advance_range = 18 else: - return f'not attempt to advance' + return f"not attempt to advance" if outs == 2: advance_range += 2 @@ -2312,27 +2643,26 @@ class StratManagerAi(pydantic.BaseModel): elif outs == 0: advance_range += 3 - return f'{advance_base} {advance_range}+' + return f"{advance_base} {advance_range}+" # def uncapped_advance_runner(self, this_play: StratPlay, to_base: int, runner: BattingCard, defender_pos: CardPosition, modifier: int = -1): # total_mod = modifier + defender_pos.arm # if to_base == 3: - def trail_advance(self, to_base: int, outs: int, sent_home: bool = False) -> str: """Returns a string to be posted with the advancement message""" - advance_base = f'attempt to advance if their safe range is' + advance_base = f"attempt to advance if their safe range is" if sent_home: if self.uncapped_trail >= 8: - return 'attempt to advance' + return "attempt to advance" elif self.uncapped_trail >= 5: if outs == 2: - return 'attempt to advance' + return "attempt to advance" else: advance_range = 14 else: - return 'not attempt to advance' + return "not attempt to advance" else: if self.uncapped_trail >= 8: @@ -2340,25 +2670,25 @@ class StratManagerAi(pydantic.BaseModel): else: advance_range = 16 - return f'{advance_base} {advance_range}+' + return f"{advance_base} {advance_range}+" def throw_lead_runner(self, to_base: int, outs: int) -> str: """Returns a string to be posted with the throw message""" - return 'throw for the lead runner' + return "throw for the lead runner" def throw_which_runner(self, to_base: int, outs: int) -> str: """Returns a string to be posted with the throw message""" if to_base == 4: - return 'throw for the lead runner' + return "throw for the lead runner" else: - return 'throw for the lead runner if their safe range is 14-' + return "throw for the lead runner if their safe range is 14-" def gb_decide_advance(self, starting_outs: int, run_lead: int): """Returns a string to be posted with the advancement message""" - advance_base = f'attempt to advance if their safe range is' + advance_base = f"attempt to advance if their safe range is" if self.running >= 8: advance_range = 10 elif self.running >= 5: @@ -2374,12 +2704,12 @@ class StratManagerAi(pydantic.BaseModel): elif run_lead < 0: advance_range += 3 - return f'{advance_base} {min(advance_range, 20)}+' + return f"{advance_base} {min(advance_range, 20)}+" def gb_decide_throw(self, starting_outs: int, run_lead: int): """Returns a string to be posted with the advancement message""" - throw_base = f'throw for the lead runner if their safe range is' + throw_base = f"throw for the lead runner if their safe range is" if self.decide_throw >= 8: throw_range = 13 elif self.decide_throw >= 5: @@ -2395,50 +2725,78 @@ class StratManagerAi(pydantic.BaseModel): elif run_lead < 0: throw_range += 3 - return f'{throw_base} {max(throw_range, 0)}-' + return f"{throw_base} {max(throw_range, 0)}-" def go_to_reliever( - self, this_play, tot_allowed: int, is_starter: bool = False) -> bool: + self, this_play, tot_allowed: int, is_starter: bool = False + ) -> bool: run_lead = this_play.ai_run_diff() obc = this_play.on_base_code - logger.info(f'db_calls_gameplay - StratManagerAi - ID: {self.id} - go_to_reliever: ' - f'outs: {this_play.starting_outs}, obc: {obc}, run_lead: {run_lead}, ' - f'tot_allowed: {tot_allowed}') + logger.info( + f"db_calls_gameplay - StratManagerAi - ID: {self.id} - go_to_reliever: " + f"outs: {this_play.starting_outs}, obc: {obc}, run_lead: {run_lead}, " + f"tot_allowed: {tot_allowed}" + ) lead_target = run_lead if is_starter else 3 # AI up big if tot_allowed < 5 and is_starter: - logger.info(f'db_calls_gameplay - StratManagerAi - ID: {self.id} - go_to_reliever: False / code 1') + logger.info( + f"db_calls_gameplay - StratManagerAi - ID: {self.id} - go_to_reliever: False / code 1" + ) return False elif run_lead > 5 or (run_lead > 2 and self.ahead_aggression > 5): - if tot_allowed <= lead_target or obc <= 3 or (this_play.starting_outs == 2 and not is_starter): - logger.info(f'db_calls_gameplay - StratManagerAi - ID: {self.id} - go_to_reliever: False / code 2') + if ( + tot_allowed <= lead_target + or obc <= 3 + or (this_play.starting_outs == 2 and not is_starter) + ): + logger.info( + f"db_calls_gameplay - StratManagerAi - ID: {self.id} - go_to_reliever: False / code 2" + ) return False elif run_lead > 2 or (run_lead >= 0 and self.ahead_aggression > 5): - if tot_allowed < lead_target or obc <= 1 or (this_play.starting_outs == 2 and not is_starter): - logger.info(f'db_calls_gameplay - StratManagerAi - ID: {self.id} - go_to_reliever: False / code 3') + if ( + tot_allowed < lead_target + or obc <= 1 + or (this_play.starting_outs == 2 and not is_starter) + ): + logger.info( + f"db_calls_gameplay - StratManagerAi - ID: {self.id} - go_to_reliever: False / code 3" + ) return False elif run_lead >= 0 or (run_lead >= -2 and self.behind_aggression > 5): - if tot_allowed < 5 or obc <= run_lead or (this_play.starting_outs == 2 and not is_starter): - logger.info(f'db_calls_gameplay - StratManagerAi - ID: {self.id} - go_to_reliever: False / code 4') + if ( + tot_allowed < 5 + or obc <= run_lead + or (this_play.starting_outs == 2 and not is_starter) + ): + logger.info( + f"db_calls_gameplay - StratManagerAi - ID: {self.id} - go_to_reliever: False / code 4" + ) return False elif run_lead >= -3 and self.behind_aggression > 5: if tot_allowed < 5 and obc <= 1: - logger.info(f'db_calls_gameplay - StratManagerAi - ID: {self.id} - go_to_reliever: False / code 5') + logger.info( + f"db_calls_gameplay - StratManagerAi - ID: {self.id} - go_to_reliever: False / code 5" + ) return False elif run_lead <= -5: if is_starter and this_play.inning_num <= 3: - logger.info(f'db_calls_gameplay - StratManagerAi - ID: {self.id} - go_to_reliever: False / code 6') + logger.info( + f"db_calls_gameplay - StratManagerAi - ID: {self.id} - go_to_reliever: False / code 6" + ) return False if this_play.starting_outs != 0: - logger.info(f'db_calls_gameplay - StratManagerAi - ID: {self.id} - go_to_reliever: False / code 7') + logger.info( + f"db_calls_gameplay - StratManagerAi - ID: {self.id} - go_to_reliever: False / code 7" + ) return False return True - def convert_strat_manager(manager: ManagerAi) -> StratManagerAi: manager_dict = model_to_dict(manager) return StratManagerAi(**manager_dict) @@ -2450,21 +2808,20 @@ def get_manager(game) -> Optional[StratManagerAi]: # manager_ai_id = game.home_team_id if game.ai_team == 'home' else game.away_team_id # manager_ai_id = 1 - team_id = game.home_team_id if game.ai_team == 'home' else game.away_team_id + team_id = game.home_team_id if game.ai_team == "home" else game.away_team_id manager_ai_id = ((datetime.datetime.now().day * team_id) % 3) + 1 if manager_ai_id > 3 or manager_ai_id < 1: manager_ai_id = 1 - logger.debug(f'manager id: {manager_ai_id} for game {game}') + logger.debug(f"manager id: {manager_ai_id} for game {game}") try: this_manager = ManagerAi.get_by_id(manager_ai_id) except Exception as e: - e_message = f'Could not find manager id {manager_ai_id}' - logger.error(f'{e_message}: {type(e)}: {e}') - raise KeyError(f'Could not find this AI manager\'s playbook') + e_message = f"Could not find manager id {manager_ai_id}" + logger.error(f"{e_message}: {type(e)}: {e}") + raise KeyError(f"Could not find this AI manager's playbook") return convert_strat_manager(this_manager) db.close() -