{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "0",
   "metadata": {},
   "source": [
    "# WNBA\n",
    "\n",
    "This page is regenerated every week by sdvplot's docs workflow. It builds the standings with offensive, defensive and net ratings, plots offense against defense and lists\n",
    "the scoring leaders with their headshots, for the latest WNBA season with games: the season to date from May to\n",
    "September, the final regular season once it is over. Data: wehoop's ESPN box scores, read from release files through\n",
    "[sportsdataverse-py](https://py.sportsdataverse.org/) (no stats.wnba.com calls)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1",
   "metadata": {},
   "source": [
    "The WNBA season tips off in May, so until then the calendar points at last season. For a season that is not published yet `load_wnba_team_boxscore` warns and returns an empty frame rather\n",
    "than raising, so the helper below turns \"no regular-season games\" into a `NoDataError` and the page steps back one\n",
    "season."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2",
   "metadata": {},
   "outputs": [],
   "source": [
    "import datetime as dt\n",
    "import warnings\n",
    "\n",
    "import polars as pl\n",
    "import sportsdataverse.wnba as wnba\n",
    "from IPython.display import Markdown, display\n",
    "from sportsdataverse.errors import NoDataError\n",
    "\n",
    "import sdvplot\n",
    "\n",
    "today = dt.date.today()\n",
    "current = today.year if today.month >= 5 else today.year - 1\n",
    "SOURCE = \"Data: wehoop (ESPN) via sportsdataverse-py\"\n",
    "\n",
    "\n",
    "def label(season):\n",
    "    return str(season)\n",
    "\n",
    "\n",
    "def team_games(season):\n",
    "    with warnings.catch_warnings():\n",
    "        warnings.simplefilter(\"ignore\")  # \"no data for season(s)\": handled just below\n",
    "        box = wnba.load_wnba_team_boxscore(seasons=[season])\n",
    "    if box.is_empty() or box.filter(pl.col(\"season_type\") == 2).is_empty():\n",
    "        raise NoDataError(f\"no {label(season)} regular-season games yet\")\n",
    "    return box\n",
    "\n",
    "\n",
    "try:\n",
    "    season, box = current, team_games(current)\n",
    "except NoDataError as err:\n",
    "    print(f\"{err}; showing {label(current - 1)} instead\")\n",
    "    season, box = current - 1, team_games(current - 1)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3",
   "metadata": {},
   "source": [
    "The status line is written when the page runs: the season to date, a finished regular season with the playoffs under\n",
    "way, or the offseason."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4",
   "metadata": {},
   "outputs": [],
   "source": [
    "last_game = box[\"game_date\"].max()\n",
    "if season < current:\n",
    "    status = f\"**Offseason:** the final {label(season)} regular season; the {label(current)} season has no games yet.\"\n",
    "    through = \"final regular season\"\n",
    "elif box.filter(pl.col(\"season_type\") == 3).is_empty():\n",
    "    status = f\"**Season to date:** the {label(season)} season through {last_game:%B} {last_game.day}.\"\n",
    "    through = f\"through {last_game:%b} {last_game.day}\"\n",
    "elif (today - last_game).days <= 10:\n",
    "    status = f\"**Playoffs:** the final {label(season)} regular season; the playoffs are under way.\"\n",
    "    through = \"final regular season\"\n",
    "else:\n",
    "    status = f\"**Offseason:** the final {label(season)} regular season.\"\n",
    "    through = \"final regular season\"\n",
    "subtitle = through[:1].upper() + through[1:]\n",
    "display(Markdown(status))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5",
   "metadata": {},
   "source": [
    "ESPN files the All-Star Game and the in-season cup final as regular-season games, though neither counts in the\n",
    "standings. The schedule marks them in `type_abbreviation` (`ALLSTAR`, `CC`), so keep the standard games (`STD`) only.\n",
    "`resolve` then maps the ESPN team ids to sdvplot's, for the team table's names and conferences."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6",
   "metadata": {},
   "outputs": [],
   "source": [
    "standard = wnba.load_wnba_schedule(seasons=[season]).filter(\n",
    "    (pl.col(\"season_type\") == 2) & (pl.col(\"type_abbreviation\") == \"STD\")\n",
    ")\n",
    "assert box.schema[\"game_id\"] == standard.schema[\"game_id\"]\n",
    "regular = box.filter(pl.col(\"season_type\") == 2).join(standard.select(\"game_id\"), on=\"game_id\", how=\"semi\")\n",
    "regular = regular.with_columns(\n",
    "    team=pl.Series(sdvplot.resolve(regular[\"team_id\"].cast(pl.String).to_list(), \"wnba\"), dtype=pl.String)\n",
    ")\n",
    "possessions = (  # the box-score estimate, averaged with the opponent's\n",
    "    pl.col(\"field_goals_attempted\")\n",
    "    - pl.col(\"offensive_rebounds\")\n",
    "    + pl.col(\"total_turnovers\")\n",
    "    + 0.44 * pl.col(\"free_throws_attempted\")\n",
    ")\n",
    "games = regular.with_columns(poss=possessions).with_columns(poss=pl.col(\"poss\").mean().over(\"game_id\"))\n",
    "teams = sdvplot.teams(\"wnba\").select(team=\"team_id\", abbr=\"abbr\", name=\"short_name\", conference=\"conference\")\n",
    "ratings = (\n",
    "    games.sort(\"game_date\")\n",
    "    .group_by(\"team\", maintain_order=True)\n",
    "    .agg(\n",
    "        w=pl.col(\"team_winner\").sum(),\n",
    "        l=(~pl.col(\"team_winner\")).sum(),\n",
    "        l10=pl.col(\"team_winner\").tail(10).sum(),\n",
    "        ortg=100 * pl.col(\"team_score\").sum() / pl.col(\"poss\").sum(),\n",
    "        drtg=100 * pl.col(\"opponent_team_score\").sum() / pl.col(\"poss\").sum(),\n",
    "    )\n",
    "    .with_columns(pct=pl.col(\"w\") / (pl.col(\"w\") + pl.col(\"l\")), net=pl.col(\"ortg\") - pl.col(\"drtg\"))\n",
    "    .join(teams, on=\"team\")\n",
    "    .sort([\"pct\", \"net\", \"team\"], descending=[True, True, False])  # a tiebreaker keeps re-renders stable\n",
    ")\n",
    "ratings.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7",
   "metadata": {},
   "source": [
    "## 1. Standings with net rating\n",
    "\n",
    "Each conference ordered by winning percentage, with every team's points scored and allowed per 100 possessions."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8",
   "metadata": {},
   "outputs": [],
   "source": [
    "from great_tables import GT\n",
    "\n",
    "from sdvplot.great_tables import gt_save_crop, gt_sdv_logos, gt_theme_athletic\n",
    "\n",
    "table = ratings.with_columns(\n",
    "    record=pl.format(\"{}-{}\", \"w\", \"l\"),\n",
    "    last10=pl.format(\"{}-{}\", \"l10\", pl.min_horizontal(10, pl.col(\"w\") + pl.col(\"l\")) - pl.col(\"l10\")),\n",
    "    seed=pl.col(\"pct\").rank(\"ordinal\", descending=True).over(\"conference\"),\n",
    ").sort(\"conference\", \"seed\")\n",
    "table = table.select(\"conference\", \"seed\", \"abbr\", \"name\", \"record\", \"pct\", \"last10\", \"ortg\", \"drtg\", \"net\")\n",
    "gt = (\n",
    "    GT(table, groupname_col=\"conference\", id=\"wnba-standings\")  # fixed id: no random one each run\n",
    "    .tab_header(f\"WNBA standings and ratings, {label(season)}\", subtitle)\n",
    "    .fmt_number(\"pct\", decimals=3)\n",
    "    .cols_align(\"left\", \"name\")\n",
    "    .fmt_number([\"ortg\", \"drtg\"], decimals=1)\n",
    "    .fmt_number(\"net\", decimals=1, force_sign=True)\n",
    "    .data_color(\"net\", palette=[\"#c84630\", \"#f7f7f7\", \"#2e8b57\"], domain=[-15, 15])\n",
    "    .tab_spanner(\"Per 100 possessions\", [\"ortg\", \"drtg\", \"net\"])\n",
    "    .cols_label(\n",
    "        seed=\"\", abbr=\"\", name=\"Team\", record=\"W-L\", pct=\"Pct\", last10=\"Last 10\", ortg=\"Off\", drtg=\"Def\", net=\"Net\"\n",
    "    )\n",
    "    .tab_source_note(SOURCE + \". Possessions estimated from the box score; ties ordered by net rating.\")\n",
    ")\n",
    "gt = gt_theme_athletic(gt_sdv_logos(gt, \"abbr\", league=\"wnba\", height=28))\n",
    "gt"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9",
   "metadata": {},
   "source": [
    "`gt_save_crop` renders the same table to a trimmed PNG, ready to post."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "10",
   "metadata": {
    "sdvplot_gallery": {
     "alt": "WNBA standings table by conference with team logos, records and offensive, defensive and net ratings.",
     "title": "WNBA standings with net rating"
    },
    "tags": [
     "gallery"
    ]
   },
   "outputs": [],
   "source": [
    "gt_save_crop(gt, width=900)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "11",
   "metadata": {},
   "source": [
    "## 2. Offense against defense\n",
    "\n",
    "plotnine with `geom_sdv_logos`: offensive rating against defensive rating, the defense axis reversed so the better\n",
    "defenses sit higher, and `geom_mean_lines` at the league averages."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "12",
   "metadata": {
    "sdvplot_gallery": {
     "alt": "WNBA team logos placed by offensive and defensive rating per 100 possessions this season.",
     "title": "WNBA offense vs defense"
    },
    "tags": [
     "gallery"
    ]
   },
   "outputs": [],
   "source": [
    "from plotnine import aes, element_text, ggplot, labs, scale_x_continuous, scale_y_reverse, theme, theme_minimal\n",
    "\n",
    "from sdvplot.plotnine import geom_mean_lines, geom_sdv_logos\n",
    "\n",
    "(\n",
    "    ggplot(ratings.to_pandas(), aes(\"ortg\", \"drtg\", x0=\"ortg\", y0=\"drtg\", team=\"team\"))\n",
    "    + geom_mean_lines(color=\"grey\")\n",
    "    + geom_sdv_logos(league=\"wnba\", season=season, height=0.09)\n",
    "    + scale_x_continuous(expand=(0.06, 0))  # logos do not widen the limits: leave room for the outermost ones\n",
    "    + scale_y_reverse(expand=(0.08, 0))\n",
    "    + labs(\n",
    "        x=\"Offensive rating (points per 100 possessions)\",\n",
    "        y=\"Defensive rating (reversed)\",\n",
    "        title=f\"WNBA offense vs defense, {label(season)} {through}\",\n",
    "        caption=SOURCE,\n",
    "    )\n",
    "    + theme_minimal()\n",
    "    + theme(figure_size=(8, 6), plot_title=element_text(weight=\"bold\"))\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "13",
   "metadata": {},
   "source": [
    "## 3. Scoring leaders with headshots\n",
    "\n",
    "Points, rebounds and assists per game from the player box scores (standard games only), for players who appeared in at least half of the\n",
    "most games any team has played. `gt_sdv_headshots` turns the ESPN athlete ids into headshots and `gt_color_pills`\n",
    "draws the scoring column."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "14",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sdvplot.great_tables import gt_color_pills, gt_sdv_headshots, gt_theme_almanac\n",
    "\n",
    "players = (\n",
    "    wnba.load_wnba_player_boxscore(seasons=[season])\n",
    "    .filter((pl.col(\"season_type\") == 2) & ~pl.col(\"did_not_play\") & pl.col(\"minutes\").is_not_null())\n",
    "    .join(standard.select(\"game_id\"), on=\"game_id\", how=\"semi\")\n",
    ")  # no All-Star or cup final\n",
    "games_played = players.group_by(\"team_id\", maintain_order=True).agg(pl.col(\"game_id\").n_unique())[\"game_id\"].max()\n",
    "leaders = (\n",
    "    players.sort(\"game_date\")\n",
    "    .group_by(\"athlete_id\", maintain_order=True)\n",
    "    .agg(\n",
    "        name=pl.col(\"athlete_display_name\").last(),\n",
    "        team=pl.col(\"team_abbreviation\").last(),\n",
    "        gp=pl.len(),\n",
    "        ppg=pl.col(\"points\").mean(),\n",
    "        rpg=pl.col(\"rebounds\").mean(),\n",
    "        apg=pl.col(\"assists\").mean(),\n",
    "    )\n",
    "    .filter(pl.col(\"gp\") >= games_played / 2)\n",
    "    .sort([\"ppg\", \"athlete_id\"], descending=[True, False])\n",
    "    .head(10)\n",
    "    .with_row_index(\"rank\", offset=1)\n",
    "    .select(\"rank\", \"athlete_id\", \"name\", \"team\", \"gp\", \"ppg\", \"rpg\", \"apg\")\n",
    ")\n",
    "leaders_gt = (\n",
    "    GT(leaders, id=\"wnba-leaders\")\n",
    "    .tab_header(f\"WNBA scoring leaders, {label(season)}\", f\"{subtitle}; minimum {games_played / 2:.0f} games\")\n",
    "    .fmt_number([\"rpg\", \"apg\"], decimals=1)\n",
    "    .cols_label(rank=\"\", athlete_id=\"\", name=\"Player\", team=\"\", gp=\"GP\", ppg=\"PPG\", rpg=\"RPG\", apg=\"APG\")\n",
    "    .tab_source_note(SOURCE)\n",
    ")\n",
    "leaders_gt = gt_color_pills(\n",
    "    leaders_gt, \"ppg\", palette=[\"#f3e4c8\", \"#c8102e\"], digits=1, domain=[leaders[\"ppg\"].min(), leaders[\"ppg\"].max()]\n",
    ")\n",
    "leaders_gt = gt_sdv_logos(\n",
    "    gt_sdv_headshots(leaders_gt, \"athlete_id\", league=\"wnba\", height=40), \"team\", league=\"wnba\", height=24\n",
    ")\n",
    "leaders_gt = gt_theme_almanac(leaders_gt)\n",
    "leaders_gt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "15",
   "metadata": {
    "sdvplot_gallery": {
     "alt": "Table of the WNBA's top ten scorers with headshots, team logos and points, rebounds and assists per game.",
     "title": "WNBA scoring leaders with headshots"
    },
    "tags": [
     "gallery"
    ]
   },
   "outputs": [],
   "source": [
    "gt_save_crop(leaders_gt, width=800)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  },
  "sdvplot": {
   "description": "The latest WNBA season, rebuilt every week: standings with net rating, offense vs defense with logos and the scoring leaders with headshots.",
   "label": "WNBA",
   "position": 4
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
