{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "cell-00",
   "metadata": {},
   "source": [
    "# Make your own flood animation from VIIRS\n",
    "\n",
    "This notebook rebuilds the 2022 Pakistan floods animation on the\n",
    "[walkthrough page](https://viirs.blu-h.org/walkthrough/), one step at a time.\n",
    "At the end you point it at a place and dates of your own.\n",
    "\n",
    "It reads Blu-H's VIIRS flood archive directly from Microsoft Planetary Computer Pro:\n",
    "\n",
    "1. Install the libraries\n",
    "2. Choose what to animate\n",
    "3. Sign in\n",
    "4. Find the images\n",
    "5. Look inside one image\n",
    "6. Read every frame\n",
    "7. Draw a frame\n",
    "8. Make the animation\n",
    "9. Your turn\n",
    "\n",
    "**You need** view access to the archive (the invitation email from Blu-H) and\n",
    "Python 3.10 or later. It runs in Jupyter or Google Colab. The showcase takes\n",
    "about ten minutes, most of it reading images."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-01",
   "metadata": {},
   "source": [
    "## 1. Install the libraries\n",
    "\n",
    "Safe to run again. In Colab, run it once per session."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-02",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install --quiet \"rasterio>=1.4,<2\" \"azure-identity>=1.17,<2\" \"requests>=2.31,<3\" \"matplotlib>=3.8,<4\" \"imageio>=2.34,<3\" \"imageio-ffmpeg>=0.5,<1\" \"pillow>=10,<13\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-03",
   "metadata": {},
   "source": [
    "## 2. Choose what to animate\n",
    "\n",
    "These settings make the showcase: the 2022 monsoon floods along the lower\n",
    "Indus in Pakistan, from the first rains in June to the slow draining in\n",
    "November. Step 9 explains how to change them."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-04",
   "metadata": {},
   "outputs": [],
   "source": [
    "from pathlib import Path\n",
    "\n",
    "# Blu-H's catalog. Leave these as they are.\n",
    "CATALOG_URL = \"https://gc-viirs-dev.emetfsbgdzgxgxd4.northcentralus.geocatalog.spatio.azure.com\"\n",
    "TENANT = \"blu-h.org\"  # the Microsoft Entra directory you're a guest in\n",
    "COLLECTION = \"water-com-viirs\"  # VIIRS 1-day and 5-day flood composites, 375 m\n",
    "\n",
    "# What to animate.\n",
    "PLACE = \"Lower Indus, Pakistan\"\n",
    "AOI = (66.5, 24.0, 71.5, 29.5)  # west, south, east, north, in degrees\n",
    "START = \"2022-06-15\"\n",
    "END = \"2022-11-30\"\n",
    "COMPOSITE_DAYS = 5  # 5 or 1. See step 4.\n",
    "EVERY_DAYS = 1  # one frame every N days\n",
    "FPS = 8  # frames per second in the video\n",
    "\n",
    "OUTPUT_DIR = Path(\"viirs-flood-animation\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-05",
   "metadata": {},
   "source": [
    "## 3. Sign in\n",
    "\n",
    "Running the next cell prints a link and a code. Open the link, enter the code\n",
    "and sign in with **the email your invitation was sent to**. You stay signed in\n",
    "until the notebook restarts."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-06",
   "metadata": {},
   "outputs": [],
   "source": [
    "import datetime as dt\n",
    "\n",
    "import requests\n",
    "from azure.identity import DeviceCodeCredential\n",
    "from requests.adapters import HTTPAdapter\n",
    "from urllib3.util.retry import Retry\n",
    "\n",
    "API_VERSION = \"2025-04-30-preview\"\n",
    "SCOPE = \"https://geocatalog.spatio.azure.com/.default\"\n",
    "\n",
    "if not CATALOG_URL.startswith(\"https://\"):\n",
    "    raise ValueError(\n",
    "        \"CATALOG_URL isn't set. Download the current notebook from \"\n",
    "        \"https://viirs.blu-h.org/walkthrough/\"\n",
    "    )\n",
    "CATALOG_URL = CATALOG_URL.rstrip(\"/\")\n",
    "\n",
    "credential = DeviceCodeCredential(tenant_id=TENANT)\n",
    "\n",
    "# Retry briefly when the service is busy, instead of failing the whole run.\n",
    "session = requests.Session()\n",
    "retry = Retry(\n",
    "    total=4, backoff_factor=1, status_forcelist=(429, 500, 502, 503, 504), allowed_methods=None\n",
    ")\n",
    "session.mount(\"https://\", HTTPAdapter(max_retries=retry))\n",
    "\n",
    "\n",
    "def catalog(method, path, **kwargs):\n",
    "    \"\"\"Call the catalog API and return its JSON reply.\"\"\"\n",
    "    token = credential.get_token(SCOPE).token  # azure-identity caches and renews it\n",
    "    reply = session.request(\n",
    "        method,\n",
    "        CATALOG_URL + path,\n",
    "        params={\"api-version\": API_VERSION},\n",
    "        headers={\"Authorization\": f\"Bearer {token}\"},\n",
    "        timeout=60,\n",
    "        **kwargs,\n",
    "    )\n",
    "    if reply.status_code == 401:\n",
    "        raise PermissionError(\n",
    "            \"The catalog didn't accept the sign-in. Run this cell again and sign in \"\n",
    "            \"with the email your invitation was sent to.\"\n",
    "        )\n",
    "    if reply.status_code == 403:\n",
    "        raise PermissionError(\n",
    "            \"You're signed in, but this account can't read the archive. Check that you \"\n",
    "            \"accepted the invitation, or write to info@blu-h.org.\"\n",
    "        )\n",
    "    reply.raise_for_status()\n",
    "    return reply.json()\n",
    "\n",
    "\n",
    "_sas = {\"token\": \"\", \"expires\": dt.datetime.min.replace(tzinfo=dt.timezone.utc)}\n",
    "\n",
    "\n",
    "def sas_token():\n",
    "    \"\"\"A read-only token for the archive's image files, renewed before it expires.\n",
    "\n",
    "    It works like a password for the files, so the notebook never prints it.\n",
    "    \"\"\"\n",
    "    if _sas[\"expires\"] - dt.datetime.now(dt.timezone.utc) < dt.timedelta(minutes=30):\n",
    "        reply = catalog(\"GET\", f\"/sas/token/{COLLECTION}\")\n",
    "        _sas[\"token\"] = reply[\"token\"]\n",
    "        _sas[\"expires\"] = dt.datetime.fromisoformat(reply[\"msft:expiry\"].replace(\"Z\", \"+00:00\"))\n",
    "    return _sas[\"token\"]\n",
    "\n",
    "\n",
    "collection = catalog(\"GET\", f\"/stac/collections/{COLLECTION}\")\n",
    "sas_token()\n",
    "print(f\"Signed in. Reading from: {collection.get('title', COLLECTION)}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-07",
   "metadata": {},
   "source": [
    "## 4. Find the images\n",
    "\n",
    "The archive is a [STAC](https://stacspec.org/) catalog: every image is an\n",
    "*item* with a footprint, dates and links to its files. One search returns\n",
    "every item that overlaps your area and dates.\n",
    "\n",
    "The flood maps come as **composites**. Each pixel keeps the most water seen\n",
    "over 1 or 5 days, which removes most of the cloud from any single overpass. The\n",
    "5-day composite starting on 30 August covers 30 August to 3 September. A\n",
    "new one starts every day, so neighbouring frames overlap and the animation is\n",
    "smooth.\n",
    "\n",
    "Large areas cross more than one 15° tile of the archive's grid. Those tiles\n",
    "are joined into one image per date in step 6."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-08",
   "metadata": {},
   "outputs": [],
   "source": [
    "from collections import defaultdict\n",
    "\n",
    "MAX_FRAMES = 400\n",
    "\n",
    "start, end = dt.date.fromisoformat(START), dt.date.fromisoformat(END)\n",
    "west, south, east, north = AOI\n",
    "if not (-180 <= west < east <= 180 and -90 <= south < north <= 90):\n",
    "    raise ValueError(\n",
    "        \"AOI must be (west, south, east, north) in degrees, west < east, south < north.\"\n",
    "    )\n",
    "if start > end:\n",
    "    raise ValueError(\"START must be on or before END.\")\n",
    "if COMPOSITE_DAYS not in (1, 5):\n",
    "    raise ValueError(\"COMPOSITE_DAYS must be 1 or 5.\")\n",
    "\n",
    "\n",
    "def search(aoi, first, last):\n",
    "    \"\"\"Every item overlapping the area between two dates, following page links.\"\"\"\n",
    "    body = {\n",
    "        \"collections\": [COLLECTION],\n",
    "        \"bbox\": list(aoi),\n",
    "        \"datetime\": f\"{first}T00:00:00Z/{last}T23:59:59Z\",\n",
    "        \"limit\": 200,\n",
    "    }\n",
    "    items = []\n",
    "    for _ in range(100):\n",
    "        page = catalog(\"POST\", \"/stac/search\", json=body)\n",
    "        items += page[\"features\"]\n",
    "        following = [link for link in page.get(\"links\", []) if link.get(\"rel\") == \"next\"]\n",
    "        if not following:\n",
    "            return items\n",
    "        body = following[0][\"body\"]  # the next page is the same search with a page token\n",
    "    raise RuntimeError(\"The search returned too many pages. Use a smaller area or fewer dates.\")\n",
    "\n",
    "\n",
    "def window_start(item):\n",
    "    return dt.date.fromisoformat(item[\"properties\"][\"start_datetime\"][:10])\n",
    "\n",
    "\n",
    "# One item per date and tile. If an image was ever re-processed, keep the newest.\n",
    "items_by_date = defaultdict(dict)\n",
    "for item in search(AOI, start, end):\n",
    "    props = item[\"properties\"]\n",
    "    if (\n",
    "        props.get(\"viirs:composite_days\") != COMPOSITE_DAYS\n",
    "        or not start <= window_start(item) <= end\n",
    "    ):\n",
    "        continue\n",
    "    tile = props.get(\"viirs:grid\", item[\"id\"])\n",
    "    kept = items_by_date[window_start(item)].get(tile)\n",
    "    if kept is None or (props.get(\"created\", \"\"), item[\"id\"]) > (\n",
    "        kept[\"properties\"].get(\"created\", \"\"),\n",
    "        kept[\"id\"],\n",
    "    ):\n",
    "        items_by_date[window_start(item)][tile] = item\n",
    "\n",
    "wanted = [start + dt.timedelta(days=d) for d in range(0, (end - start).days + 1, EVERY_DAYS)]\n",
    "frame_dates = [d for d in wanted if d in items_by_date]\n",
    "missing = [d for d in wanted if d not in items_by_date]\n",
    "\n",
    "if not frame_dates:\n",
    "    raise LookupError(\n",
    "        \"No images for this area and these dates. The archive may not cover them: \"\n",
    "        \"try other dates, or COMPOSITE_DAYS = 1.\"\n",
    "    )\n",
    "if len(frame_dates) > MAX_FRAMES:\n",
    "    raise ValueError(\n",
    "        f\"{len(frame_dates)} frames is more than {MAX_FRAMES}. Raise EVERY_DAYS or shorten the dates.\"\n",
    "    )\n",
    "\n",
    "tiles = sorted({tile for by_tile in items_by_date.values() for tile in by_tile})\n",
    "print(\n",
    "    f\"{len(frame_dates)} frames from {frame_dates[0]} to {frame_dates[-1]}, on tiles {', '.join(tiles)}.\"\n",
    ")\n",
    "if missing:\n",
    "    print(\n",
    "        f\"{len(missing)} dates have no image and are skipped: {', '.join(map(str, missing[:10]))}\",\n",
    "        end=\"\",\n",
    "    )\n",
    "    print(\" ...\" if len(missing) > 10 else \"\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-09",
   "metadata": {},
   "source": [
    "## 5. Look inside one image\n",
    "\n",
    "Each item's `visual` file is a Cloud-Optimized GeoTIFF: one number per 375 m\n",
    "pixel, stored in blocks so you can fetch just your area instead of the whole\n",
    "15° tile.\n",
    "\n",
    "The number is a code from the\n",
    "[NOAA VIIRS Flood Mapping ATBD](https://www.star.nesdis.noaa.gov/jpss/documents/ATBD/ATBD_VIIRS_Flood_Mapping_v1.0.pdf)\n",
    "(Table 2-4):\n",
    "\n",
    "| Code | Meaning |\n",
    "| --- | --- |\n",
    "| 16, 17 | Clear land: bare soil, vegetation |\n",
    "| 20, 27, 38 | Snow, river or lake ice, water on snow or ice |\n",
    "| 30, 50 | Cloud, cloud or terrain shadow |\n",
    "| 99, 100 | Usual open water: river, lake, reservoir, sea. These files use 99; the ATBD lists 100 |\n",
    "| 15 | Open water whose fraction couldn't be measured. Shown as usual water |\n",
    "| **101 to 200** | **Flood water**: code − 100 is the percentage of the pixel under water |\n",
    "| 1, 255 | No data |\n",
    "\n",
    "\"Flood water\" means water where the reference map of permanent water says\n",
    "there is usually none.\n",
    "\n",
    "The files also hold smaller preview copies (overviews), but those were made by\n",
    "averaging codes, and an average of \"cloud\" and \"40% flood\" means nothing. So\n",
    "this notebook always reads full-resolution pixels."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-10",
   "metadata": {
    "tags": [
     "pure"
    ]
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "NODATA = 255  # where the archive's converter found no value\n",
    "\n",
    "CLASSES = {\n",
    "    \"Land\": (16, 17),\n",
    "    \"Usual water\": (15, 99, 100),\n",
    "    \"Cloud or shadow\": (30, 50),\n",
    "    \"Snow or ice\": (20, 27, 38),\n",
    "    \"No data\": (1, NODATA),\n",
    "}\n",
    "FLOOD_CODES = range(101, 201)\n",
    "\n",
    "COLOURS = {\n",
    "    \"Land\": \"#e9e4da\",\n",
    "    \"Usual water\": \"#5b7083\",\n",
    "    \"Cloud or shadow\": \"#b9bcc0\",\n",
    "    \"Snow or ice\": \"#d9cfe8\",\n",
    "    \"No data\": \"#ffffff\",\n",
    "}\n",
    "# Blu-H's flood ramp (ColorBrewer Blues), from 0 % to 100 % of the pixel under water.\n",
    "FLOOD_RAMP = (\"#deebf7\", \"#9ecae1\", \"#3182bd\", \"#08519c\", \"#08306b\")\n",
    "\n",
    "\n",
    "def _rgb(hex_colour):\n",
    "    return [int(hex_colour[i : i + 2], 16) for i in (1, 3, 5)]\n",
    "\n",
    "\n",
    "def colour_table():\n",
    "    \"\"\"A 256-entry lookup from code to RGB. Unknown codes show as no data.\"\"\"\n",
    "    table = np.tile(np.array(_rgb(COLOURS[\"No data\"]), dtype=np.uint8), (256, 1))\n",
    "    for name, codes in CLASSES.items():\n",
    "        table[list(codes)] = _rgb(COLOURS[name])\n",
    "    stops = np.linspace(0, 100, len(FLOOD_RAMP))\n",
    "    ramp = np.array([_rgb(c) for c in FLOOD_RAMP], dtype=float)\n",
    "    percent = np.arange(1, 101)\n",
    "    for channel in range(3):\n",
    "        table[101:201, channel] = np.round(np.interp(percent, stops, ramp[:, channel]))\n",
    "    return table\n",
    "\n",
    "\n",
    "COLOUR_TABLE = colour_table()\n",
    "\n",
    "\n",
    "def to_rgb(codes):\n",
    "    \"\"\"Colour a grid of codes for display.\"\"\"\n",
    "    return COLOUR_TABLE[codes]\n",
    "\n",
    "\n",
    "def flood_percent(codes):\n",
    "    \"\"\"Percentage of each pixel under flood water, 0 where there's none.\"\"\"\n",
    "    flooded = (codes >= FLOOD_CODES.start) & (codes < FLOOD_CODES.stop)\n",
    "    return np.where(flooded, codes.astype(np.int16) - 100, 0)\n",
    "\n",
    "\n",
    "def class_shares(codes):\n",
    "    \"\"\"Share of the pixels in each class, plus flood water and anything unexpected.\"\"\"\n",
    "    counts = np.bincount(codes.ravel(), minlength=256)\n",
    "    shares = {name: counts[list(c)].sum() / codes.size for name, c in CLASSES.items()}\n",
    "    shares[\"Flood water\"] = counts[FLOOD_CODES.start : FLOOD_CODES.stop].sum() / codes.size\n",
    "    shares[\"Unexpected codes\"] = 1 - sum(shares.values())\n",
    "    return shares\n",
    "\n",
    "\n",
    "def row_areas_km2(top, pixel_deg, rows):\n",
    "    \"\"\"Area of one pixel in each row, in km². Pixels shrink towards the poles.\"\"\"\n",
    "    radius_km = 6371.0088\n",
    "    edges = np.radians(top - pixel_deg * np.arange(rows + 1))\n",
    "    return radius_km**2 * np.radians(pixel_deg) * (np.sin(edges[:-1]) - np.sin(edges[1:]))\n",
    "\n",
    "\n",
    "def flooded_km2(codes, row_areas):\n",
    "    \"\"\"Area under flood water: each pixel counts for its share of water.\"\"\"\n",
    "    return float((flood_percent(codes) / 100 * row_areas[:, None]).sum())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-11",
   "metadata": {},
   "source": [
    "Reading works the same way for every date: lay a pixel grid over your area,\n",
    "then copy each tile's pixels onto it. The grid is lined up with the archive's\n",
    "own pixels, so nothing is resampled. The images are saved in `OUTPUT_DIR`, so\n",
    "running again doesn't download them twice."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-12",
   "metadata": {},
   "outputs": [],
   "source": [
    "import hashlib\n",
    "import json\n",
    "import math\n",
    "import re\n",
    "\n",
    "import rasterio\n",
    "from rasterio.enums import Resampling\n",
    "from rasterio.errors import RasterioIOError\n",
    "from rasterio.transform import Affine\n",
    "from rasterio.vrt import WarpedVRT\n",
    "\n",
    "GDAL_OPTIONS = {\n",
    "    \"GDAL_DISABLE_READDIR_ON_OPEN\": \"EMPTY_DIR\",  # don't list the storage folder\n",
    "    \"GDAL_HTTP_MAX_RETRY\": \"4\",\n",
    "    \"GDAL_HTTP_RETRY_DELAY\": \"2\",\n",
    "    \"GDAL_HTTP_MERGE_CONSECUTIVE_RANGES\": \"YES\",\n",
    "}\n",
    "MAX_PIXELS = 9_000_000  # about 10° × 10°\n",
    "CACHE_DIR = OUTPUT_DIR / \"cache\"\n",
    "\n",
    "\n",
    "def signed(item):\n",
    "    return f\"{item['assets']['visual']['href']}?{sas_token()}\"\n",
    "\n",
    "\n",
    "def hide_token(text):\n",
    "    return re.sub(r\"\\?\\S+\", \"?<token>\", text)\n",
    "\n",
    "\n",
    "def open_image(item):\n",
    "    try:\n",
    "        return rasterio.open(signed(item))\n",
    "    except RasterioIOError as error:\n",
    "        # `from None` keeps the file link and its token out of the error shown.\n",
    "        raise RuntimeError(f\"Couldn't open {item['id']}: {hide_token(str(error))}\") from None\n",
    "\n",
    "\n",
    "def pixel_grid(aoi, item):\n",
    "    \"\"\"A grid covering the area, lined up with the archive's pixels.\"\"\"\n",
    "    w, s, e, n = aoi\n",
    "    with rasterio.Env(**GDAL_OPTIONS), open_image(item) as image:\n",
    "        t = image.transform\n",
    "    size = t.a\n",
    "    left, top = math.floor((w - t.c) / size), math.floor((t.f - n) / size)\n",
    "    right, bottom = math.ceil((e - t.c) / size), math.ceil((t.f - s) / size)\n",
    "    width, height = right - left, bottom - top\n",
    "    if width * height > MAX_PIXELS:\n",
    "        raise ValueError(\n",
    "            f\"The area is {width} × {height} pixels, more than {MAX_PIXELS:,}. Use a smaller AOI.\"\n",
    "        )\n",
    "    transform = Affine(size, 0, t.c + left * size, 0, -size, t.f - top * size)\n",
    "    return {\"transform\": transform, \"width\": width, \"height\": height}\n",
    "\n",
    "\n",
    "def read_codes(items, grid):\n",
    "    \"\"\"Copy each tile's pixels for the area onto the grid, at full resolution.\"\"\"\n",
    "    codes = np.full((grid[\"height\"], grid[\"width\"]), NODATA, dtype=np.uint8)\n",
    "    with rasterio.Env(**GDAL_OPTIONS):\n",
    "        for item in items:\n",
    "            with open_image(item) as image:\n",
    "                try:\n",
    "                    with WarpedVRT(\n",
    "                        image,\n",
    "                        crs=image.crs,\n",
    "                        resampling=Resampling.nearest,\n",
    "                        nodata=NODATA,\n",
    "                        **grid,\n",
    "                    ) as view:\n",
    "                        tile = view.read(1)\n",
    "                except RasterioIOError as error:\n",
    "                    raise RuntimeError(\n",
    "                        f\"Couldn't read {item['id']}: {hide_token(str(error))}\"\n",
    "                    ) from None\n",
    "            codes = np.where(codes == NODATA, tile, codes)\n",
    "    return codes\n",
    "\n",
    "\n",
    "def frame_codes(date):\n",
    "    \"\"\"The codes for one date, from the saved copy if there is one.\"\"\"\n",
    "    items = sorted(items_by_date[date].values(), key=lambda item: item[\"id\"])\n",
    "    key = json.dumps([list(GRID[\"transform\"])[:6], GRID[\"width\"], GRID[\"height\"]])\n",
    "    key += json.dumps([item[\"id\"] for item in items])\n",
    "    path = CACHE_DIR / f\"{date}-{hashlib.sha256(key.encode()).hexdigest()[:16]}.npz\"\n",
    "    if path.exists():\n",
    "        with np.load(path) as saved:\n",
    "            return saved[\"codes\"]\n",
    "    codes = read_codes(items, GRID)\n",
    "    CACHE_DIR.mkdir(parents=True, exist_ok=True)\n",
    "    partial = path.with_name(path.stem + \".partial.npz\")\n",
    "    np.savez_compressed(partial, codes=codes)\n",
    "    partial.replace(path)  # a run stopped half-way never leaves a broken copy\n",
    "    return codes\n",
    "\n",
    "\n",
    "GRID = pixel_grid(AOI, next(iter(items_by_date[frame_dates[0]].values())))\n",
    "ROW_AREAS = row_areas_km2(GRID[\"transform\"].f, GRID[\"transform\"].a, GRID[\"height\"])\n",
    "print(f\"Grid: {GRID['width']} × {GRID['height']} pixels of {GRID['transform'].a:.5f}°\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-13",
   "metadata": {},
   "source": [
    "Now read one date from the middle of the run and see what it holds."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-14",
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "from matplotlib.patches import Patch\n",
    "\n",
    "sample_date = frame_dates[len(frame_dates) // 2]\n",
    "sample = frame_codes(sample_date)\n",
    "\n",
    "for name, share in class_shares(sample).items():\n",
    "    if share > 0.0005 or name == \"Flood water\":\n",
    "        print(f\"{name:>17}: {share:6.1%}\")\n",
    "print(f\"Flood water covers about {flooded_km2(sample, ROW_AREAS):,.0f} km².\")\n",
    "\n",
    "extent = (\n",
    "    GRID[\"transform\"].c,\n",
    "    GRID[\"transform\"].c + GRID[\"width\"] * GRID[\"transform\"].a,\n",
    "    GRID[\"transform\"].f - GRID[\"height\"] * GRID[\"transform\"].a,\n",
    "    GRID[\"transform\"].f,\n",
    ")\n",
    "# Degrees of longitude get shorter away from the equator; this keeps shapes true.\n",
    "ASPECT = 1 / math.cos(math.radians((extent[2] + extent[3]) / 2))\n",
    "\n",
    "fig, ax = plt.subplots(figsize=(8, 8))\n",
    "ax.imshow(to_rgb(sample), extent=extent, aspect=ASPECT, interpolation=\"antialiased\")\n",
    "ax.set_title(f\"{PLACE}: {COMPOSITE_DAYS}-day composite from {sample_date}\")\n",
    "legend = [Patch(facecolor=COLOURS[n], edgecolor=\"#9a9a9a\", label=n) for n in CLASSES]\n",
    "legend.append(Patch(facecolor=FLOOD_RAMP[3], label=\"Flood water\"))\n",
    "ax.legend(handles=legend, loc=\"lower left\", fontsize=8, framealpha=0.9)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-15",
   "metadata": {},
   "source": [
    "## 6. Read every frame\n",
    "\n",
    "Each frame downloads only the blocks under your area. Four at a time keeps it\n",
    "quick without hammering the service. For every frame the notebook also adds up\n",
    "the flooded area and how much of the view was hidden by cloud."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-16",
   "metadata": {},
   "outputs": [],
   "source": [
    "from concurrent.futures import ThreadPoolExecutor\n",
    "\n",
    "stats = []\n",
    "with ThreadPoolExecutor(max_workers=4) as pool:\n",
    "    for n, (date, codes) in enumerate(zip(frame_dates, pool.map(frame_codes, frame_dates)), 1):\n",
    "        shares = class_shares(codes)\n",
    "        stats.append(\n",
    "            {\n",
    "                \"date\": date,\n",
    "                \"flood_km2\": flooded_km2(codes, ROW_AREAS),\n",
    "                \"hidden\": shares[\"Cloud or shadow\"] + shares[\"No data\"],\n",
    "            }\n",
    "        )\n",
    "        if n % 10 == 0 or n == len(frame_dates):\n",
    "            print(f\"Read {n} of {len(frame_dates)} frames\")\n",
    "\n",
    "peak = max(range(len(stats)), key=lambda i: stats[i][\"flood_km2\"])\n",
    "print(\n",
    "    f\"Most flood water: {stats[peak]['flood_km2']:,.0f} km² \"\n",
    "    f\"in the composite from {stats[peak]['date']}.\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-17",
   "metadata": {},
   "source": [
    "## 7. Draw a frame\n",
    "\n",
    "Every frame uses the same figure: the map, its date, a legend and a timeline\n",
    "of flooded area. Only the image, the date and the timeline marker change from\n",
    "frame to frame, so nothing jumps around in the video."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-18",
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.dates as mdates\n",
    "from IPython.display import display\n",
    "from matplotlib.backends.backend_agg import FigureCanvasAgg\n",
    "from matplotlib.cm import ScalarMappable\n",
    "from matplotlib.colors import LinearSegmentedColormap, Normalize\n",
    "from matplotlib.figure import Figure\n",
    "from matplotlib.ticker import FuncFormatter\n",
    "\n",
    "WIDTH_PX, HEIGHT_PX = 960, 1088  # multiples of 16 keep video players happy\n",
    "DPI = 100\n",
    "FLOOD_CMAP = LinearSegmentedColormap.from_list(\"flood\", FLOOD_RAMP)\n",
    "\n",
    "\n",
    "def window_label(date):\n",
    "    last = date + dt.timedelta(days=COMPOSITE_DAYS - 1)\n",
    "    if COMPOSITE_DAYS == 1:\n",
    "        return f\"{date.day} {date:%b %Y}\"\n",
    "    if (date.year, date.month) == (last.year, last.month):\n",
    "        return f\"{date.day}–{last.day} {last:%b %Y}\"\n",
    "    first = f\"{date.day} {date:%b}\" if date.year == last.year else f\"{date.day} {date:%b %Y}\"\n",
    "    return f\"{first} – {last.day} {last:%b %Y}\"\n",
    "\n",
    "\n",
    "def degrees(axis):\n",
    "    def label(value, _):\n",
    "        if axis == \"lon\":\n",
    "            return f\"{abs(value):g}°{'E' if value >= 0 else 'W'}\"\n",
    "        return f\"{abs(value):g}°{'N' if value >= 0 else 'S'}\"\n",
    "\n",
    "    return FuncFormatter(label)\n",
    "\n",
    "\n",
    "def make_animator():\n",
    "    \"\"\"Build the figure once. Returns it and a function that draws frame i.\"\"\"\n",
    "    # A standalone figure with its own renderer draws the same in Jupyter,\n",
    "    # Colab and scripts, and never pops up on its own.\n",
    "    fig = Figure(figsize=(WIDTH_PX / DPI, HEIGHT_PX / DPI), dpi=DPI, facecolor=\"white\")\n",
    "    canvas = FigureCanvasAgg(fig)\n",
    "\n",
    "    fig.text(0.06, 0.965, PLACE, fontsize=19, fontweight=\"bold\", va=\"top\")\n",
    "    fig.text(\n",
    "        0.06,\n",
    "        0.925,\n",
    "        f\"Flood water seen by VIIRS, {COMPOSITE_DAYS}-day composites\",\n",
    "        fontsize=12,\n",
    "        color=\"#4a4a4a\",\n",
    "        va=\"top\",\n",
    "    )\n",
    "    date_text = fig.text(0.94, 0.965, \"\", fontsize=17, ha=\"right\", va=\"top\")\n",
    "    hidden_text = fig.text(0.94, 0.925, \"\", fontsize=11, ha=\"right\", va=\"top\", color=\"#4a4a4a\")\n",
    "\n",
    "    ax = fig.add_axes((0.08, 0.30, 0.86, 0.6))\n",
    "    image = ax.imshow(\n",
    "        to_rgb(frame_codes(frame_dates[0])),\n",
    "        extent=extent,\n",
    "        aspect=ASPECT,\n",
    "        interpolation=\"antialiased\",\n",
    "    )\n",
    "    ax.xaxis.set_major_formatter(degrees(\"lon\"))\n",
    "    ax.yaxis.set_major_formatter(degrees(\"lat\"))\n",
    "    ax.tick_params(labelsize=9)\n",
    "\n",
    "    legend = fig.add_axes((0.08, 0.235, 0.86, 0.03))\n",
    "    legend.set_axis_off()\n",
    "    legend.legend(\n",
    "        handles=[Patch(facecolor=COLOURS[n], edgecolor=\"#9a9a9a\", label=n) for n in CLASSES],\n",
    "        loc=\"center left\",\n",
    "        ncol=len(CLASSES),\n",
    "        frameon=False,\n",
    "        fontsize=10,\n",
    "        handlelength=1.2,\n",
    "        borderaxespad=0,\n",
    "    )\n",
    "    bar = fig.add_axes((0.08, 0.2, 0.36, 0.014))\n",
    "    fig.colorbar(ScalarMappable(Normalize(0, 100), FLOOD_CMAP), cax=bar, orientation=\"horizontal\")\n",
    "    bar.tick_params(labelsize=9)\n",
    "    fig.text(0.46, 0.207, \"Flood water, % of each 375 m pixel\", fontsize=10, va=\"center\")\n",
    "\n",
    "    timeline = fig.add_axes((0.08, 0.07, 0.86, 0.075))\n",
    "    # Dates without an image are gaps in the line, not straight joins.\n",
    "    area_on = {s[\"date\"]: s[\"flood_km2\"] for s in stats}\n",
    "    dates = [d for d in wanted if frame_dates[0] <= d <= frame_dates[-1]]\n",
    "    areas = np.ma.masked_invalid([area_on.get(d, np.nan) for d in dates])\n",
    "    timeline.fill_between(dates, areas, color=FLOOD_RAMP[1], linewidth=0)\n",
    "    timeline.plot(dates, areas, color=FLOOD_RAMP[3], linewidth=1.5)\n",
    "    (marker,) = timeline.plot([], [], \"o\", color=FLOOD_RAMP[4], markersize=7)\n",
    "    cursor = timeline.axvline(dates[0], color=FLOOD_RAMP[4], linewidth=1)\n",
    "    timeline.set_xlim(dates[0], dates[-1])\n",
    "    timeline.set_ylim(0, areas.max() * 1.15 or 1)\n",
    "    timeline.yaxis.set_major_formatter(FuncFormatter(lambda v, _: f\"{v:,.0f}\"))\n",
    "    timeline.xaxis.set_major_formatter(\n",
    "        mdates.DateFormatter(\"%b %Y\" if len(dates) > 60 else \"%d %b\")\n",
    "    )\n",
    "    timeline.spines[[\"top\", \"right\"]].set_visible(False)\n",
    "    timeline.tick_params(labelsize=9)\n",
    "    timeline.set_title(\"Flood water seen, km² (clouds hide some)\", fontsize=10, loc=\"left\", pad=6)\n",
    "\n",
    "    fig.text(\n",
    "        0.06,\n",
    "        0.018,\n",
    "        \"Source: VIIRS flood product, CIMSS/SSEC for NOAA/NESDIS JPSS. Archive: Blu-H.\",\n",
    "        fontsize=8.5,\n",
    "        color=\"#6a6a6a\",\n",
    "    )\n",
    "\n",
    "    def draw(i):\n",
    "        date = frame_dates[i]\n",
    "        image.set_data(to_rgb(frame_codes(date)))\n",
    "        date_text.set_text(window_label(date))\n",
    "        hidden_text.set_text(f\"Cloud or no data: {stats[i]['hidden']:.0%}\")\n",
    "        marker.set_data([date], [stats[i][\"flood_km2\"]])\n",
    "        cursor.set_xdata([date, date])\n",
    "        canvas.draw()\n",
    "        return np.asarray(canvas.buffer_rgba())[..., :3].copy()\n",
    "\n",
    "    return fig, draw\n",
    "\n",
    "\n",
    "fig, draw = make_animator()\n",
    "draw(peak)\n",
    "display(fig)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-19",
   "metadata": {},
   "source": [
    "## 8. Make the animation\n",
    "\n",
    "This draws every frame and writes an MP4 video and a smaller GIF to\n",
    "`OUTPUT_DIR`. The last frame is held for a second before the video loops."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-20",
   "metadata": {},
   "outputs": [],
   "source": [
    "import imageio.v2 as imageio\n",
    "from IPython.display import Video\n",
    "from PIL import Image\n",
    "\n",
    "name = re.sub(r\"[^a-z0-9]+\", \"-\", f\"{PLACE} {START} {END}\".lower()).strip(\"-\")\n",
    "mp4_path, gif_path = OUTPUT_DIR / f\"{name}.mp4\", OUTPUT_DIR / f\"{name}.gif\"\n",
    "OUTPUT_DIR.mkdir(parents=True, exist_ok=True)\n",
    "\n",
    "fig, draw = make_animator()\n",
    "order = list(range(len(frame_dates))) + [len(frame_dates) - 1] * FPS\n",
    "\n",
    "gif_frames = []\n",
    "with imageio.get_writer(\n",
    "    mp4_path,\n",
    "    fps=FPS,\n",
    "    codec=\"libx264\",\n",
    "    quality=8,\n",
    "    pixelformat=\"yuv420p\",\n",
    "    macro_block_size=16,\n",
    "    ffmpeg_log_level=\"error\",\n",
    ") as video:\n",
    "    for n, i in enumerate(order, 1):\n",
    "        frame = draw(i)\n",
    "        video.append_data(frame)\n",
    "        small = Image.fromarray(frame).resize((WIDTH_PX // 2, HEIGHT_PX // 2), Image.LANCZOS)\n",
    "        gif_frames.append(small.quantize(colors=128))\n",
    "        if n % 10 == 0 or n == len(order):\n",
    "            print(f\"Drew {n} of {len(order)} frames\")\n",
    "\n",
    "gif_frames[0].save(\n",
    "    gif_path, save_all=True, append_images=gif_frames[1:], duration=round(1000 / FPS), loop=0\n",
    ")\n",
    "print(f\"Saved {mp4_path} and {gif_path}\")\n",
    "display(Video(str(mp4_path), embed=True, html_attributes=\"controls loop muted playsinline\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-21",
   "metadata": {},
   "source": [
    "## 9. Your turn\n",
    "\n",
    "Go back to step 2 and change the settings:\n",
    "\n",
    "- `PLACE` is the title on the video.\n",
    "- `AOI` is `(west, south, east, north)` in degrees. To find one, draw a box\n",
    "  on [bboxfinder.com](http://bboxfinder.com/) and copy the coordinates.\n",
    "  Up to about 10° × 10°.\n",
    "- `START` and `END` are the dates, up to 400 frames. Floods that build over\n",
    "  weeks show best. A run of one to six months is a good length.\n",
    "- `COMPOSITE_DAYS = 1` gives daily maps: sharper timing, but more cloud. Keep 5\n",
    "  for cloudy seasons such as a monsoon.\n",
    "- `EVERY_DAYS = 2` or more halves the frames for a long run.\n",
    "\n",
    "Then run step 2 and every cell from step 4 down (in Jupyter: select the step 4\n",
    "cell, then **Run > Run Selected Cell and All Below**). You don't need to sign in\n",
    "again.\n",
    "\n",
    "Step 4 tells you if the archive has no images for your area and dates.\n",
    "\n",
    "### Reading the result\n",
    "\n",
    "- VIIRS sees the ground only in daylight and through gaps in the cloud. Where\n",
    "  cloud hides the ground, flood water isn't counted, so the areas are lower\n",
    "  bounds. The \"cloud or no data\" figure tells you how much of each frame that\n",
    "  applies to.\n",
    "- A composite keeps the most water seen in its window. That fills cloud gaps,\n",
    "  but it also makes water linger in the video for a few days after it's gone.\n",
    "- Each pixel is 375 m across. A shallow, scattered flood shows as a low\n",
    "  percentage over a wide area, not as a sharp edge.\n",
    "- This is a record of what the satellite saw. It isn't a substitute for\n",
    "  official flood warnings.\n",
    "\n",
    "### Credit\n",
    "\n",
    "The images and videos you make are yours to use. If you publish them, please\n",
    "credit the source: *VIIRS flood products produced by CIMSS at UW-Madison SSEC,\n",
    "funded by NOAA/NESDIS and the JPSS Program Office. Archive hosted by Blu-H.*\n",
    "\n",
    "Questions or problems: [info@blu-h.org](mailto:info@blu-h.org)."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
