{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "0",
   "metadata": {},
   "source": [
    "# folium maps\n",
    "\n",
    "[Folium](https://python-visualization.github.io/folium/) writes Leaflet web maps from Python: tiles,\n",
    "markers, popups and layers, saved as one HTML page. sdvplot puts team logos, wordmarks and player\n",
    "headshots on a map as image markers at each (longitude, latitude), with the team's name as the tooltip,\n",
    "and gives you the team colors and image URLs for the rest of the map. Every location here comes from a\n",
    "data source, never typed in: MLB ballparks from the MLB Stats API, college football stadiums and players'\n",
    "hometowns from cfbfastR, both through sportsdataverse-py."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1",
   "metadata": {},
   "outputs": [],
   "source": [
    "import folium\n",
    "import polars as pl\n",
    "import sportsdataverse.cfb as cfb\n",
    "import sportsdataverse.mlb as mlb\n",
    "\n",
    "import sdvplot\n",
    "\n",
    "MLB_SEASON = 2026\n",
    "CFB_SEASON = 2025  # football names a season by the year it starts"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2",
   "metadata": {},
   "source": [
    "The MLB Stats API's teams endpoint, hydrated with `venue(location)`, carries each home park's coordinates.\n",
    "Its abbreviations (`AZ`, `CWS`) differ from ESPN's (`ARI`, `CHW`), so `sdvplot.resolve` maps both to one\n",
    "team id before the standings join. cfbfastR's team info has every stadium's coordinates, capacity and\n",
    "year built; its ESPN team ids are integers, cast once to the strings sdvplot uses. cfbfastR's rosters carry\n",
    "each player's hometown coordinates."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3",
   "metadata": {},
   "outputs": [],
   "source": [
    "teams = mlb.mlb_teams(season=MLB_SEASON, hydrate=\"venue(location)\")[\"teams\"]\n",
    "parks = pl.DataFrame(\n",
    "    [\n",
    "        {\n",
    "            \"abbr\": t[\"abbreviation\"],\n",
    "            \"team\": t[\"name\"],\n",
    "            \"division\": t[\"division\"][\"name\"],\n",
    "            \"park\": t[\"venue\"][\"name\"],\n",
    "            \"city\": t[\"venue\"][\"location\"][\"city\"],\n",
    "            \"elevation\": t[\"venue\"][\"location\"].get(\"elevation\"),\n",
    "            \"latitude\": t[\"venue\"][\"location\"][\"defaultCoordinates\"][\"latitude\"],\n",
    "            \"longitude\": t[\"venue\"][\"location\"][\"defaultCoordinates\"][\"longitude\"],\n",
    "        }\n",
    "        for t in teams\n",
    "    ]\n",
    ")\n",
    "parks = parks.with_columns(team_id=sdvplot.resolve(parks[\"abbr\"], \"mlb\"))\n",
    "standings = mlb.espn_mlb_standings(season=MLB_SEASON)\n",
    "standings = standings.with_columns(team_id=sdvplot.resolve(standings[\"team_abbreviation\"], \"mlb\")).select(\n",
    "    \"team_id\", \"wins\", \"losses\", \"point_differential\"\n",
    ")\n",
    "assert parks.schema[\"team_id\"] == standings.schema[\"team_id\"]\n",
    "parks = parks.join(standings, on=\"team_id\").sort(\"abbr\")\n",
    "\n",
    "stadiums = (\n",
    "    cfb.load_cfb_team_info([CFB_SEASON])\n",
    "    .filter(pl.col(\"classification\") == \"fbs\")\n",
    "    .with_columns(pl.col(\"team_id\").cast(pl.Int64).cast(pl.Utf8))\n",
    ")\n",
    "rosters = cfb.load_cfb_rosters_cfbd([CFB_SEASON])\n",
    "parks.height, stadiums.height, rosters.height"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4",
   "metadata": {},
   "source": [
    "## 1. Every MLB ballpark\n",
    "\n",
    "`add_logos` takes longitudes as x and latitudes as y. `height` is a fraction of the map's pixel height, so\n",
    "give the map a height in pixels; the logos keep their size as you zoom. Each logo's tooltip is the team's\n",
    "name."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5",
   "metadata": {},
   "outputs": [],
   "source": [
    "m = folium.Map(location=[38.5, -96], zoom_start=4, height=520, tiles=\"Esri.WorldGrayCanvas\")\n",
    "sdvplot.add_logos(m, parks[\"longitude\"], parks[\"latitude\"], parks[\"abbr\"], league=\"mlb\", height=0.07)\n",
    "m"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6",
   "metadata": {},
   "source": [
    "## 2. Team-colored circles sized by wins, with a popup\n",
    "\n",
    "Draw your own Folium layers under the logos. `sdvplot.team_colors` gives each team's primary color for a\n",
    "`CircleMarker`, sized here by regular-season wins, and `sdvplot.logo_url` puts the logo in the popup next to\n",
    "the park, record and run differential. The circles are larger than the logos, so click a ring to open its\n",
    "popup."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7",
   "metadata": {},
   "outputs": [],
   "source": [
    "lo, hi = parks[\"wins\"].min(), parks[\"wins\"].max()\n",
    "m = folium.Map(location=[38.5, -96], zoom_start=4, height=520, tiles=\"Esri.WorldGrayCanvas\")\n",
    "colors = sdvplot.team_colors(\"mlb\", parks[\"abbr\"])\n",
    "for row, color in zip(parks.iter_rows(named=True), colors, strict=True):\n",
    "    popup = (\n",
    "        f'<img src=\"{sdvplot.logo_url(row[\"abbr\"], \"mlb\")}\" width=\"48\"><br>'\n",
    "        f\"<b>{row['team']}</b><br>{row['park']}, {row['city']}<br>\"\n",
    "        f\"{row['wins']:.0f}-{row['losses']:.0f}, run differential {row['point_differential']:+.0f}\"\n",
    "    )\n",
    "    folium.CircleMarker(\n",
    "        [row[\"latitude\"], row[\"longitude\"]],\n",
    "        radius=8 + 14 * (row[\"wins\"] - lo) / (hi - lo),  # 8 px for the fewest wins, 22 px for the most\n",
    "        color=color,\n",
    "        weight=2,\n",
    "        fill=True,\n",
    "        fill_color=color,\n",
    "        fill_opacity=0.45,\n",
    "        popup=folium.Popup(popup, max_width=240),\n",
    "    ).add_to(m)\n",
    "sdvplot.add_logos(m, parks[\"longitude\"], parks[\"latitude\"], parks[\"abbr\"], league=\"mlb\", height=0.035)\n",
    "m"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8",
   "metadata": {},
   "source": [
    "## 3. A division in wordmarks\n",
    "\n",
    "`add_wordmarks` draws the team's wordmark instead of its logo. MLB's wordmarks come in `on_light` and\n",
    "`on_dark` variants (see `sdvplot.marks`), so name the one that suits the tiles. `fit_bounds` frames the\n",
    "map on the parks themselves. The American League East:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9",
   "metadata": {},
   "outputs": [],
   "source": [
    "al_east = parks.filter(pl.col(\"division\") == \"American League East\")\n",
    "m = folium.Map(height=520, tiles=\"Esri.WorldGrayCanvas\")\n",
    "sdvplot.add_wordmarks(\n",
    "    m, al_east[\"longitude\"], al_east[\"latitude\"], al_east[\"abbr\"], league=\"mlb\", variant=\"on_light\", height=0.07\n",
    ")\n",
    "m.fit_bounds(al_east.select(\"latitude\", \"longitude\").rows(), padding=(60, 60))\n",
    "m"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "10",
   "metadata": {},
   "source": [
    "## 4. One layer per conference, with a layer control\n",
    "\n",
    "sdvplot puts its markers in one `FeatureGroup` named \"sdvplot logos\", so a `LayerControl` lists them as\n",
    "one layer. Add a group of your own per conference, here rings in each conference's color from\n",
    "`sdvplot.teams(\"cfb\", include_conferences=True)`, and the control turns the conferences on and off while\n",
    "the logo layer stays one switch. The Power Four's stadiums, with each one's name and capacity on hover:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "11",
   "metadata": {},
   "outputs": [],
   "source": [
    "power4 = [\"SEC\", \"Big Ten\", \"Big 12\", \"ACC\"]\n",
    "conferences = sdvplot.teams(\"cfb\", include_conferences=True).select(\"team_id\", \"color_primary\")\n",
    "conference_colors = dict(conferences.iter_rows())\n",
    "p4 = stadiums.filter(pl.col(\"conference\").is_in(power4))\n",
    "m = folium.Map(location=[37.5, -92], zoom_start=4, height=560, tiles=\"Esri.WorldGrayCanvas\")\n",
    "for conference in power4:\n",
    "    layer = folium.FeatureGroup(name=conference).add_to(m)\n",
    "    for row in p4.filter(pl.col(\"conference\") == conference).iter_rows(named=True):\n",
    "        folium.CircleMarker(\n",
    "            [row[\"latitude\"], row[\"longitude\"]],\n",
    "            radius=16,\n",
    "            color=conference_colors[conference],\n",
    "            weight=4,\n",
    "            fill=False,\n",
    "            tooltip=f\"{row['school']}: {row['venue_name']}, {row['capacity']:,} seats\",\n",
    "        ).add_to(layer)\n",
    "sdvplot.add_logos(m, p4[\"longitude\"], p4[\"latitude\"], p4[\"team_id\"], league=\"cfb\", season=CFB_SEASON, height=0.04)\n",
    "folium.LayerControl(collapsed=False).add_to(m)\n",
    "m"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "12",
   "metadata": {},
   "source": [
    "## 5. Dark tiles and dark logos\n",
    "\n",
    "On a dark basemap, ask for each team's `dark` variant: the version of the logo made for dark backgrounds.\n",
    "The Big 12 on Esri's dark gray canvas:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "13",
   "metadata": {},
   "outputs": [],
   "source": [
    "big12 = stadiums.filter(pl.col(\"conference\") == \"Big 12\")\n",
    "dark_gray = \"https://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Dark_Gray_Base/MapServer\"\n",
    "m = folium.Map(\n",
    "    location=[36.5, -98],\n",
    "    zoom_start=4,\n",
    "    height=520,\n",
    "    tiles=dark_gray + \"/tile/{z}/{y}/{x}\",\n",
    "    attr=\"Tiles &copy; Esri &mdash; Esri, HERE, Garmin, &copy; OpenStreetMap contributors\",\n",
    ")\n",
    "sdvplot.add_logos(\n",
    "    m, big12[\"longitude\"], big12[\"latitude\"], big12[\"team_id\"], league=\"cfb\", season=CFB_SEASON, variant=\"dark\",\n",
    "    height=0.07,\n",
    ")  # fmt: skip\n",
    "m"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "14",
   "metadata": {},
   "source": [
    "## 6. A roster's hometowns, in headshots\n",
    "\n",
    "`add_headshots` places ESPN player headshots the same way; cfbfastR's roster ids are ESPN athlete ids,\n",
    "and the tooltip is the id. Indiana's quarterbacks, running backs, receivers and tight ends at their\n",
    "hometowns, with the Hoosiers' logo at their home stadium:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "15",
   "metadata": {},
   "outputs": [],
   "source": [
    "hoosiers = rosters.filter(\n",
    "    pl.col(\"team\") == \"Indiana\",\n",
    "    pl.col(\"position\").is_in([\"QB\", \"RB\", \"WR\", \"TE\"]),\n",
    "    pl.col(\"home_latitude\").is_not_null(),\n",
    ")\n",
    "home = stadiums.filter(pl.col(\"school\") == \"Indiana\")\n",
    "m = folium.Map(location=[36, -86], zoom_start=5, height=560, tiles=\"Esri.WorldGrayCanvas\")\n",
    "sdvplot.add_headshots(\n",
    "    m, hoosiers[\"home_longitude\"], hoosiers[\"home_latitude\"], hoosiers[\"athlete_id\"], league=\"cfb\", height=0.07\n",
    ")\n",
    "sdvplot.add_logos(m, home[\"longitude\"], home[\"latitude\"], home[\"team_id\"], league=\"cfb\", height=0.1)\n",
    "print(f\"{hoosiers.height} players\")\n",
    "m"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "sdvplot": {
   "description": "Six Folium map recipes: MLB ballparks, team-colored circles with popups, division wordmarks, a layer per conference, dark tiles with dark logos, and a roster's hometowns in headshots.",
   "label": "folium maps",
   "position": 12
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
