{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "0",
   "metadata": {},
   "source": [
    "# Perspective\n",
    "\n",
    "[Perspective](https://perspective-dev.github.io/) is an interactive data grid and chart viewer: a WebAssembly\n",
    "engine that pivots, filters and aggregates in the browser, and a `<perspective-viewer>` element that shows the result\n",
    "as a grid or a chart, which the reader can re-pivot. `sdvplot.perspective` builds two things for it:\n",
    "\n",
    "- `perspective_sdv_config()`: a viewer config in team colors. On the Datagrid it fills each team's cells; on a chart it\n",
    "  gives each team its color, for a view split by team or a scatter colored by team. A registry table theme adds its\n",
    "  fonts and sign colors.\n",
    "- `perspective_logo_column()`: each team's logo URL, as a column beside the team, which the Datagrid shows as a link\n",
    "  (Perspective 5.5's grid draws no images).\n",
    "\n",
    "The config is plain data: in Jupyter pass it to the widget as `PerspectiveWidget(frame, **config)`, and in a web page\n",
    "to the viewer's `restore()`. The module needs `pip install \"sdvplot[perspective]\"` and Python 3.11+ (Perspective ships\n",
    "wheels for 3.11 and later only).\n",
    "\n",
    "Every number here comes from the 2024 NFL regular season's play-by-play (nflverse, through sportsdataverse-py), never\n",
    "typed in. A docs page has no Jupyter kernel for the widget to talk to, so each recipe is drawn by the small `show()`\n",
    "helper below: a standalone page that loads Perspective 5.5.1 from jsDelivr and restores the config, as the widget\n",
    "does in a notebook."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1",
   "metadata": {},
   "outputs": [],
   "source": [
    "import html\n",
    "import json\n",
    "\n",
    "import polars as pl\n",
    "import sportsdataverse.nfl as nfl\n",
    "from IPython.display import HTML\n",
    "\n",
    "import sdvplot\n",
    "from sdvplot.perspective import perspective_logo_column, perspective_sdv_config\n",
    "\n",
    "SEASON = 2024\n",
    "PSP = \"https://cdn.jsdelivr.net/npm/@perspective-dev\"\n",
    "PSP_VERSION = \"5.5.1\"  # the floor of the [perspective] extra, which the tests run against\n",
    "\n",
    "\n",
    "def show(frame, config, *, height=440, theme=None):\n",
    "    \"\"\"``frame`` in a <perspective-viewer> restored to ``config``, as a standalone page (Perspective from jsDelivr).\n",
    "    In Jupyter, ``PerspectiveWidget(frame.to_pandas(), **config)`` shows the same live, backed by the kernel.\"\"\"\n",
    "    fonts = \"\"\n",
    "    if theme is not None:  # a registry theme names Google Fonts faces: the page loads them\n",
    "        f = sdvplot.table_theme_spec(theme).fonts\n",
    "        for family in sorted({x for x in (f.get(\"body\"), f.get(\"numeric\")) if x}):\n",
    "            url = f\"https://fonts.googleapis.com/css2?family={family.replace(' ', '+')}&display=swap\"\n",
    "            fonts += f'<link rel=\"stylesheet\" href=\"{html.escape(url)}\">\\n'\n",
    "    data = json.dumps(frame.to_dict(as_series=False)).replace(\"</\", \"<\\\\/\")\n",
    "    page = f\"\"\"<!doctype html>\n",
    "<html lang=\"en\"><head><meta charset=\"utf-8\">\n",
    "<link rel=\"stylesheet\" crossorigin=\"anonymous\" href=\"{PSP}/viewer@{PSP_VERSION}/dist/css/themes.css\">\n",
    "{fonts}<style>body{{margin:0}} perspective-viewer{{display:block;height:{height}px}}</style>\n",
    "</head><body><perspective-viewer></perspective-viewer>\n",
    "<script type=\"module\">\n",
    "import \"{PSP}/viewer@{PSP_VERSION}/dist/cdn/perspective-viewer.js\";\n",
    "import \"{PSP}/viewer-datagrid@{PSP_VERSION}/dist/cdn/perspective-viewer-datagrid.js\";\n",
    "import \"{PSP}/viewer-charts@{PSP_VERSION}/dist/cdn/perspective-viewer-charts.js\";\n",
    "import perspective from \"{PSP}/client@{PSP_VERSION}/dist/cdn/perspective.js\";\n",
    "const worker = await perspective.worker();\n",
    "await worker.table({data}, {{name: \"sdv\"}});\n",
    "const viewer = document.querySelector(\"perspective-viewer\");\n",
    "await viewer.load(worker);\n",
    "await viewer.restore({{table: \"sdv\", settings: false, ...{json.dumps(config)}}});\n",
    "</script></body></html>\"\"\"\n",
    "    return HTML(page)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2",
   "metadata": {},
   "source": [
    "Each pass or run with an EPA, in the regular season, is one row. The team tables below sum them by offense\n",
    "(`posteam`) and by defense (`defteam`); nflverse's team codes (`LA` for the Rams, `WAS`) resolve as they are."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3",
   "metadata": {},
   "outputs": [],
   "source": [
    "pbp = nfl.load_nfl_pbp([SEASON])\n",
    "plays = pbp.filter(\n",
    "    pl.col(\"season_type\") == \"REG\",\n",
    "    pl.col(\"play_type\").is_in([\"pass\", \"run\"]),\n",
    "    pl.col(\"epa\").is_not_null(),\n",
    "    pl.col(\"posteam\").is_not_null(),\n",
    ").select(\"week\", \"posteam\", \"defteam\", \"play_type\", \"epa\", \"success\")\n",
    "offense = plays.group_by(\"posteam\").agg(\n",
    "    plays=pl.len(), epa_per_play=pl.col(\"epa\").mean().round(3), success_rate=pl.col(\"success\").mean().round(3)\n",
    ")\n",
    "defense = plays.group_by(\"defteam\").agg(def_epa_per_play=pl.col(\"epa\").mean().round(3))\n",
    "assert offense.schema[\"posteam\"] == defense.schema[\"defteam\"]  # one dtype for the team key on both sides\n",
    "teams = offense.join(defense, left_on=\"posteam\", right_on=\"defteam\").sort(\"epa_per_play\", descending=True)\n",
    "print(plays.height, \"plays;\", teams.height, \"teams\")\n",
    "teams.head(5)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4",
   "metadata": {},
   "source": [
    "## 1. A leaderboard with team fills and logo links\n",
    "\n",
    "On the Datagrid, `perspective_sdv_config` fills the team column's cells with each team's color, and Perspective picks\n",
    "a readable text color on each fill. The grid hands its palette out in the order it first draws each team, so the\n",
    "palette is in the frame's order: the config sets no `sort`, and the frame is already sorted, one row per team.\n",
    "`perspective_logo_column` puts each team's logo URL after the team, and `logo_col` shows it as a link; here the\n",
    "`columns` list moves it to the end, where the long URLs do not push the numbers off the page. Each number column also\n",
    "gets a format: a rate or EPA to 3 decimals, a percentage to 1, an integer plain (`formats=` overrides one)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5",
   "metadata": {},
   "outputs": [],
   "source": [
    "board = perspective_logo_column(teams, \"posteam\", league=\"nfl\", season=SEASON)\n",
    "config = perspective_sdv_config(board, team_col=\"posteam\", league=\"nfl\", logo_col=\"posteam_logo\")\n",
    "config[\"columns\"] = [\"posteam\", \"plays\", \"epa_per_play\", \"success_rate\", \"def_epa_per_play\", \"posteam_logo\"]\n",
    "print(config[\"columns_config\"][\"posteam\"][\"bg_color\"][:80], \"...\")\n",
    "show(board, config)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6",
   "metadata": {},
   "source": [
    "## 2. The same table in a registry theme\n",
    "\n",
    "`theme=` takes any of the 122 registry table themes (`sdvplot.sdv_table_themes()`). On the Datagrid it sets the font\n",
    "and size (`plugin_config`) and gives each number column the theme's negative and positive colors, so an offense or\n",
    "defense below zero EPA per play reads in the theme's red. The page has to load the font: `show()` adds the Google\n",
    "Fonts link. Perspective's own \"Pro Light\" theme still draws the grid lines and header."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7",
   "metadata": {},
   "outputs": [],
   "source": [
    "config = perspective_sdv_config(board.drop(\"posteam_logo\"), team_col=\"posteam\", league=\"nfl\", theme=\"rbsdm\")\n",
    "print(config[\"plugin_config\"], config[\"columns_config\"][\"epa_per_play\"])\n",
    "show(board.drop(\"posteam_logo\"), config, theme=\"rbsdm\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8",
   "metadata": {},
   "source": [
    "## 3. Success rate as bars in team colors\n",
    "\n",
    "On a chart, the view is yours to set, and the config colors it. Split by the team (`split_by`) and each team's series\n",
    "takes its color from the number column's `palette`, which lists the teams in ascending order of team code: Perspective\n",
    "sorts the values it splits by, whatever the frame's order. Grouping by the team as well (`group_by`) puts one bar per\n",
    "team, and the sort orders the bars. A team has one color in every recipe here: the palette is taken over the teams in\n",
    "sorted order, then listed in whichever order Perspective needs."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9",
   "metadata": {},
   "outputs": [],
   "source": [
    "config = perspective_sdv_config(teams, team_col=\"posteam\", league=\"nfl\", plugin=\"X Bar\")\n",
    "config |= {\n",
    "    \"group_by\": [\"posteam\"],\n",
    "    \"split_by\": [\"posteam\"],\n",
    "    \"columns\": [\"success_rate\"],\n",
    "    \"sort\": [[\"success_rate\", \"desc\"]],\n",
    "}\n",
    "show(teams, config, height=620)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "10",
   "metadata": {},
   "source": [
    "## 4. A division race, week by week\n",
    "\n",
    "Cumulative EPA by week for the AFC North, summed in polars, then drawn as one line per team. Each team keeps its\n",
    "color: the four are made readable on the white background and at least ΔE 20 apart, so Baltimore's purple and\n",
    "Pittsburgh's black stay distinct from Cleveland's brown and Cincinnati's orange."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "11",
   "metadata": {},
   "outputs": [],
   "source": [
    "north = (\n",
    "    plays.filter(pl.col(\"posteam\").is_in([\"BAL\", \"PIT\", \"CIN\", \"CLE\"]))\n",
    "    .group_by(\"posteam\", \"week\")\n",
    "    .agg(epa=pl.col(\"epa\").sum())\n",
    "    .sort(\"week\")\n",
    "    .with_columns(cumulative_epa=pl.col(\"epa\").cum_sum().over(\"posteam\").round(1))\n",
    "    .select(\"week\", \"posteam\", \"cumulative_epa\")\n",
    ")\n",
    "config = perspective_sdv_config(north, team_col=\"posteam\", league=\"nfl\", plugin=\"Y Line\")\n",
    "config |= {\"group_by\": [\"week\"], \"split_by\": [\"posteam\"], \"columns\": [\"cumulative_epa\"]}\n",
    "show(north, config)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "12",
   "metadata": {},
   "source": [
    "## 5. Offense against defense, in the dark\n",
    "\n",
    "`mode=\"dark\"` switches to Perspective's \"Pro Dark\" theme and builds the palette against its background (#242526), so\n",
    "every team's color is at least 3:1 against it: a team whose colors are too dark there is lightened. One point per\n",
    "team, offense EPA per play across and defense up (lower is better on defense). A scatter takes its colors from the\n",
    "column in its third slot, Color: the team column. Perspective colors those categories in the order it meets them, the\n",
    "rows' order, so the config lists the team column's `palette` in the frame's order. (Split by team, a scatter draws one\n",
    "small panel per team instead.)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "13",
   "metadata": {},
   "outputs": [],
   "source": [
    "config = perspective_sdv_config(teams, team_col=\"posteam\", league=\"nfl\", plugin=\"X/Y Scatter\", mode=\"dark\")\n",
    "config |= {\"columns\": [\"epa_per_play\", \"def_epa_per_play\", \"posteam\"]}\n",
    "show(teams.select(\"posteam\", \"epa_per_play\", \"def_epa_per_play\"), config)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "14",
   "metadata": {},
   "source": [
    "## 6. A season of play-by-play, pivoted by Perspective\n",
    "\n",
    "Here the page gets the plays themselves, about 33,000 rows (three columns, EPA rounded), and Perspective does the\n",
    "pivot in the browser: passing plays only, grouped and split by offense, with the mean EPA per team. The reader can\n",
    "change the filter to `run`, or the aggregate, and the bars keep their team colors, because the palette follows the\n",
    "split values, not the numbers."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "15",
   "metadata": {},
   "outputs": [],
   "source": [
    "season = plays.select(\"posteam\", \"play_type\", pl.col(\"epa\").round(3))\n",
    "config = perspective_sdv_config(season, team_col=\"posteam\", league=\"nfl\", plugin=\"Y Bar\")\n",
    "config |= {\n",
    "    \"group_by\": [\"posteam\"],\n",
    "    \"split_by\": [\"posteam\"],\n",
    "    \"columns\": [\"epa\"],\n",
    "    \"aggregates\": {\"epa\": \"avg\"},\n",
    "    \"filter\": [[\"play_type\", \"==\", \"pass\"]],\n",
    "    \"sort\": [[\"epa\", \"desc\"]],\n",
    "}\n",
    "show(season, config)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "sdvplot": {
   "description": "Six Perspective recipes: an NFL leaderboard with team fills and logo links, the same table in a registry theme, bars and a division race in team colors, offense against defense in the dark, and a season of play-by-play pivoted in the browser.",
   "label": "Perspective",
   "position": 17
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
