{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "0",
   "metadata": {},
   "source": [
    "# pydeck\n",
    "\n",
    "[pydeck](https://deckgl.readthedocs.io/) draws [deck.gl](https://deck.gl/) layers from Python: WebGL maps and\n",
    "charts that pan, zoom and tilt in the browser. `sdvplot.pydeck` builds three kinds of layer: team logos at points\n",
    "(`logo_icon_layer`), arcs in team colors (`pass_arc_layer`), and a sportypy rink, pitch, court or field in its own\n",
    "coordinates (`surface_layer`). Each returns `pydeck.Layer`'s keyword arguments as a plain dict, and `deck()` puts\n",
    "them in a `pydeck.Deck` with its view fitted. The module needs pydeck: `pip install \"sdvplot[pydeck]\"`.\n",
    "sdvplot-js builds the same layers for deck.gl in JavaScript, and the two are tested against one shared fixture.\n",
    "\n",
    "Every point here comes from a data source, never typed in: game 7 of the 2024 Stanley Cup Final from NHL api-web\n",
    "through sportsdataverse-py, the 2018 World Cup final from StatsBomb's open data, and MLB's ballparks from the MLB\n",
    "Stats API through sportsdataverse-py. Drag to pan, scroll to zoom, and hover a mark for its team."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1",
   "metadata": {},
   "outputs": [],
   "source": [
    "import polars as pl\n",
    "import pydeck as pdk\n",
    "import requests\n",
    "import sportsdataverse.mlb as mlb\n",
    "import sportsdataverse.nhl as nhl\n",
    "\n",
    "import sdvplot\n",
    "import sdvplot.pydeck as sdeck\n",
    "\n",
    "GAME = 2023030417  # game 7 of the 2024 Stanley Cup Final, Edmonton at Florida\n",
    "WORLD_CUP_FINAL = 8658  # StatsBomb's match id: France 4-2 Croatia, 2018-07-15\n",
    "ESPN_TEAM = {\"France\": \"478\", \"Croatia\": \"477\"}  # ESPN's soccer ids for the men's teams (2755 and 18889: the women's)\n",
    "MLB_SEASON = 2026"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2",
   "metadata": {},
   "source": [
    "NHL api-web's play-by-play gives each shot in feet from centre ice, the frame sportypy draws its rink in, so\n",
    "the shots need no conversion. Its team ids are the NHL's own; the game's `homeTeam` and `awayTeam` name them.\n",
    "StatsBomb's events are in its 120 x 80 frame, which `sdvplot.pitch_coords` converts to sportypy's 105 x 68 m pitch\n",
    "(origin at the centre spot), flipping Croatia so the two teams attack opposite ends. StatsBomb open data is free for\n",
    "non-commercial use; credit it as below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3",
   "metadata": {},
   "outputs": [],
   "source": [
    "raw = nhl.nhl_web_pbp(GAME, return_parsed=False)\n",
    "nhl_team = {t[\"id\"]: t[\"abbrev\"] for t in (raw[\"homeTeam\"], raw[\"awayTeam\"])}\n",
    "shots = (\n",
    "    nhl.parse_nhl_web_pbp(raw)\n",
    "    .filter(\n",
    "        pl.col(\"period_descriptor_number\") == 1,\n",
    "        pl.col(\"type_desc_key\").is_in([\"goal\", \"shot-on-goal\", \"missed-shot\"]),\n",
    "    )\n",
    "    .select(\n",
    "        team=pl.col(\"details_event_owner_team_id\").cast(pl.Int64).replace_strict(nhl_team),\n",
    "        type=pl.col(\"type_desc_key\"),\n",
    "        time=pl.col(\"time_in_period\"),\n",
    "        x=pl.col(\"details_x_coord\"),\n",
    "        y=pl.col(\"details_y_coord\"),\n",
    "    )\n",
    "    # the goal each shot was aimed at: the goal line is 89 ft from centre, at the end the shot came from\n",
    "    .with_columns(net_x=pl.col(\"x\").sign() * 89, net_y=pl.lit(0.0))\n",
    ")\n",
    "\n",
    "events = requests.get(\n",
    "    f\"https://raw.githubusercontent.com/statsbomb/open-data/master/data/events/{WORLD_CUP_FINAL}.json\", timeout=60\n",
    ").json()\n",
    "completed = [e for e in events if e[\"type\"][\"name\"] == \"Pass\" and \"outcome\" not in e[\"pass\"]]\n",
    "passes = pl.DataFrame(\n",
    "    {\n",
    "        \"team\": [ESPN_TEAM[e[\"team\"][\"name\"]] for e in completed],\n",
    "        \"half\": [e[\"period\"] for e in completed],\n",
    "        \"x\": [e[\"location\"][0] for e in completed],\n",
    "        \"y\": [e[\"location\"][1] for e in completed],\n",
    "        \"end_x\": [e[\"pass\"][\"end_location\"][0] for e in completed],\n",
    "        \"end_y\": [e[\"pass\"][\"end_location\"][1] for e in completed],\n",
    "    }\n",
    ").with_columns(croatia=pl.col(\"team\") == ESPN_TEAM[\"Croatia\"])\n",
    "start = sdvplot.pitch_coords(passes, provider=\"statsbomb\", flip=\"croatia\")\n",
    "end = sdvplot.pitch_coords(passes, provider=\"statsbomb\", x=\"end_x\", y=\"end_y\", flip=\"croatia\")\n",
    "passes = start.with_columns(to_x=end[\"pitch_x\"], to_y=end[\"pitch_y\"])\n",
    "\n",
    "teams = mlb.mlb_teams(season=MLB_SEASON, hydrate=\"venue(location)\")[\"teams\"]\n",
    "parks = pl.DataFrame(\n",
    "    [\n",
    "        {\n",
    "            \"team\": t[\"abbreviation\"],\n",
    "            \"park\": t[\"venue\"][\"name\"],\n",
    "            \"longitude\": t[\"venue\"][\"location\"][\"defaultCoordinates\"][\"longitude\"],\n",
    "            \"latitude\": t[\"venue\"][\"location\"][\"defaultCoordinates\"][\"latitude\"],\n",
    "        }\n",
    "        for t in teams\n",
    "    ]\n",
    ").sort(\"team\")\n",
    "shots.height, passes.height, parks.height"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4",
   "metadata": {},
   "source": [
    "## 1. Every shot of a Stanley Cup Final period, as logos on the rink\n",
    "\n",
    "`surface_layer(\"hockey\", \"nhl\")` is sportypy's NHL rink as a `PolygonLayer` in feet, the origin at centre ice, and\n",
    "`logo_icon_layer` puts each shot's team logo at its (x, y) in the same feet. `deck()` sees the surface, draws it top\n",
    "down (an OrthographicView, y up) fitted to the rink, and draws the logos in the rink's coordinates. `size` is the\n",
    "logo's height on screen in pixels. In the first period Edmonton shot at the right-hand goal and Florida at the left.\n",
    "pydeck writes every layer's data into the page, so `tolerance` (in feet here) thins sportypy's arcs further than\n",
    "the default: at 0.25 ft the rink is about 9,200 points instead of 14,400 (123,000 unthinned). Each line keeps its\n",
    "shape, because each loop caps the tolerance at its own width and keeps its corners."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5",
   "metadata": {},
   "outputs": [],
   "source": [
    "rink = sdeck.surface_layer(\"hockey\", \"nhl\", tolerance=0.25)\n",
    "logos = sdeck.logo_icon_layer(shots, x=\"x\", y=\"y\", team=\"team\", league=\"nhl\", size=26)\n",
    "sdeck.deck(rink, logos, height=420, tooltip={\"text\": \"{team}\"})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6",
   "metadata": {},
   "source": [
    "## 2. Each shot as an arc to the goal it was aimed at\n",
    "\n",
    "`pass_arc_layer` draws one arc per row from (`x`, `y`) to (`xend`, `yend`), in the team's colors: its primary color\n",
    "where the arc starts and its secondary where it ends, so each arc shows its direction (no `background` here,\n",
    "so the colors are the teams' own). deck.gl's arcs stand upright\n",
    "by default, which a top-down view sees as straight lines; `tilt=90` lays them flat on the ice, and `height=0.3`\n",
    "keeps each curve low (deck.gl's default height, 1, swings a long arc well past the boards)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7",
   "metadata": {},
   "outputs": [],
   "source": [
    "arcs = sdeck.pass_arc_layer(\n",
    "    shots, x=\"x\", y=\"y\", xend=\"net_x\", yend=\"net_y\", team=\"team\", league=\"nhl\", width=3, tilt=90, height=0.3\n",
    ")\n",
    "sdeck.deck(rink, arcs, height=420)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8",
   "metadata": {},
   "source": [
    "## 3. France's passes in the 2018 World Cup final, flat on the pitch\n",
    "\n",
    "The pitch is `surface_layer(\"soccer\", \"fifa\")` resized to the 105 x 68 m frame `pitch_coords` returns, through\n",
    "sportypy's own `pitch_updates`. France's completed first-half passes, each from where it was played to where it was\n",
    "received, attacking left to right. Without `background` the colors are the team's own: France's navy and its\n",
    "secondary color."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9",
   "metadata": {},
   "outputs": [],
   "source": [
    "pitch = sdeck.surface_layer(\"soccer\", \"fifa\", pitch_updates={\"pitch_length\": 105, \"pitch_width\": 68})\n",
    "france = passes.filter(pl.col(\"team\") == ESPN_TEAM[\"France\"], pl.col(\"half\") == 1)\n",
    "arcs = sdeck.pass_arc_layer(\n",
    "    france, x=\"pitch_x\", y=\"pitch_y\", xend=\"to_x\", yend=\"to_y\", team=\"team\", league=\"soccer\",\n",
    "    id_system=\"team_id\", tilt=90, height=0.3, width=2,\n",
    ")  # fmt: skip\n",
    "print(f\"{france.height} passes\")\n",
    "sdeck.deck(pitch, arcs, height=440)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "10",
   "metadata": {},
   "source": [
    "## 4. Both finalists, readable on the grass\n",
    "\n",
    "The arcs are drawn on the pitch's green, so pass it as `background`: every color then keeps 3:1 contrast against\n",
    "the grass (WCAG's minimum for graphics), a team color that would not read gives way to the team's other color or is\n",
    "lightened until it does, and the two teams' colors stay distinct (a CIE76 ΔE of 20 or more). This is the same team\n",
    "palette sdvplot-js uses for dark mode. Croatia's passes are flipped to attack right to left.\n",
    "\n",
    "One caveat: a color that does not read gives way to the team's other color, so when only one of a team's two colors\n",
    "reads on the background, both ends take it. France's navy does not read on this dark grass, so its passes are mint at\n",
    "both ends (the printed colors show it) and their direction is lost, while Croatia's two colors both read (lightened)\n",
    "and its arcs keep theirs. On a grass where both of a team's colors read, the ends differ: check `sourceColor` against\n",
    "`targetColor`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "11",
   "metadata": {},
   "outputs": [],
   "source": [
    "grass = \"#{:02x}{:02x}{:02x}\".format(*pitch[\"data\"][0][\"fillColor\"][:3])  # the pitch's own fill\n",
    "first_half = passes.filter(pl.col(\"half\") == 1)\n",
    "arcs = sdeck.pass_arc_layer(\n",
    "    first_half, x=\"pitch_x\", y=\"pitch_y\", xend=\"to_x\", yend=\"to_y\", team=\"team\", league=\"soccer\",\n",
    "    id_system=\"team_id\", tilt=90, height=0.3, background=grass,\n",
    ")  # fmt: skip\n",
    "print(grass, {d[\"team\"]: (d[\"sourceColor\"], d[\"targetColor\"]) for d in arcs[\"data\"]})\n",
    "sdeck.deck(pitch, arcs, height=440)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "12",
   "metadata": {},
   "source": [
    "## 5. Upright arcs in 3D\n",
    "\n",
    "Without `tilt`, deck.gl's arcs rise off the surface, higher for longer passes, and a tilted view shows them. `deck()`\n",
    "draws top down, so build the `pydeck.Deck` yourself with an OrbitView. The layers are `pydeck.Layer` keyword\n",
    "arguments: a constant string is quoted (`\"'cartesian'\"`), because pydeck reads an unquoted string as an expression.\n",
    "France's second-half passes:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "13",
   "metadata": {},
   "outputs": [],
   "source": [
    "second = passes.filter(pl.col(\"team\") == ESPN_TEAM[\"France\"], pl.col(\"half\") == 2)\n",
    "arcs = sdeck.pass_arc_layer(\n",
    "    second, x=\"pitch_x\", y=\"pitch_y\", xend=\"to_x\", yend=\"to_y\", team=\"team\", league=\"soccer\",\n",
    "    id_system=\"team_id\", background=grass,\n",
    ")  # fmt: skip\n",
    "pdk.Deck(\n",
    "    layers=[pdk.Layer(**pitch), pdk.Layer(**arcs, coordinate_system=\"'cartesian'\")],\n",
    "    views=[pdk.View(type=\"OrbitView\", controller=True)],\n",
    "    initial_view_state=pdk.ViewState(target=[0, 0, 0], rotation_x=40, rotation_orbit=-20, zoom=2.4),\n",
    "    map_provider=None,\n",
    "    height=440,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "14",
   "metadata": {},
   "source": [
    "## 6. Logos on a map\n",
    "\n",
    "Without a surface, `deck()` draws a map fitted to the layers' positions, so `x` is a longitude and `y` a latitude.\n",
    "Every MLB ballpark, from the MLB Stats API's venue coordinates; its abbreviations (`AZ`, `CWS`) resolve to the same\n",
    "teams as ESPN's."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "15",
   "metadata": {},
   "outputs": [],
   "source": [
    "logos = sdeck.logo_icon_layer(parks, x=\"longitude\", y=\"latitude\", team=\"team\", league=\"mlb\", size=34)\n",
    "sdeck.deck(logos, height=440, map_style=\"light\", tooltip={\"text\": \"{team}\"})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "16",
   "metadata": {},
   "source": [
    "## 7. A box lacrosse rink\n",
    "\n",
    "`surface_layer` draws all ten of sportypy's sports, lacrosse, softball and volleyball included. The NLL plays box\n",
    "lacrosse on a rink with boards, in feet with the origin at its centre, as the hockey rink above. With no other\n",
    "layer, `deck()` fits the view to the surface."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "17",
   "metadata": {},
   "outputs": [],
   "source": [
    "box = sdeck.surface_layer(\"lacrosse\", \"nll\")\n",
    "sdeck.deck(box, height=360)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "18",
   "metadata": {},
   "source": [
    "Data: NHL api-web; StatsBomb open data; the MLB Stats API."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "sdvplot": {
   "description": "Seven pydeck recipes: shots as logos on an NHL rink, shots as arcs to the goal, a team's passes flat on the pitch, both finalists readable on the grass, upright arcs in 3D, logos on a map, and a box lacrosse rink.",
   "label": "pydeck",
   "position": 16
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
