Download backend/analysis.py from rj7002/CourtIQ: direct link, hf CLI and curl.
- Browser
- Download file 35.6 kB
-
https://huggingface.co/spaces/rj7002/CourtIQ/resolve/main/backend/analysis.py
- Command line
-
hf download hf://spaces/rj7002/CourtIQ/backend/analysis.py
-
curl -L -o analysis.py https://huggingface.co/spaces/rj7002/CourtIQ/resolve/main/backend/analysis.py
35.6 kB
| """ | |
| Core analytics engine. | |
| WOWY uses all play-types; xFG uses shot rows only. | |
| Both read from the same CSV. | |
| """ | |
| import os | |
| import math | |
| import numpy as np | |
| import pandas as pd | |
| import joblib | |
| from concurrent.futures import ThreadPoolExecutor, as_completed | |
| from courtCoordinates import CourtCoordinates | |
| def _clean_records(records): | |
| """Replace float NaN/Inf with None in a list of dicts from to_dict().""" | |
| out = [] | |
| for rec in records: | |
| out.append({ | |
| k: (None if isinstance(v, float) and not math.isfinite(v) else v) | |
| for k, v in rec.items() | |
| }) | |
| return out | |
| # DATA_PATH = os.path.join(os.path.dirname(__file__), '..', 'download (4).csv') | |
| DATA_PATH = '/Users/ryan/Downloads/download (8).csv' | |
| MODEL_DIR = os.path.join(os.path.dirname(__file__), '..', 'model_export') | |
| BASKET_LEFT_X = 47.0 | |
| BASKET_RIGHT_X = 893.0 | |
| BASKET_Y = 250.0 | |
| COURT_LEN = 940.0 | |
| THREE_PT_DIST = 218.0 | |
| FGA_TYPES = {'JumpShot', 'LayUpShot', 'DunkShot', 'TipShot'} | |
| TOV_TYPES = {'Lost Ball Turnover'} | |
| # --------------------------------------------------------------------------- | |
| # Data loading | |
| # --------------------------------------------------------------------------- | |
| def load_df(): | |
| df = pd.read_csv(DATA_PATH, low_memory=False) | |
| df = df.sort_values( | |
| ['GameId', 'Period', 'SecondsRemaining'], | |
| ascending=[True, True, False] | |
| ).reset_index(drop=True) | |
| return df | |
| def get_team(df): | |
| return df['Team'].value_counts().idxmax() | |
| # --------------------------------------------------------------------------- | |
| # WOWY | |
| # --------------------------------------------------------------------------- | |
| def _get_lineup(row, team, on_floor_cols): | |
| players = [] | |
| for nc, tc in on_floor_cols: | |
| if row[tc] == team and pd.notna(row[nc]): | |
| players.append(row[nc]) | |
| return tuple(sorted(players)) if len(players) == 5 else None | |
| def _stint_stats(s): | |
| fga = s[s['PlayType'].isin(FGA_TYPES)] | |
| made = fga[fga['ScoringPlay'].astype(str).str.lower() == 'true'] | |
| made3 = made[made['ScoreValue'].astype(float, errors='ignore') == 3] | |
| is_3 = fga['PlayText'].str.contains('Three Point', na=False) | |
| ftm = int((s['PlayType'] == 'MadeFreeThrow').sum()) | |
| fta = int(s['PlayType'].isin(['MadeFreeThrow', 'MissedFreeThrow']).sum()) | |
| orb = int((s['PlayType'] == 'Offensive Rebound').sum()) | |
| drb = int((s['PlayType'] == 'Defensive Rebound').sum()) | |
| tov = int(s['PlayType'].isin(TOV_TYPES).sum()) | |
| poss = max(len(fga) + 0.44 * fta + tov - orb, 0.1) | |
| return { | |
| 'pts': s[s['ScoringPlay'].astype(str).str.lower() == 'true']['ScoreValue'] | |
| .astype(float, errors='ignore').sum(), | |
| 'fga': len(fga), | |
| 'fgm': len(made), | |
| 'fga3': int(is_3.sum()), | |
| 'fgm3': len(made3), | |
| 'ftm': ftm, | |
| 'orb': orb, | |
| 'drb': drb, | |
| 'tov': tov, | |
| 'ast': int(s['PlayText'].str.contains('Assisted by', na=False).sum()), | |
| 'poss': poss, | |
| } | |
| def _compute_stats(s): | |
| m = {k: s[f'm_{k}'].sum() for k in ['pts','fga','fgm','fga3','fgm3','ftm','orb','drb','tov','ast','poss']} | |
| o = {k: s[f'o_{k}'].sum() for k in ['pts','fga','fgm','fga3','fgm3','ftm','orb','drb','tov','ast','poss']} | |
| def safe(n, d, scale=1): | |
| if d == 0: return None | |
| result = float(n) / float(d) * scale | |
| return round(result, 1) if result == result else None # NaN guard | |
| off_rtg = safe(m['pts'], m['poss'], 100) | |
| def_rtg = safe(o['pts'], o['poss'], 100) | |
| return { | |
| 'off_rtg': off_rtg, | |
| 'def_rtg': def_rtg, | |
| 'net_rtg': round((off_rtg or 0) - (def_rtg or 0), 1), | |
| 'off_efg': safe(m['fgm'] + 0.5 * m['fgm3'], m['fga'], 100), | |
| # 'off_3pt': safe(m['fgm3'], m['fga3'], 100), | |
| 'off_3rate': safe(m['fga3'], m['fga'], 100), | |
| 'off_tov': safe(m['tov'], m['poss'], 100), | |
| 'off_orb': safe(m['orb'], m['orb'] + o['drb'], 100), | |
| 'off_ftrate': safe(m['ftm'], m['fga'], 100), | |
| 'off_ast': safe(m['ast'], m['fgm'], 100), | |
| 'def_efg': safe(o['fgm'] + 0.5 * o['fgm3'], o['fga'], 100), | |
| # 'def_3pt': safe(o['fgm3'], o['fga3'], 100), | |
| 'def_3rate': safe(o['fga3'], o['fga'], 100), | |
| 'def_tov': safe(o['tov'], o['poss'], 100), | |
| 'def_drb': safe(m['drb'], m['drb'] + o['orb'], 100), | |
| 'def_ftrate': safe(o['ftm'], o['fga'], 100), | |
| 'poss': m['poss'], | |
| } | |
| def build_stints(df, team): | |
| cols = [(f'OnFloor[{i}] Name', f'OnFloor[{i}] Team') for i in range(10)] | |
| plays = df.copy() | |
| plays['lineup'] = plays.apply(lambda r: _get_lineup(r, team, cols), axis=1) | |
| plays = plays[plays['lineup'].notna()].copy() | |
| changed = ( | |
| (plays['lineup'] != plays['lineup'].shift(1)) | | |
| (plays['GameId'] != plays['GameId'].shift(1)) | | |
| (plays['Period'] != plays['Period'].shift(1)) | |
| ) | |
| plays['stint_id'] = changed.cumsum() | |
| rows = [] | |
| for sid, s in plays.groupby('stint_id'): | |
| mich = s[s['Team'] == team] | |
| opp = s[s['Team'] != team] | |
| ms = _stint_stats(mich) | |
| os_ = _stint_stats(opp) | |
| sec = max(float(s['SecondsRemaining'].iloc[0]) - float(s['SecondsRemaining'].iloc[-1]), 0) | |
| row = {'stint_id': sid, 'game_id': s['GameId'].iloc[0], | |
| 'period': s['Period'].iloc[0], 'lineup': s['lineup'].iloc[0], 'seconds': sec} | |
| for k, v in ms.items(): row[f'm_{k}'] = v | |
| for k, v in os_.items(): row[f'o_{k}'] = v | |
| rows.append(row) | |
| return pd.DataFrame(rows) | |
| def compute_wowy(stints, min_seconds_with=1800, min_seconds_without=1800, lg_ortg=None): | |
| all_players = set() | |
| for lu in stints['lineup']: | |
| all_players.update(lu) | |
| records = [] | |
| for player in sorted(all_players): | |
| with_s = stints[stints['lineup'].apply(lambda l: player in l)] | |
| without_s = stints[stints['lineup'].apply(lambda l: player not in l)] | |
| if (with_s['seconds'].sum() < min_seconds_with or | |
| without_s['seconds'].sum() < min_seconds_without): | |
| continue | |
| w = _compute_stats(with_s) | |
| wo = _compute_stats(without_s) | |
| row = { | |
| 'player': player, | |
| 'with_min': round(with_s['seconds'].sum() / 60, 1), | |
| 'without_min': round(without_s['seconds'].sum() / 60, 1), | |
| } | |
| for stat in w: | |
| row[f'with_{stat}'] = w[stat] | |
| row[f'wo_{stat}'] = wo[stat] | |
| # flip = stat in ('def_rtg','def_efg','def_3pt','def_3rate','def_ftrate','off_tov') | |
| flip = stat in ('def_rtg','def_efg','def_3rate','def_ftrate','off_tov') | |
| delta = ((wo[stat] or 0) - (w[stat] or 0)) if flip else ((w[stat] or 0) - (wo[stat] or 0)) | |
| row[f'd_{stat}'] = round(delta, 1) | |
| row['delta_netRtg'] = round(row['d_off_rtg'] + row['d_def_rtg'], 1) | |
| off_rtg_with = w.get('off_rtg') | |
| row['adj_off_rtg_plus'] = round(off_rtg_with - lg_ortg, 1) if (off_rtg_with is not None and lg_ortg is not None) else None | |
| records.append(row) | |
| return pd.DataFrame(records).sort_values('delta_netRtg', ascending=False).reset_index(drop=True) | |
| def compute_lineup_stats(stints, top_n=20): | |
| lu_groups = stints.groupby('lineup') | |
| rows = [] | |
| for lu, grp in lu_groups: | |
| secs = grp['seconds'].sum() | |
| if secs < 600: | |
| continue | |
| st = _compute_stats(grp) | |
| rows.append({ | |
| 'lineup': ' / '.join(lu), | |
| 'players': list(lu), | |
| 'minutes': round(secs / 60, 1), | |
| **st, | |
| }) | |
| df = pd.DataFrame(rows).sort_values('net_rtg', ascending=False).reset_index(drop=True) | |
| return df.head(top_n) | |
| # --------------------------------------------------------------------------- | |
| # xFG (features mirror xfg_model.ipynb β trained on pbp_shots_data.csv) | |
| # --------------------------------------------------------------------------- | |
| def compute_xfg(df, team): | |
| model, feats = _load_xfg_model() | |
| shots = df[ | |
| (df['ShotInfo Range'].notna()) & | |
| (df['ShotInfo Range'] != 'free_throw') & | |
| (df['ShotInfo Made'].notna()) & | |
| (df['Team'] == team) | |
| ].copy().reset_index(drop=True) | |
| shots['_made'] = ( | |
| shots['ShotInfo Made'].astype(str).str.lower() | |
| .map({'true': 1, 'false': 0}).fillna(0).astype(int) | |
| ) | |
| # --- Location (coordinates / 10 = feet) --- | |
| x = shots['ShotInfo Location X'].astype(float) | |
| y = shots['ShotInfo Location Y'].astype(float) | |
| shooting_right = x >= (COURT_LEN / 2) | |
| basket_x = np.where(shooting_right, BASKET_RIGHT_X, BASKET_LEFT_X) | |
| dy = np.where(shooting_right, BASKET_RIGHT_X - x, x - BASKET_LEFT_X).clip(min=0) / 10 | |
| abs_dx = np.abs(y - BASKET_Y) / 10 | |
| dist_ft = np.sqrt((x - basket_x)**2 + (y - BASKET_Y)**2) / 10 | |
| angle = np.degrees(np.arctan2(abs_dx, np.where(dy < 0.1, 0.1, dy))) | |
| shots['shotDist'] = dist_ft | |
| shots['shotDist_sq'] = dist_ft ** 2 | |
| shots['shotDist_log'] = np.log1p(dist_ft) | |
| shots['dy'] = dy | |
| shots['abs_dx'] = abs_dx | |
| shots['angle_to_basket'] = angle | |
| # --- Shot type --- | |
| shots['is_three'] = (shots['ShotInfo Range'] == 'three_pointer').astype(int) | |
| shots['is_rim'] = (shots['ShotInfo Range'] == 'rim').astype(int) | |
| shots['is_midrange'] = (shots['ShotInfo Range'] == 'jumper').astype(int) | |
| shots['is_dunk_layup'] = shots['PlayType'].isin({'LayUpShot', 'DunkShot', 'TipShot'}).astype(int) | |
| shots['is_corner_three'] = ((shots['is_three'] == 1) & (angle >= 65)).astype(int) | |
| shots['is_wing_three'] = ((shots['is_three'] == 1) & (angle < 65)).astype(int) | |
| shots['in_paint'] = (shots['shotDist'].fillna(999) < 8).astype(int) | |
| shots['dist_x_angle'] = shots['shotDist'].fillna(0) * pd.Series(angle, index=shots.index).fillna(45) | |
| # --- Game context --- | |
| is_home = shots['IsHomeTeam'].astype(str).str.lower().map({'true': 1, 'false': 0}).fillna(0) | |
| shots['possTeamIsHome'] = is_home | |
| shots['homeScore'] = shots['HomeScore'].fillna(0).astype(float) | |
| shots['awayScore'] = shots['AwayScore'].fillna(0).astype(float) | |
| shots['score_diff_shooter'] = np.where( | |
| is_home.astype(bool), | |
| shots['homeScore'] - shots['awayScore'], | |
| shots['awayScore'] - shots['homeScore'], | |
| ) | |
| shots['periodNumber'] = shots['Period'].fillna(1).astype(float) | |
| shots['is_second_half'] = (shots['Period'].fillna(1) == 2).astype(int) | |
| # --- Previous action --- | |
| prev_text = shots['PlayText'].shift(1).fillna('') | |
| same_game = shots['GameId'] == shots['GameId'].shift(1) | |
| shots['prev_is_rebound'] = (same_game & prev_text.str.contains('Rebound', case=False, na=False)).astype(int) | |
| shots['prev_is_pass'] = (same_game & prev_text.str.contains('Assist|Pass', case=False, na=False)).astype(int) | |
| # --- Player rolling FG% (shift(1) so only past shots inform each row) --- | |
| LEAGUE_AVG_FG = 0.444 | |
| LEAGUE_AVG_3PT = 0.340 | |
| LEAGUE_AVG_RIM = 0.584 | |
| LEAGUE_AVG_MID = 0.399 | |
| RANGE_PRIORS = {'rim': LEAGUE_AVG_RIM, 'jumper': LEAGUE_AVG_MID, 'three_pointer': LEAGUE_AVG_3PT} | |
| def _rolling_pct(series, prior): | |
| cumsum = series.cumsum().shift(1).fillna(0) | |
| cumcnt = pd.Series(range(len(series)), index=series.index) | |
| return (cumsum / cumcnt.clip(lower=1)).where(cumcnt > 0, prior) | |
| shots['shooter_fg_pct'] = ( | |
| shots.groupby('ShotInfo Shooter Id')['_made'] | |
| .transform(lambda x: _rolling_pct(x, LEAGUE_AVG_FG)) | |
| ) | |
| for rng, prior in RANGE_PRIORS.items(): | |
| col = f'shooter_{rng}_pct' | |
| mask = shots['ShotInfo Range'] == rng | |
| pct = (shots[mask] | |
| .groupby('ShotInfo Shooter Id')['_made'] | |
| .transform(lambda x, p=prior: _rolling_pct(x, p))) | |
| shots[col] = prior | |
| shots.loc[mask, col] = pct.values | |
| shots['shooter_range_pct'] = np.where( | |
| shots['ShotInfo Range'] == 'rim', shots['shooter_rim_pct'], | |
| np.where(shots['ShotInfo Range'] == 'jumper', shots['shooter_jumper_pct'], | |
| shots['shooter_three_pointer_pct']) | |
| ) | |
| shots['hot_hand'] = ( | |
| shots.groupby('ShotInfo Shooter Id')['_made'] | |
| .transform(lambda x: x.shift(1).fillna(0.5)) | |
| ) | |
| shots['last5_fg_pct'] = ( | |
| shots.groupby('ShotInfo Shooter Id')['_made'] | |
| .transform(lambda x: x.shift(1).rolling(5, min_periods=1).mean().fillna(LEAGUE_AVG_FG)) | |
| ) | |
| # H1 FG% (shots in period 1) | |
| shots['_period_bin'] = (shots['Period'].fillna(1) >= 2).astype(int) | |
| for pb, label in [(0, 'h1'), (1, 'h2')]: | |
| mask = shots['_period_bin'] == pb | |
| pct = (shots[mask] | |
| .groupby('ShotInfo Shooter Id')['_made'] | |
| .transform(lambda x: _rolling_pct(x, LEAGUE_AVG_FG))) | |
| shots[f'shooter_{label}_pct'] = LEAGUE_AVG_FG | |
| shots.loc[mask, f'shooter_{label}_pct'] = pct.values | |
| shots.drop(columns=['_period_bin'], inplace=True) | |
| # --- Lineup quality (avg season FG% of the 5 on-floor teammates) --- | |
| TEAM_SLOTS = [f'OnFloor[{i}] Id' for i in range(5)] | |
| season_player_fg = shots.groupby('ShotInfo Shooter Id')['_made'].mean() | |
| for i in range(5): | |
| shots[f'_lp_fg_{i}'] = shots[TEAM_SLOTS[i]].map(season_player_fg).fillna(LEAGUE_AVG_FG) | |
| shots['lineup_avg_fg'] = shots[[f'_lp_fg_{i}' for i in range(5)]].mean(axis=1) | |
| shots.drop(columns=[f'_lp_fg_{i}' for i in range(5)], inplace=True) | |
| # --- Interaction features --- | |
| shots['skill_x_dist'] = shots['shooter_range_pct'] * shots['shotDist'] | |
| shots['skill_x_dist_sq'] = shots['shooter_range_pct'] * shots['shotDist_sq'] | |
| shots['dist_x_range_pct'] = shots['shotDist'] * shots['shooter_fg_pct'] | |
| shots['paint_x_layup'] = shots['in_paint'] * shots['is_dunk_layup'] | |
| shots['hot_x_skill'] = shots['hot_hand'] * shots['shooter_range_pct'] | |
| shots['last5_x_skill'] = shots['last5_fg_pct'] * shots['shooter_range_pct'] | |
| shots['xfg'] = model.predict_proba(shots[feats].fillna(0))[:, 1] | |
| return shots | |
| def player_xfg_summary(shots_with_xfg): | |
| grp = shots_with_xfg.groupby('ShotInfo Shooter Name') | |
| rows = [] | |
| for name, g in grp: | |
| if len(g) < 15: | |
| continue | |
| is_three = (g['ShotInfo Range'] == 'three_pointer') | |
| fga = len(g) | |
| actual_efg = (g['_made'].sum() + 0.5 * (g['_made'] * is_three).sum()) / fga | |
| xfg_efg = (g['xfg'] * (1 + 0.5 * is_three)).sum() / fga | |
| by_range = {} | |
| for rng in ('rim', 'jumper', 'three_pointer'): | |
| sub = g[g['ShotInfo Range'] == rng] | |
| if len(sub) >= 5: | |
| sub_is_three = (sub['ShotInfo Range'] == 'three_pointer') | |
| sub_fga = len(sub) | |
| sub_act = (sub['_made'].sum() + 0.5 * (sub['_made'] * sub_is_three).sum()) / sub_fga | |
| sub_xfg = (sub['xfg'] * (1 + 0.5 * sub_is_three)).sum() / sub_fga | |
| by_range[rng] = { | |
| 'attempts': sub_fga, | |
| 'actual': round(sub_act, 3), | |
| 'xfg': round(sub_xfg, 3), | |
| 'diff': round(sub_act - sub_xfg, 3), | |
| } | |
| rows.append({ | |
| 'player': name, | |
| 'attempts': fga, | |
| 'actual_fg': round(actual_efg, 3), | |
| 'xfg': round(xfg_efg, 3), | |
| 'diff': round(actual_efg - xfg_efg, 3), | |
| 'by_range': by_range, | |
| 'shot_quality': round(xfg_efg, 3), | |
| }) | |
| return sorted(rows, key=lambda r: -r['attempts']) | |
| def lineup_xfg_summary(shots_with_xfg): | |
| cols = [(f'OnFloor[{i}] Name', f'OnFloor[{i}] Team') for i in range(10)] | |
| team = shots_with_xfg['Team'].iloc[0] | |
| def get_lu(row): | |
| players = [row[nc] for nc, tc in cols if row[tc] == team and pd.notna(row[nc])] | |
| return tuple(sorted(players)) if len(players) == 5 else None | |
| shots_with_xfg = shots_with_xfg.copy() | |
| shots_with_xfg['lineup'] = shots_with_xfg.apply(get_lu, axis=1) | |
| shots_with_xfg = shots_with_xfg[shots_with_xfg['lineup'].notna()] | |
| grp = shots_with_xfg.groupby('lineup') | |
| rows = [] | |
| for lu, g in grp: | |
| if len(g) < 10: | |
| continue | |
| is_three = (g['ShotInfo Range'] == 'three_pointer') | |
| fga = len(g) | |
| actual_efg = (g['_made'].sum() + 0.5 * (g['_made'] * is_three).sum()) / fga | |
| xfg_efg = (g['xfg'] * (1 + 0.5 * is_three)).sum() / fga | |
| rows.append({ | |
| 'lineup': ' / '.join(lu), | |
| 'players': list(lu), | |
| 'fga': len(g), | |
| 'actual_efg': round(actual_efg * 100, 1), | |
| 'xfg_efg': round(xfg_efg * 100, 1), | |
| 'diff': round((actual_efg - xfg_efg) * 100, 1), | |
| }) | |
| return sorted(rows, key=lambda r: -r['xfg_efg']) | |
| # --------------------------------------------------------------------------- | |
| # N-man lineup stats (used by /api/lineup-size) | |
| # --------------------------------------------------------------------------- | |
| def compute_nman_lineups(stints, shots, n, min_seconds=600, top_n=25, include_players=None): | |
| from itertools import combinations as iter_combos | |
| all_players = sorted({p for lu in stints['lineup'] for p in lu}) | |
| include_set = set(include_players or []) | |
| total_o_fga3 = float(stints['o_fga3'].sum()) | |
| total_o_fgm3 = float(stints['o_fgm3'].sum()) | |
| D1_3PT_PCT = total_o_fgm3 / total_o_fga3 if total_o_fga3 > 0 else 0.34 | |
| # Pre-tag shots once so we can compute xFG for any combo | |
| shots_tagged = None | |
| if shots is not None and len(shots): | |
| team = shots['Team'].iloc[0] | |
| cols = [(f'OnFloor[{i}] Name', f'OnFloor[{i}] Team') for i in range(10)] | |
| def _tag(row): | |
| ps = frozenset(row[nc] for nc, tc in cols | |
| if row[tc] == team and pd.notna(row[nc])) | |
| return ps if len(ps) == 5 else None | |
| shots_tagged = shots.copy() | |
| shots_tagged['_lineup_set'] = shots_tagged.apply(_tag, axis=1) | |
| rows = [] | |
| for combo in iter_combos(all_players, n): | |
| if include_set and not include_set.issubset(combo): | |
| continue | |
| cs = frozenset(combo) | |
| mask = stints['lineup'].apply(lambda l, cs=cs: cs.issubset(l)) | |
| grp = stints[mask] | |
| secs = float(grp['seconds'].sum()) | |
| if secs < min_seconds: | |
| continue | |
| st = _compute_stats(grp) | |
| row = { | |
| 'lineup': ' / '.join(combo), | |
| 'players': list(combo), | |
| 'minutes': round(secs / 60, 1), | |
| **st, | |
| } | |
| xd = None | |
| if shots_tagged is not None: | |
| xd = _xfg_for_combo(shots_tagged, cs, frozenset()) | |
| if xd: | |
| row['fga'] = xd['shot_n'] | |
| row['xfg_efg'] = xd['xfg'] | |
| row['actual_efg'] = xd['actual_fg'] | |
| row['diff'] = xd['fg_diff'] | |
| # Luck-adjusted ratings | |
| poss = st.get('poss') or 0 | |
| adj_off = adj_def = None | |
| if xd and poss > 0 and xd.get('shot_n') and st.get('off_rtg') is not None: | |
| adj_off = round(st['off_rtg'] - xd['fg_diff'] * 2 * xd['shot_n'] / poss, 1) | |
| o_fga3 = float(grp['o_fga3'].sum()) | |
| o_fgm3 = float(grp['o_fgm3'].sum()) | |
| o_poss = float(grp['o_poss'].sum()) | |
| if o_fga3 > 0 and o_poss > 0 and st.get('def_rtg') is not None: | |
| luck_def = (o_fgm3 / o_fga3 - D1_3PT_PCT) * 3 * o_fga3 / o_poss * 100 | |
| adj_def = round(st['def_rtg'] - luck_def, 1) | |
| row['adj_off_rtg'] = adj_off | |
| row['adj_def_rtg'] = adj_def | |
| row['adj_net_rtg'] = round(adj_off - adj_def, 1) if adj_off is not None and adj_def is not None else None | |
| rows.append(row) | |
| if not rows: | |
| return [] | |
| df = pd.DataFrame(rows).sort_values('net_rtg', ascending=False) | |
| if top_n: | |
| df = df.head(top_n) | |
| return _clean_records(df.to_dict(orient='records')) | |
| # --------------------------------------------------------------------------- | |
| # Interactive lineup combo (notebook-style WOWY) | |
| # --------------------------------------------------------------------------- | |
| def _xfg_for_combo(shots_tagged, on_set, off_set): | |
| """Return xeFG stats for shots taken while on_set is on / off_set is off.""" | |
| mask = shots_tagged['_lineup_set'].apply( | |
| lambda l: l is not None and | |
| all(p in l for p in on_set) and | |
| all(p not in l for p in off_set) | |
| ) | |
| s = shots_tagged[mask] | |
| if len(s) < 3: | |
| return None | |
| fga = len(s) | |
| is_three = (s['ShotInfo Range'] == 'three_pointer') | |
| # actual eFG% = (FGM + 0.5 * FGM3) / FGA | |
| actual_efg = (s['_made'].sum() + 0.5 * (s['_made'] * is_three).sum()) / fga | |
| # xeFG% = sum(xfg_prob * (1 + 0.5 * is_three)) / FGA β weights 3s for their extra point | |
| xfg_efg = (s['xfg'] * (1 + 0.5 * is_three)).sum() / fga | |
| return { | |
| 'shot_n': fga, | |
| 'xfg': round(xfg_efg * 100, 1), | |
| 'actual_fg': round(actual_efg * 100, 1), | |
| 'fg_diff': round((actual_efg - xfg_efg) * 100, 1), | |
| } | |
| def compute_lineup_combos(stints, selected_players, min_seconds=120, shots=None): | |
| from itertools import combinations as iter_combos | |
| # Pre-compute per-shot lineup set once (cheap filter later) | |
| shots_tagged = None | |
| if shots is not None and len(shots): | |
| team = shots['Team'].iloc[0] | |
| cols = [(f'OnFloor[{i}] Name', f'OnFloor[{i}] Team') for i in range(10)] | |
| def _shot_lineup(row): | |
| ps = frozenset(row[nc] for nc, tc in cols | |
| if row[tc] == team and pd.notna(row[nc])) | |
| return ps if len(ps) == 5 else None | |
| shots_tagged = shots.copy() | |
| shots_tagged['_lineup_set'] = shots_tagged.apply(_shot_lineup, axis=1) | |
| # Season-average opponent 3PT% β used as "expected" rate for defensive adjustment | |
| total_o_fga3 = float(stints['o_fga3'].sum()) | |
| total_o_fgm3 = float(stints['o_fgm3'].sum()) | |
| D1_3PT_PCT = total_o_fgm3 / total_o_fga3 if total_o_fga3 > 0 else 0.34 | |
| n = len(selected_players) | |
| combo_stats = {} | |
| combo_secs = {} | |
| combo_xfg = {} | |
| combo_def3 = {} # key β (o_fga3, o_fgm3, o_poss) | |
| for r in range(n + 1): | |
| for on_tup in iter_combos(selected_players, r): | |
| on_set = frozenset(on_tup) | |
| off_set = frozenset(selected_players) - on_set | |
| mask = stints['lineup'].apply( | |
| lambda l, on=on_set, off=off_set: | |
| all(p in l for p in on) and all(p not in l for p in off) | |
| ) | |
| s = stints[mask] | |
| key = tuple(sorted(on_set)) | |
| combo_stats[key] = _compute_stats(s) if len(s) else None | |
| combo_secs[key] = float(s['seconds'].sum()) if len(s) else 0.0 | |
| if len(s): | |
| combo_def3[key] = ( | |
| float(s['o_fga3'].sum()), | |
| float(s['o_fgm3'].sum()), | |
| float(s['o_poss'].sum()), | |
| ) | |
| if shots_tagged is not None: | |
| combo_xfg[key] = _xfg_for_combo(shots_tagged, on_set, off_set) | |
| def combo_label(on_set): | |
| return [{'player': p, 'on': p in on_set} for p in selected_players] | |
| def _luck_adjusted(st, xq, d3): | |
| """Return (adj_off_rtg, adj_def_rtg, adj_net_rtg) or (None, None, None).""" | |
| poss = st.get('poss') or 0 | |
| adj_off = adj_def = None | |
| # Offensive: xFG-based β remove luck from field-goal shooting | |
| if xq and poss > 0 and xq.get('shot_n') and st.get('off_rtg') is not None: | |
| luck_off = xq['fg_diff'] * 2 * xq['shot_n'] / poss | |
| adj_off = round(st['off_rtg'] - luck_off, 1) | |
| # Defensive: 3PT-based β remove luck from opponent 3PT shooting | |
| if d3 and poss > 0: | |
| o_fga3, o_fgm3, o_poss = d3 | |
| if o_fga3 > 0 and o_poss > 0 and st.get('def_rtg') is not None: | |
| luck_def = (o_fgm3 / o_fga3 - D1_3PT_PCT) * 3 * o_fga3 / o_poss * 100 | |
| adj_def = round(st['def_rtg'] - luck_def, 1) | |
| adj_net = round(adj_off - adj_def, 1) if adj_off is not None and adj_def is not None else None | |
| return adj_off, adj_def, adj_net | |
| # --- Table 1: raw stats per combination --- | |
| raw = [] | |
| for key, st in combo_stats.items(): | |
| on_set = frozenset(key) | |
| secs = combo_secs[key] | |
| if secs < min_seconds or st is None: | |
| continue | |
| row = { | |
| 'on_count': len(on_set), | |
| 'combo': combo_label(on_set), | |
| 'minutes': round(secs / 60, 1), | |
| **{k: v for k, v in st.items()}, | |
| } | |
| xq = combo_xfg.get(key) | |
| if xq: | |
| row.update(xq) | |
| adj_off, adj_def, adj_net = _luck_adjusted(st, xq, combo_def3.get(key)) | |
| row['adj_off_rtg'] = adj_off | |
| row['adj_def_rtg'] = adj_def | |
| row['adj_net_rtg'] = adj_net | |
| raw.append(row) | |
| raw.sort(key=lambda r: (-r['on_count'], -(r['net_rtg'] or 0))) | |
| # --- Table 2: on-off delta pairs (each unique pair once) --- | |
| # FLIP = {'def_rtg','def_efg','def_3pt','def_3rate','def_ftrate','off_tov','def_rtg_pad'} | |
| FLIP = {'def_rtg','def_efg','def_3rate','def_ftrate','off_tov','def_rtg_pad'} | |
| seen = set() | |
| deltas = [] | |
| for key in combo_stats: | |
| on_set = frozenset(key) | |
| off_set = frozenset(selected_players) - on_set | |
| if on_set == off_set: | |
| continue | |
| pair_key = frozenset([on_set, off_set]) | |
| if pair_key in seen: | |
| continue | |
| seen.add(pair_key) | |
| # larger set is "ON"; ties broken alphabetically | |
| if len(on_set) > len(off_set): | |
| side_on, side_off = on_set, off_set | |
| elif len(off_set) > len(on_set): | |
| side_on, side_off = off_set, on_set | |
| else: | |
| la = ' '.join(sorted(on_set)) | |
| lb = ' '.join(sorted(off_set)) | |
| side_on, side_off = (on_set, off_set) if la < lb else (off_set, on_set) | |
| k_on = tuple(sorted(side_on)) | |
| k_off = tuple(sorted(side_off)) | |
| st_on = combo_stats.get(k_on) | |
| st_off = combo_stats.get(k_off) | |
| s_on = combo_secs.get(k_on, 0) | |
| s_off = combo_secs.get(k_off, 0) | |
| if s_on < min_seconds or s_off < min_seconds or st_on is None or st_off is None: | |
| continue | |
| d = { | |
| 'on_combo': combo_label(side_on), | |
| 'off_combo': combo_label(side_off), | |
| 'min_on': round(s_on / 60, 1), | |
| 'min_off': round(s_off / 60, 1), | |
| } | |
| for stat in st_on: | |
| v_on = st_on[stat] | |
| v_off = st_off[stat] | |
| if v_on is None or v_off is None: | |
| d[f'd_{stat}'] = None | |
| else: | |
| d[f'd_{stat}'] = round( | |
| (v_off - v_on) if stat in FLIP else (v_on - v_off), 1 | |
| ) | |
| # xFG deltas β positive always means better for the ON side | |
| xq_on = combo_xfg.get(k_on) | |
| xq_off = combo_xfg.get(k_off) | |
| if xq_on and xq_off: | |
| d['d_xfg'] = round(xq_on['xfg'] - xq_off['xfg'], 1) | |
| d['d_actual_fg'] = round(xq_on['actual_fg'] - xq_off['actual_fg'], 1) | |
| d['d_fg_diff'] = round(xq_on['fg_diff'] - xq_off['fg_diff'], 1) | |
| deltas.append(d) | |
| deltas.sort(key=lambda r: -(r.get('d_net_rtg') or 0)) | |
| return {'raw': raw, 'deltas': deltas} | |
| def get_roster_with_minutes(stints): | |
| mins = {} | |
| for _, row in stints.iterrows(): | |
| for p in row['lineup']: | |
| mins[p] = mins.get(p, 0) + row['seconds'] | |
| return [ | |
| {'player': p, 'minutes': round(s / 60, 1)} | |
| for p, s in sorted(mins.items(), key=lambda x: -x[1]) | |
| ] | |
| # --------------------------------------------------------------------------- | |
| # Shot chart zones | |
| # --------------------------------------------------------------------------- | |
| def _classify_zone(shot_dist, angle, is_three, y_raw, play_type): | |
| is_right = (y_raw or 250) > 250 | |
| if shot_dist < 4 or play_type in ('DunkShot', 'TipShot'): | |
| return 'atr2' | |
| if is_three and angle >= 65: | |
| return 'rc3' if is_right else 'lc3' | |
| if is_three and angle > 20: | |
| return 'rw3' if is_right else 'lw3' | |
| if is_three: | |
| return 'tok3' | |
| if shot_dist < 12: | |
| return 'paint2' | |
| if angle > 45: | |
| return 'rb2' if is_right else 'lb2' | |
| return 're2' if is_right else 'le2' | |
| def compute_shot_zones(shots): | |
| s = shots.copy() | |
| s['zone'] = [ | |
| _classify_zone( | |
| row['shotDist'], row['angle_to_basket'], | |
| row['ShotInfo Range'] == 'three_pointer', | |
| row['ShotInfo Location Y'], row['PlayType'] | |
| ) | |
| for _, row in s.iterrows() | |
| ] | |
| all_zones = ['atr2','paint2','lb2','rb2','le2','re2','lc3','rc3','lw3','rw3','tok3'] | |
| def _zone_stats(grp): | |
| out = {} | |
| for z in all_zones: | |
| g = grp[grp['zone'] == z] | |
| if len(g) == 0: | |
| out[z] = None | |
| continue | |
| out[z] = { | |
| 'n': len(g), | |
| 'actual_fg': round(g['_made'].mean() * 100, 1), | |
| 'xfg': round(g['xfg'].mean() * 100, 1), | |
| 'diff': round((g['_made'].mean() - g['xfg'].mean()) * 100, 1), | |
| } | |
| return out | |
| team_zones = _zone_stats(s) | |
| player_zones = {} | |
| for name, grp in s.groupby('ShotInfo Shooter Name'): | |
| if len(grp) < 10: | |
| continue | |
| player_zones[name] = _zone_stats(grp) | |
| return {'team': team_zones, 'players': player_zones} | |
| # --------------------------------------------------------------------------- | |
| # 3-D court helpers | |
| # --------------------------------------------------------------------------- | |
| _COURT_LINES = None | |
| def _get_court_lines(): | |
| global _COURT_LINES | |
| if _COURT_LINES is None: | |
| _COURT_LINES = CourtCoordinates("2024-2025").get_coordinates().to_dict(orient='records') | |
| return _COURT_LINES | |
| def _shots_to_court_coords(shots): | |
| """Map CBB shot coordinates (tenths-of-feet) to the CourtCoordinates system.""" | |
| df = shots.copy() | |
| x = df['ShotInfo Location X'].astype(float) | |
| y = df['ShotInfo Location Y'].astype(float) | |
| shooting_right = x >= (COURT_LEN / 2) | |
| # court_x: lateral position centred at 0 (court width axis) | |
| court_x = np.where(shooting_right, BASKET_Y - y, y - BASKET_Y) | |
| # court_y: depth from baseline; hoop sits at y=52 in CourtCoordinates | |
| court_y = np.where( | |
| shooting_right, | |
| BASKET_RIGHT_X - x + 52, | |
| x - BASKET_LEFT_X + 52, | |
| ).clip(0, 460) | |
| result = pd.DataFrame({ | |
| 'court_x': court_x.round(1), | |
| 'court_y': court_y.round(1), | |
| 'xfg': df['xfg'].round(3), | |
| 'made': df['_made'], | |
| 'range': df['ShotInfo Range'], | |
| 'dist': df['shotDist'].round(1), | |
| 'player': df['ShotInfo Shooter Name'].fillna('Unknown'), | |
| }) | |
| return _clean_records(result.to_dict(orient='records')) | |
| # --------------------------------------------------------------------------- | |
| # Cached entry point | |
| # --------------------------------------------------------------------------- | |
| _cache: dict = {} | |
| _analytics_cache: dict = {} # (team_lower, season) β snapshot of computed results | |
| _xfg_model = None | |
| _xfg_feats = None | |
| def _load_xfg_model(): | |
| global _xfg_model, _xfg_feats | |
| if _xfg_model is None: | |
| _xfg_model = joblib.load(os.path.join(MODEL_DIR, 'final_shot_quality_model.joblib')) | |
| _xfg_feats = joblib.load(os.path.join(MODEL_DIR, 'final_feature_list.joblib')) | |
| return _xfg_model, _xfg_feats | |
| def _populate_cache(df): | |
| """Run full analytics pipeline in parallel and populate _cache.""" | |
| _cache.clear() | |
| team = get_team(df) | |
| season = int(df['Season'].dropna().iloc[0]) if 'Season' in df.columns else DEFAULT_SEASON | |
| stints = build_stints(df, team) | |
| lg_ortg = float(stints['m_pts'].sum() / stints['m_poss'].sum() * 100) | |
| lg_drtg = float(stints['o_pts'].sum() / stints['o_poss'].sum() * 100) | |
| # Run independent analytics in parallel | |
| with ThreadPoolExecutor(max_workers=7) as ex: | |
| fut_wowy = ex.submit(compute_wowy, stints, lg_ortg=lg_ortg) | |
| fut_shots = ex.submit(compute_xfg, df, team) | |
| fut_lu_st = ex.submit(compute_lineup_stats, stints) | |
| fut_roster = ex.submit(get_roster_with_minutes, stints) | |
| fut_logo = ex.submit(_get_logo, team) | |
| fut_colors = ex.submit(_get_colors, team) | |
| fut_profiles = ex.submit(_get_player_profiles, team, season) | |
| wowy = fut_wowy.result() | |
| shots = fut_shots.result() | |
| lu_st = fut_lu_st.result() | |
| px = player_xfg_summary(shots) | |
| lx = lineup_xfg_summary(shots) | |
| colors = fut_colors.result() | |
| _cache['team'] = team | |
| _cache['league_avg'] = (lg_ortg, lg_drtg) | |
| _cache['season'] = int(df['Season'].dropna().iloc[0]) if 'Season' in df.columns else None | |
| _cache['logo_url'] = fut_logo.result() | |
| _cache['primary_color'] = colors.get('primary') | |
| _cache['secondary_color'] = colors.get('secondary') | |
| _cache['wowy'] = _clean_records(wowy.to_dict(orient='records')) | |
| _cache['player_xfg'] = px | |
| _cache['lineup_xfg'] = lx | |
| _cache['lineup_stats'] = _clean_records(lu_st.to_dict(orient='records')) | |
| _cache['games'] = int(df['GameId'].nunique()) | |
| _cache['stints'] = int(len(stints)) | |
| _cache['_stints'] = stints | |
| _cache['_shots'] = shots | |
| _cache['shot_zones'] = compute_shot_zones(shots) | |
| _cache['roster'] = fut_roster.result() | |
| _cache['player_profiles'] = fut_profiles.result() | |
| _cache['court_lines'] = _get_court_lines() | |
| _cache['shot_positions'] = _shots_to_court_coords(shots) | |
| return _cache | |
| def _get_player_profiles(team, season): | |
| try: | |
| from cbb_stats import fetch_player_profiles | |
| result = fetch_player_profiles(team, season) | |
| return result.get('players', []) | |
| except Exception: | |
| return [] | |
| def _get_logo(team): | |
| try: | |
| from fetch import get_team_logo_url | |
| return get_team_logo_url(team) | |
| except Exception: | |
| return None | |
| def _get_colors(team): | |
| try: | |
| from fetch import get_team_colors | |
| return get_team_colors(team) | |
| except Exception: | |
| return {'primary': None, 'secondary': None} | |
| DEFAULT_TEAM = 'Illinois' | |
| DEFAULT_SEASON = 2025 | |
| def get_all_data(): | |
| """Return cached data. Uses local CSV in dev, fetches default team in prod.""" | |
| if _cache: | |
| return _cache | |
| if os.path.exists(DATA_PATH): | |
| return _populate_cache(load_df()) | |
| from fetch import fetch_and_flatten | |
| df = fetch_and_flatten(DEFAULT_TEAM, DEFAULT_SEASON) | |
| return _populate_cache(df) | |
| def _snapshot(): | |
| return {k: v.copy() if isinstance(v, pd.DataFrame) else v | |
| for k, v in _cache.items()} | |
| def _restore(snap): | |
| _cache.clear() | |
| for k, v in snap.items(): | |
| _cache[k] = v.copy() if isinstance(v, pd.DataFrame) else v | |
| def load_team(team: str, season: int): | |
| """Fetch from API, compute analytics, replace cache. Returns cache.""" | |
| key = (team.lower(), season) | |
| if key in _analytics_cache: | |
| _restore(_analytics_cache[key]) | |
| return _cache | |
| from fetch import fetch_and_flatten | |
| df = fetch_and_flatten(team, season) | |
| _populate_cache(df) | |
| _analytics_cache[key] = _snapshot() | |
| return _cache | |