{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "e06a27bf",
   "metadata": {},
   "source": [
    "# Calculating Coverage Percentage of the AOI by an Item\n",
    "\n",
    "This notebook demonstrates the use of pystac-client to calculate the percentage an Item's geometry that intesects with the area of interest (AOI) specified in the search by the `intersects` parameter."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b65de617",
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import Any, Dict\n",
    "\n",
    "import matplotlib.pyplot as plt\n",
    "from pystac.item import Item\n",
    "from shapely.geometry import shape\n",
    "\n",
    "from pystac_client import Client"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "98942e75",
   "metadata": {},
   "outputs": [],
   "source": [
    "def intersection_percent(item: Item, aoi: Dict[str, Any]) -> float:\n",
    "    \"\"\"The percentage that the Item's geometry intersects the AOI. An Item that\n",
    "    completely covers the AOI has a value of 100.\n",
    "    \"\"\"\n",
    "    geom_item = shape(item.geometry)\n",
    "    geom_aoi = shape(aoi)\n",
    "\n",
    "    intersected_geom = geom_aoi.intersection(geom_item)\n",
    "\n",
    "    intersection_percent = (intersected_geom.area * 100) / geom_aoi.area\n",
    "\n",
    "    return intersection_percent\n",
    "\n",
    "\n",
    "# STAC API root URL\n",
    "URL = \"https://planetarycomputer.microsoft.com/api/stac/v1\"\n",
    "\n",
    "# geometry of the AOI to search over\n",
    "intersects_geometry = {\n",
    "    \"type\": \"Polygon\",\n",
    "    \"coordinates\": [\n",
    "        [\n",
    "            [-73.21, 43.99],\n",
    "            [-73.21, 47.05],\n",
    "            [-70.12, 47.05],\n",
    "            [-70.12, 43.99],\n",
    "            [-73.21, 43.99],\n",
    "        ]\n",
    "    ],\n",
    "}\n",
    "\n",
    "# Create a Client and an ItemSearch representing our search\n",
    "# No search operations will be performed until we call the items() method\n",
    "client = Client.open(URL)\n",
    "item_search = client.search(\n",
    "    collections=[\"sentinel-2-l2a\"], intersects=intersects_geometry, max_items=100\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0b0883fe",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(\n",
    "    [\n",
    "        f\"{intersection_percent(item, intersects_geometry):.2f}\"\n",
    "        for item in item_search.items()\n",
    "    ]\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "03254847",
   "metadata": {},
   "outputs": [],
   "source": [
    "# create a generator that filters to only those Items that intersect more than 5%\n",
    "items_gt_5_percent = (\n",
    "    i for i in item_search.items() if intersection_percent(i, intersects_geometry) > 5\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e1de7a09",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Render the AOI and Item results\n",
    "# The green shape is the AOI\n",
    "# The blue shapes are the Item geometries\n",
    "# If there are no blue shapes, adjust the intersection percent filter above\n",
    "# until there are\n",
    "\n",
    "cm = plt.get_cmap(\"RdBu\")\n",
    "fig, axs = plt.subplots()\n",
    "axs.set_aspect(\"equal\", \"datalim\")\n",
    "\n",
    "for item in items_gt_5_percent:\n",
    "    xs, ys = shape(item.geometry).exterior.xy\n",
    "    axs.fill(xs, ys, alpha=0.5, fc=\"b\", ec=\"none\")\n",
    "\n",
    "geom_intersects = shape(intersects_geometry)\n",
    "xs, ys = geom_intersects.exterior.xy\n",
    "axs.fill(xs, ys, alpha=0.5, fc=\"g\", ec=\"none\")\n",
    "\n",
    "plt.show()"
   ]
  }
 ],
 "metadata": {
  "interpreter": {
   "hash": "6b6313dbab648ff537330b996f33bf845c0da10ea77ae70864d6ca8e2699c7ea"
  },
  "kernelspec": {
   "display_name": "Python 3.9.11 ('.venv': venv)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
