{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# How to create STAC Catalogs \n", "## STAC Community Sprint, Arlington, November 7th 2019" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This notebook runs through some of the basics of using PySTAC to create a static STAC. It was part of a 30 minute presentation at the [community STAC sprint](https://github.com/radiantearth/community-sprints/tree/master/11052019-arlignton-va) in Arlington, VA in November 2019." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This tutorial will require the `boto3`, `rasterio`, and `shapely` libraries:" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Requirement already satisfied: boto3 in /Users/rob/proj/stac/pystac/venv/lib/python3.6/site-packages (1.10.8)\n", "Requirement already satisfied: botocore<1.14.0,>=1.13.8 in /Users/rob/proj/stac/pystac/venv/lib/python3.6/site-packages (from boto3) (1.13.8)\n", "Requirement already satisfied: s3transfer<0.3.0,>=0.2.0 in /Users/rob/proj/stac/pystac/venv/lib/python3.6/site-packages (from boto3) (0.2.1)\n", "Requirement already satisfied: jmespath<1.0.0,>=0.7.1 in /Users/rob/proj/stac/pystac/venv/lib/python3.6/site-packages (from boto3) (0.9.4)\n", "Requirement already satisfied: urllib3<1.26,>=1.20; python_version >= \"3.4\" in /Users/rob/proj/stac/pystac/venv/lib/python3.6/site-packages (from botocore<1.14.0,>=1.13.8->boto3) (1.25.6)\n", "Requirement already satisfied: docutils<0.16,>=0.10 in /Users/rob/proj/stac/pystac/venv/lib/python3.6/site-packages (from botocore<1.14.0,>=1.13.8->boto3) (0.15.2)\n", "Requirement already satisfied: python-dateutil<3.0.0,>=2.1; python_version >= \"2.7\" in /Users/rob/proj/stac/pystac/venv/lib/python3.6/site-packages (from botocore<1.14.0,>=1.13.8->boto3) (2.8.1)\n", "Requirement already satisfied: six>=1.5 in /Users/rob/proj/stac/pystac/venv/lib/python3.6/site-packages (from python-dateutil<3.0.0,>=2.1; python_version >= \"2.7\"->botocore<1.14.0,>=1.13.8->boto3) (1.12.0)\n", "\u001b[33mWARNING: You are using pip version 20.1.1; however, version 20.2 is available.\n", "You should consider upgrading via the '/Users/rob/proj/stac/pystac/venv/bin/python -m pip install --upgrade pip' command.\u001b[0m\n", "Requirement already satisfied: rasterio in /Users/rob/proj/stac/pystac/venv/lib/python3.6/site-packages (1.1.0)\n", "Requirement already satisfied: numpy in /Users/rob/proj/stac/pystac/venv/lib/python3.6/site-packages (from rasterio) (1.17.3)\n", "Requirement already satisfied: snuggs>=1.4.1 in /Users/rob/proj/stac/pystac/venv/lib/python3.6/site-packages (from rasterio) (1.4.7)\n", "Requirement already satisfied: click<8,>=4.0 in /Users/rob/proj/stac/pystac/venv/lib/python3.6/site-packages (from rasterio) (7.0)\n", "Requirement already satisfied: click-plugins in /Users/rob/proj/stac/pystac/venv/lib/python3.6/site-packages (from rasterio) (1.1.1)\n", "Requirement already satisfied: attrs in /Users/rob/proj/stac/pystac/venv/lib/python3.6/site-packages (from rasterio) (19.3.0)\n", "Requirement already satisfied: cligj>=0.5 in /Users/rob/proj/stac/pystac/venv/lib/python3.6/site-packages (from rasterio) (0.5.0)\n", "Requirement already satisfied: affine in /Users/rob/proj/stac/pystac/venv/lib/python3.6/site-packages (from rasterio) (2.3.0)\n", "Requirement already satisfied: pyparsing>=2.1.6 in /Users/rob/proj/stac/pystac/venv/lib/python3.6/site-packages (from snuggs>=1.4.1->rasterio) (2.4.2)\n", "\u001b[33mWARNING: You are using pip version 20.1.1; however, version 20.2 is available.\n", "You should consider upgrading via the '/Users/rob/proj/stac/pystac/venv/bin/python -m pip install --upgrade pip' command.\u001b[0m\n", "Requirement already satisfied: shapely in /Users/rob/proj/stac/pystac/venv/lib/python3.6/site-packages (1.6.4.post2)\n", "\u001b[33mWARNING: You are using pip version 20.1.1; however, version 20.2 is available.\n", "You should consider upgrading via the '/Users/rob/proj/stac/pystac/venv/bin/python -m pip install --upgrade pip' command.\u001b[0m\n" ] } ], "source": [ "!pip install boto3\n", "!pip install rasterio\n", "!pip install shapely" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can import pystac and access most of the functionality we need with the single import:" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "import pystac" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Creating a catalog from a local file" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To give us some material to work with, lets download a single image from the [Spacenet 5 challenge](https://www.topcoder.com/challenges/30099956). We'll use a temporary directory to save off our single-item STAC." ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "import os\n", "import urllib.request\n", "from tempfile import TemporaryDirectory\n", "\n", "tmp_dir = TemporaryDirectory()\n", "img_path = os.path.join(tmp_dir.name, 'image.tif')" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "('/var/folders/sv/zr8j0t4j1f726nhlt3vb8c300000gn/T/tmpt1wuelid/image.tif',\n", " )" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "url = ('http://spacenet-dataset.s3.amazonaws.com/'\n", " 'spacenet/SN5_roads/train/AOI_7_Moscow/MS/'\n", " 'SN5_roads_train_AOI_7_Moscow_MS_chip996.tif')\n", "urllib.request.urlretrieve(url, img_path)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We want to create a Catalog. Let's check the pydocs for `Catalog` to see what information we'll need. (We use `__doc__` instead of `help()` here to avoid printing out all the docs for the class.)" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "A PySTAC Catalog represents a STAC catalog in memory.\n", "\n", " A Catalog is a :class:`~pystac.STACObject` that may contain children,\n", " which are instances of :class:`~pystac.Catalog` or :class:`~pystac.Collection`,\n", " as well as :class:`~pystac.Item` s.\n", "\n", " Args:\n", " id (str): Identifier for the catalog. Must be unique within the STAC.\n", " description (str): Detailed multi-line description to fully explain the catalog.\n", " `CommonMark 0.28 syntax `_ MAY be used for rich text\n", " representation.\n", " title (str or None): Optional short descriptive one-line title for the catalog.\n", " stac_extensions (List[str]): Optional list of extensions the Catalog implements.\n", " href (str or None): Optional HREF for this catalog, which be set as the catalog's\n", " self link's HREF.\n", "\n", " Attributes:\n", " id (str): Identifier for the catalog.\n", " description (str): Detailed multi-line description to fully explain the catalog.\n", " title (str or None): Optional short descriptive one-line title for the catalog.\n", " stac_extensions (List[str] or None): Optional list of extensions the Catalog implements.\n", " extra_fields (dict or None): Extra fields that are part of the top-level JSON properties\n", " of the Catalog.\n", " links (List[Link]): A list of :class:`~pystac.Link` objects representing\n", " all links associated with this Catalog.\n", " \n" ] } ], "source": [ "print(pystac.Catalog.__doc__)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's just give an ID and a description. We don't have to worry about the HREF right now; that will be set later." ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "catalog = pystac.Catalog(id='test-catalog', description='Tutorial catalog.')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "There are no children or items in the catalog, since we haven't added anything yet." ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[]\n", "[]\n" ] } ], "source": [ "print(list(catalog.get_children()))\n", "print(list(catalog.get_items()))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We'll now create an Item to represent the image. Check the pydocs to see what you need to supply:" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "An Item is the core granular entity in a STAC, containing the core metadata\n", " that enables any client to search or crawl online catalogs of spatial 'assets' -\n", " satellite imagery, derived data, DEM's, etc.\n", "\n", " Args:\n", " id (str): Provider identifier. Must be unique within the STAC.\n", " geometry (dict): Defines the full footprint of the asset represented by this item,\n", " formatted according to `RFC 7946, section 3.1 (GeoJSON)\n", " `_.\n", " bbox (List[float] or None): Bounding Box of the asset represented by this item using\n", " either 2D or 3D geometries. The length of the array must be 2*n where n is the\n", " number of dimensions. Could also be None in the case of a null geometry.\n", " datetime (datetime or None): Datetime associated with this item. If None,\n", " a start_datetime and end_datetime must be supplied in the properties.\n", " properties (dict): A dictionary of additional metadata for the item.\n", " stac_extensions (List[str]): Optional list of extensions the Item implements.\n", " href (str or None): Optional HREF for this item, which be set as the item's\n", " self link's HREF.\n", " collection (Collection or str): The Collection or Collection ID that this item\n", " belongs to.\n", " extra_fields (dict or None): Extra fields that are part of the top-level JSON properties\n", " of the Item.\n", "\n", " Attributes:\n", " id (str): Provider identifier. Unique within the STAC.\n", " geometry (dict): Defines the full footprint of the asset represented by this item,\n", " formatted according to `RFC 7946, section 3.1 (GeoJSON)\n", " `_.\n", " bbox (List[float] or None): Bounding Box of the asset represented by this item using\n", " either 2D or 3D geometries. The length of the array is 2*n where n is the\n", " number of dimensions. Could also be None in the case of a null geometry.\n", " datetime (datetime or None): Datetime associated with this item. If None,\n", " the start_datetime and end_datetime in the common_metadata\n", " will supply the datetime range of the Item.\n", " properties (dict): A dictionary of additional metadata for the item.\n", " stac_extensions (List[str] or None): Optional list of extensions the Item implements.\n", " collection (Collection or None): Collection that this item is a part of.\n", " links (List[Link]): A list of :class:`~pystac.Link` objects representing\n", " all links associated with this STACObject.\n", " assets (Dict[str, Asset]): Dictionary of asset objects that can be downloaded,\n", " each with a unique key.\n", " collection_id (str or None): The Collection ID that this item belongs to, if any.\n", " extra_fields (dict or None): Extra fields that are part of the top-level JSON properties\n", " of the Item.\n", " \n" ] } ], "source": [ "print(pystac.Item.__doc__)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Using [rasterio](https://rasterio.readthedocs.io/en/stable/), we can pull out the bounding box of the image to use for the image metadata. If the image contained a NoData border, we would ideally pull out the footprint and save it as the geometry; in this case, we're working with a small chip the most likely has no NoData values." ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [], "source": [ "import rasterio\n", "from shapely.geometry import Polygon, mapping\n", "\n", "def get_bbox_and_footprint(raster_uri):\n", " with rasterio.open(raster_uri) as ds:\n", " bounds = ds.bounds\n", " bbox = [bounds.left, bounds.bottom, bounds.right, bounds.top]\n", " footprint = Polygon([\n", " [bounds.left, bounds.bottom],\n", " [bounds.left, bounds.top],\n", " [bounds.right, bounds.top],\n", " [bounds.right, bounds.bottom]\n", " ])\n", " \n", " return (bbox, mapping(footprint))" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[37.6616853489879, 55.73478197572927, 37.66573047610874, 55.73882710285011]\n", "{'type': 'Polygon', 'coordinates': (((37.6616853489879, 55.73478197572927), (37.6616853489879, 55.73882710285011), (37.66573047610874, 55.73882710285011), (37.66573047610874, 55.73478197572927), (37.6616853489879, 55.73478197572927)),)}\n" ] } ], "source": [ "bbox, footprint = get_bbox_and_footprint(img_path)\n", "print(bbox)\n", "print(footprint)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We're also using `datetime.utcnow()` to supply the required datetime property for our Item. Since this is a required property, you might often find yourself making up a time to fill in if you don't know the exact capture time." ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [], "source": [ "from datetime import datetime\n", "\n", "item = pystac.Item(id='local-image',\n", " geometry=footprint,\n", " bbox=bbox,\n", " datetime=datetime.utcnow(),\n", " properties={})" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We haven't added it to a catalog yet, so it's parent isn't set. Once we add it to the catalog, we can see it correctly links to it's parent." ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "item.get_parent() is None" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [], "source": [ "catalog.add_item(item)" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "item.get_parent()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "`describe()` is a useful method on `Catalog` - but be careful when using it on large catalogs, as it will walk the entire tree of the STAC." ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "* \n", " * \n" ] } ], "source": [ "catalog.describe()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Adding Assets\n", "\n", "We've created an Item, but there aren't any assets associated with it. Let's create one:" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "An object that contains a link to data associated with the Item that can be\n", " downloaded or streamed.\n", "\n", " Args:\n", " href (str): Link to the asset object. Relative and absolute links are both allowed.\n", " title (str): Optional displayed title for clients and users.\n", " description (str): A description of the Asset providing additional details, such as\n", " how it was processed or created. CommonMark 0.29 syntax MAY be used for rich\n", " text representation.\n", " media_type (str): Optional description of the media type. Registered Media Types\n", " are preferred. See :class:`~pystac.MediaType` for common media types.\n", " roles ([str]): Optional, Semantic roles (i.e. thumbnail, overview, data, metadata)\n", " of the asset.\n", " properties (dict): Optional, additional properties for this asset. This is used by\n", " extensions as a way to serialize and deserialize properties on asset\n", " object JSON.\n", "\n", " Attributes:\n", " href (str): Link to the asset object. Relative and absolute links are both allowed.\n", " title (str): Optional displayed title for clients and users.\n", " description (str): A description of the Asset providing additional details, such as\n", " how it was processed or created. CommonMark 0.29 syntax MAY be used for rich\n", " text representation.\n", " media_type (str): Optional description of the media type. Registered Media Types\n", " are preferred. See :class:`~pystac.MediaType` for common media types.\n", " properties (dict): Optional, additional properties for this asset. This is used by\n", " extensions as a way to serialize and deserialize properties on asset\n", " object JSON.\n", " owner (Item or None): The Item this asset belongs to.\n", " \n" ] } ], "source": [ "print(pystac.Asset.__doc__)" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "item.add_asset(\n", " key='image', \n", " asset=pystac.Asset(\n", " href=img_path, \n", " media_type=pystac.MediaType.GEOTIFF\n", " )\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "At any time we can call `to_dict()` on STAC objects to see how the STAC JSON is shaping up. Notice the asset is now set:" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{\n", " \"type\": \"Feature\",\n", " \"stac_version\": \"1.0.0-beta.2\",\n", " \"id\": \"local-image\",\n", " \"properties\": {\n", " \"datetime\": \"2020-08-03T03:47:48.786929Z\"\n", " },\n", " \"geometry\": {\n", " \"type\": \"Polygon\",\n", " \"coordinates\": [\n", " [\n", " [\n", " 37.6616853489879,\n", " 55.73478197572927\n", " ],\n", " [\n", " 37.6616853489879,\n", " 55.73882710285011\n", " ],\n", " [\n", " 37.66573047610874,\n", " 55.73882710285011\n", " ],\n", " [\n", " 37.66573047610874,\n", " 55.73478197572927\n", " ],\n", " [\n", " 37.6616853489879,\n", " 55.73478197572927\n", " ]\n", " ]\n", " ]\n", " },\n", " \"links\": [\n", " {\n", " \"rel\": \"root\",\n", " \"href\": null,\n", " \"type\": \"application/json\"\n", " },\n", " {\n", " \"rel\": \"parent\",\n", " \"href\": null,\n", " \"type\": \"application/json\"\n", " }\n", " ],\n", " \"assets\": {\n", " \"image\": {\n", " \"href\": \"/var/folders/sv/zr8j0t4j1f726nhlt3vb8c300000gn/T/tmpt1wuelid/image.tif\",\n", " \"type\": \"image/tiff; application=geotiff\"\n", " }\n", " },\n", " \"bbox\": [\n", " 37.6616853489879,\n", " 55.73478197572927,\n", " 37.66573047610874,\n", " 55.73882710285011\n", " ]\n", "}\n" ] } ], "source": [ "import json\n", "print(json.dumps(item.to_dict(), indent=4))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that the link `href` properties are `null`. This is OK, as we're working with the STAC in memory. Next, we'll talk about writing the catalog out, and how to set those HREFs." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Saving the catalog" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As the JSON above indicates, there's no HREFs set on these in-memory items. PySTAC uses the `self` link on STAC objects to track where the file lives. Because we haven't set them, they evaluate to `None`:" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n", "True\n" ] } ], "source": [ "print(catalog.get_self_href() is None)\n", "print(item.get_self_href() is None)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In order to set them, we can use `normalize_hrefs`. This method will create a normalized set of HREFs for each STAC object in the catalog, according to the [best practices document](https://github.com/radiantearth/stac-spec/blob/v0.8.1/best-practices.md#catalog-layout)'s recommendations on how to lay out a catalog." ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "catalog.normalize_hrefs(os.path.join(tmp_dir.name, 'stac'))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now that we've normalized to a root directory (the temporary directory), we see that the `self` links are set:" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "/var/folders/sv/zr8j0t4j1f726nhlt3vb8c300000gn/T/tmpt1wuelid/stac/catalog.json\n", "/var/folders/sv/zr8j0t4j1f726nhlt3vb8c300000gn/T/tmpt1wuelid/stac/local-image/local-image.json\n" ] } ], "source": [ "print(catalog.get_self_href())\n", "print(item.get_self_href())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can now call `save` on the catalog, which will recursively save all the STAC objects to their respective self HREFs.\n", "\n", "Save requires a `CatalogType` to be set. You can review the [API docs](https://pystac.readthedocs.io/en/stable/api.html#catalogtype) on `CatalogType` to see what each type means (unfortunately `help` doesn't show docstrings for attributes)." ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [], "source": [ "catalog.save(catalog_type=pystac.CatalogType.SELF_CONTAINED)" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "/var/folders/sv/zr8j0t4j1f726nhlt3vb8c300000gn/T/tmpt1wuelid/stac/catalog.json\r\n", "\r\n", "/var/folders/sv/zr8j0t4j1f726nhlt3vb8c300000gn/T/tmpt1wuelid/stac/local-image:\r\n", "local-image.json\r\n" ] } ], "source": [ "!ls {tmp_dir.name}/stac/*" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{\n", " \"id\": \"test-catalog\",\n", " \"stac_version\": \"1.0.0-beta.2\",\n", " \"description\": \"Tutorial catalog.\",\n", " \"links\": [\n", " {\n", " \"rel\": \"root\",\n", " \"href\": \"./catalog.json\",\n", " \"type\": \"application/json\"\n", " },\n", " {\n", " \"rel\": \"item\",\n", " \"href\": \"./local-image/local-image.json\",\n", " \"type\": \"application/json\"\n", " }\n", " ]\n", "}\n" ] } ], "source": [ "with open(catalog.get_self_href()) as f:\n", " print(f.read())" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{\n", " \"type\": \"Feature\",\n", " \"stac_version\": \"1.0.0-beta.2\",\n", " \"id\": \"local-image\",\n", " \"properties\": {\n", " \"datetime\": \"2020-08-03T03:47:48.786929Z\"\n", " },\n", " \"geometry\": {\n", " \"type\": \"Polygon\",\n", " \"coordinates\": [\n", " [\n", " [\n", " 37.6616853489879,\n", " 55.73478197572927\n", " ],\n", " [\n", " 37.6616853489879,\n", " 55.73882710285011\n", " ],\n", " [\n", " 37.66573047610874,\n", " 55.73882710285011\n", " ],\n", " [\n", " 37.66573047610874,\n", " 55.73478197572927\n", " ],\n", " [\n", " 37.6616853489879,\n", " 55.73478197572927\n", " ]\n", " ]\n", " ]\n", " },\n", " \"links\": [\n", " {\n", " \"rel\": \"root\",\n", " \"href\": \"../catalog.json\",\n", " \"type\": \"application/json\"\n", " },\n", " {\n", " \"rel\": \"parent\",\n", " \"href\": \"../catalog.json\",\n", " \"type\": \"application/json\"\n", " }\n", " ],\n", " \"assets\": {\n", " \"image\": {\n", " \"href\": \"/var/folders/sv/zr8j0t4j1f726nhlt3vb8c300000gn/T/tmpt1wuelid/image.tif\",\n", " \"type\": \"image/tiff; application=geotiff\"\n", " }\n", " },\n", " \"bbox\": [\n", " 37.6616853489879,\n", " 55.73478197572927,\n", " 37.66573047610874,\n", " 55.73882710285011\n", " ]\n", "}\n" ] } ], "source": [ "with open(item.get_self_href()) as f:\n", " print(f.read())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As you can see, all links are saved with relative paths. That's because we used `catalog_type=CatalogType.SELF_CONTAINED`. If we save an Absolute Published catalog, we'll see absolute paths:" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [], "source": [ "catalog.save(catalog_type=pystac.CatalogType.ABSOLUTE_PUBLISHED)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now the links included in the STAC item are all absolute:" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{\n", " \"type\": \"Feature\",\n", " \"stac_version\": \"1.0.0-beta.2\",\n", " \"id\": \"local-image\",\n", " \"properties\": {\n", " \"datetime\": \"2020-08-03T03:47:48.786929Z\"\n", " },\n", " \"geometry\": {\n", " \"type\": \"Polygon\",\n", " \"coordinates\": [\n", " [\n", " [\n", " 37.6616853489879,\n", " 55.73478197572927\n", " ],\n", " [\n", " 37.6616853489879,\n", " 55.73882710285011\n", " ],\n", " [\n", " 37.66573047610874,\n", " 55.73882710285011\n", " ],\n", " [\n", " 37.66573047610874,\n", " 55.73478197572927\n", " ],\n", " [\n", " 37.6616853489879,\n", " 55.73478197572927\n", " ]\n", " ]\n", " ]\n", " },\n", " \"links\": [\n", " {\n", " \"rel\": \"self\",\n", " \"href\": \"/var/folders/sv/zr8j0t4j1f726nhlt3vb8c300000gn/T/tmpt1wuelid/stac/local-image/local-image.json\",\n", " \"type\": \"application/json\"\n", " },\n", " {\n", " \"rel\": \"root\",\n", " \"href\": \"/var/folders/sv/zr8j0t4j1f726nhlt3vb8c300000gn/T/tmpt1wuelid/stac/catalog.json\",\n", " \"type\": \"application/json\"\n", " },\n", " {\n", " \"rel\": \"parent\",\n", " \"href\": \"/var/folders/sv/zr8j0t4j1f726nhlt3vb8c300000gn/T/tmpt1wuelid/stac/catalog.json\",\n", " \"type\": \"application/json\"\n", " }\n", " ],\n", " \"assets\": {\n", " \"image\": {\n", " \"href\": \"/var/folders/sv/zr8j0t4j1f726nhlt3vb8c300000gn/T/tmpt1wuelid/image.tif\",\n", " \"type\": \"image/tiff; application=geotiff\"\n", " }\n", " },\n", " \"bbox\": [\n", " 37.6616853489879,\n", " 55.73478197572927,\n", " 37.66573047610874,\n", " 55.73882710285011\n", " ]\n", "}\n" ] } ], "source": [ "with open(item.get_self_href()) as f:\n", " print(f.read())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Notice that the Asset HREF is absolute in both cases. We can make the Asset HREF relative to the STAC Item by using `.make_all_asset_hrefs_relative()`:" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [], "source": [ "catalog.make_all_asset_hrefs_relative()\n", "catalog.save(catalog_type=pystac.CatalogType.SELF_CONTAINED)" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{\n", " \"type\": \"Feature\",\n", " \"stac_version\": \"1.0.0-beta.2\",\n", " \"id\": \"local-image\",\n", " \"properties\": {\n", " \"datetime\": \"2020-08-03T03:47:48.786929Z\"\n", " },\n", " \"geometry\": {\n", " \"type\": \"Polygon\",\n", " \"coordinates\": [\n", " [\n", " [\n", " 37.6616853489879,\n", " 55.73478197572927\n", " ],\n", " [\n", " 37.6616853489879,\n", " 55.73882710285011\n", " ],\n", " [\n", " 37.66573047610874,\n", " 55.73882710285011\n", " ],\n", " [\n", " 37.66573047610874,\n", " 55.73478197572927\n", " ],\n", " [\n", " 37.6616853489879,\n", " 55.73478197572927\n", " ]\n", " ]\n", " ]\n", " },\n", " \"links\": [\n", " {\n", " \"rel\": \"root\",\n", " \"href\": \"../catalog.json\",\n", " \"type\": \"application/json\"\n", " },\n", " {\n", " \"rel\": \"parent\",\n", " \"href\": \"../catalog.json\",\n", " \"type\": \"application/json\"\n", " }\n", " ],\n", " \"assets\": {\n", " \"image\": {\n", " \"href\": \"../../image.tif\",\n", " \"type\": \"image/tiff; application=geotiff\"\n", " }\n", " },\n", " \"bbox\": [\n", " 37.6616853489879,\n", " 55.73478197572927,\n", " 37.66573047610874,\n", " 55.73882710285011\n", " ]\n", "}\n" ] } ], "source": [ "with open(item.get_self_href()) as f:\n", " print(f.read())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Creating an Item that implements the EO extension\n", "\n", "In the code above our item only implemented the core STAC Item specification. With [extensions](https://github.com/radiantearth/stac-spec/tree/v0.9.0/extensions) we can record more information and add additional functionality to the Item. Given that we know this is a World View 3 image that has earth observation data, we can enable the [eo extension](https://github.com/radiantearth/stac-spec/tree/v0.8.1/extensions/eo) to add band information." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To add eo information to an item we'll need to specify some more data. First, let's define the bands of World View 3:" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [], "source": [ "from pystac.extensions.eo import Band\n", "\n", "# From: https://www.spaceimagingme.com/downloads/sensors/datasheets/DG_WorldView3_DS_2014.pdf\n", "\n", "wv3_bands = [Band.create(name='Coastal', description='Coastal: 400 - 450 nm', common_name='coastal'),\n", " Band.create(name='Blue', description='Blue: 450 - 510 nm', common_name='blue'),\n", " Band.create(name='Green', description='Green: 510 - 580 nm', common_name='green'),\n", " Band.create(name='Yellow', description='Yellow: 585 - 625 nm', common_name='yellow'),\n", " Band.create(name='Red', description='Red: 630 - 690 nm', common_name='red'),\n", " Band.create(name='Red Edge', description='Red Edge: 705 - 745 nm', common_name='rededge'),\n", " Band.create(name='Near-IR1', description='Near-IR1: 770 - 895 nm', common_name='nir08'),\n", " Band.create(name='Near-IR2', description='Near-IR2: 860 - 1040 nm', common_name='nir09')]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Notice that we used the `.create` method create new band information." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can now create an Item, enable the eo extension, add the band information and add it to our catalog:" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [], "source": [ "eo_item = pystac.Item(id='local-image-eo',\n", " geometry=footprint,\n", " bbox=bbox,\n", " datetime=datetime.utcnow(),\n", " properties={})\n", "\n", "eo_item.ext.enable(pystac.Extensions.EO)\n", "eo_item.ext.eo.apply(bands=wv3_bands)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "There are also [common metadata](https://github.com/radiantearth/stac-spec/blob/v0.9.0/item-spec/common-metadata.md) fields that we can use to capture additional information about the WorldView 3 imagery:" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [], "source": [ "eo_item.common_metadata.platform = \"Maxar\"\n", "eo_item.common_metadata.instrument=\"WorldView3\"\n", "eo_item.common_metadata.gsd = 0.3" ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 33, "metadata": {}, "output_type": "execute_result" } ], "source": [ "eo_item" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can use the eo extension to add bands to the assets we add to the item:" ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on method set_bands in module pystac.extensions.eo:\n", "\n", "set_bands(bands, asset=None) method of pystac.extensions.eo.EOItemExt instance\n", " Set an Item or an Asset bands.\n", " \n", " If an Asset is supplied, sets the property on the Asset.\n", " Otherwise sets the Item's value.\n", "\n" ] } ], "source": [ "eo_ext = eo_item.ext.eo\n", "help(eo_ext.set_bands)\n", "\n", "#eo_item.add_asset(key='image', asset=)" ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 35, "metadata": {}, "output_type": "execute_result" } ], "source": [ "asset = pystac.Asset(href=img_path, \n", " media_type=pystac.MediaType.GEOTIFF)\n", "eo_ext.set_bands(wv3_bands, asset)\n", "eo_item.add_asset(\"image\", asset)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If we look at the asset's JSON representation, we can see the appropriate band indexes are set:" ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'href': '/var/folders/sv/zr8j0t4j1f726nhlt3vb8c300000gn/T/tmpt1wuelid/image.tif',\n", " 'type': 'image/tiff; application=geotiff',\n", " 'eo:bands': [{'name': 'Coastal',\n", " 'common_name': 'coastal',\n", " 'description': 'Coastal: 400 - 450 nm'},\n", " {'name': 'Blue', 'common_name': 'blue', 'description': 'Blue: 450 - 510 nm'},\n", " {'name': 'Green',\n", " 'common_name': 'green',\n", " 'description': 'Green: 510 - 580 nm'},\n", " {'name': 'Yellow',\n", " 'common_name': 'yellow',\n", " 'description': 'Yellow: 585 - 625 nm'},\n", " {'name': 'Red', 'common_name': 'red', 'description': 'Red: 630 - 690 nm'},\n", " {'name': 'Red Edge',\n", " 'common_name': 'rededge',\n", " 'description': 'Red Edge: 705 - 745 nm'},\n", " {'name': 'Near-IR1',\n", " 'common_name': 'nir08',\n", " 'description': 'Near-IR1: 770 - 895 nm'},\n", " {'name': 'Near-IR2',\n", " 'common_name': 'nir09',\n", " 'description': 'Near-IR2: 860 - 1040 nm'}]}" ] }, "execution_count": 36, "metadata": {}, "output_type": "execute_result" } ], "source": [ "asset.to_dict()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's clear the in-memory catalog, add the EO item, and save to a new STAC:" ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[]" ] }, "execution_count": 37, "metadata": {}, "output_type": "execute_result" } ], "source": [ "catalog.clear_items()\n", "list(catalog.get_items())" ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[]" ] }, "execution_count": 38, "metadata": {}, "output_type": "execute_result" } ], "source": [ "catalog.add_item(eo_item)\n", "list(catalog.get_items())" ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [], "source": [ "catalog.normalize_and_save(root_href=os.path.join(tmp_dir.name, 'stac-eo'), \n", " catalog_type=pystac.CatalogType.SELF_CONTAINED)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now, if we read the catalog from the filesystem, PySTAC recognizes that the item implements eo and so use it's functionality, e.g. getting the bands off the asset:" ] }, { "cell_type": "code", "execution_count": 40, "metadata": {}, "outputs": [], "source": [ "catalog2 = pystac.read_file(os.path.join(tmp_dir.name, 'stac-eo', 'catalog.json'))" ] }, { "cell_type": "code", "execution_count": 41, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[]" ] }, "execution_count": 41, "metadata": {}, "output_type": "execute_result" } ], "source": [ "list(catalog2.get_items())" ] }, { "cell_type": "code", "execution_count": 42, "metadata": {}, "outputs": [], "source": [ "item = next(catalog2.get_all_items())" ] }, { "cell_type": "code", "execution_count": 43, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 43, "metadata": {}, "output_type": "execute_result" } ], "source": [ "item.ext.implements('eo')" ] }, { "cell_type": "code", "execution_count": 44, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[,\n", " ,\n", " ,\n", " ,\n", " ,\n", " ,\n", " ,\n", " ]" ] }, "execution_count": 44, "metadata": {}, "output_type": "execute_result" } ], "source": [ "item.ext.eo.get_bands(item.assets['image'])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Collections\n", "\n", "Collections are a subtype of Catalog that have some additional properties to make them more searchable. They also can define common properties so that items in the collection don't have to duplicate common data for each item. Let's create a collection to hold common properties between two images from the Spacenet 5 challenge.\n", "\n", "First we'll get another image, and it's bbox and footprint:" ] }, { "cell_type": "code", "execution_count": 45, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "('/var/folders/sv/zr8j0t4j1f726nhlt3vb8c300000gn/T/tmpt1wuelid/image.tif',\n", " )" ] }, "execution_count": 45, "metadata": {}, "output_type": "execute_result" } ], "source": [ "url2 = ('http://spacenet-dataset.s3.amazonaws.com/'\n", " 'spacenet/SN5_roads/train/AOI_7_Moscow/MS/'\n", " 'SN5_roads_train_AOI_7_Moscow_MS_chip997.tif')\n", "img_path2 = os.path.join(tmp_dir.name, 'image.tif')\n", "urllib.request.urlretrieve(url2, img_path2)" ] }, { "cell_type": "code", "execution_count": 46, "metadata": {}, "outputs": [], "source": [ "bbox2, footprint2 = get_bbox_and_footprint(img_path2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can take a look at the pydocs for Collection to see what information we need to supply in order to satisfy the spec." ] }, { "cell_type": "code", "execution_count": 47, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "A Collection extends the Catalog spec with additional metadata that helps\n", " enable discovery.\n", "\n", " Args:\n", " id (str): Identifier for the collection. Must be unique within the STAC.\n", " description (str): Detailed multi-line description to fully explain the collection.\n", " `CommonMark 0.28 syntax `_ MAY be used for rich text\n", " representation.\n", " extent (Extent): Spatial and temporal extents that describe the bounds of\n", " all items contained within this Collection.\n", " title (str or None): Optional short descriptive one-line title for the collection.\n", " stac_extensions (List[str]): Optional list of extensions the Collection implements.\n", " href (str or None): Optional HREF for this collection, which be set as the collection's\n", " self link's HREF.\n", " license (str): Collection's license(s) as a `SPDX License identifier\n", " `_, `various`, or `proprietary`. If collection includes\n", " data with multiple different licenses, use `various` and add a link for each.\n", " Defaults to 'proprietary'.\n", " keywords (List[str]): Optional list of keywords describing the collection.\n", " providers (List[Provider]): Optional list of providers of this Collection.\n", " properties (dict): Optional dict of common fields across referenced items.\n", " summaries (dict): An optional map of property summaries,\n", " either a set of values or statistics such as a range.\n", " extra_fields (dict or None): Extra fields that are part of the top-level JSON properties\n", " of the Collection.\n", "\n", " Attributes:\n", " id (str): Identifier for the collection.\n", " description (str): Detailed multi-line description to fully explain the collection.\n", " extent (Extent): Spatial and temporal extents that describe the bounds of\n", " all items contained within this Collection.\n", " title (str or None): Optional short descriptive one-line title for the collection.\n", " stac_extensions (List[str]): Optional list of extensions the Collection implements.\n", " keywords (List[str] or None): Optional list of keywords describing the collection.\n", " providers (List[Provider] or None): Optional list of providers of this Collection.\n", " properties (dict or None): Optional dict of common fields across referenced items.\n", " summaries (dict or None): An optional map of property summaries,\n", " either a set of values or statistics such as a range.\n", " links (List[Link]): A list of :class:`~pystac.Link` objects representing\n", " all links associated with this Collection.\n", " extra_fields (dict or None): Extra fields that are part of the top-level JSON properties\n", " of the Catalog.\n", " \n" ] } ], "source": [ "print(pystac.Collection.__doc__)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Beyond what a Catalog reqiures, a Collection requires a license, and an `Extent` that describes the range of space and time that the items it hold occupy." ] }, { "cell_type": "code", "execution_count": 48, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Describes the spatio-temporal extents of a Collection.\n", "\n", " Args:\n", " spatial (SpatialExtent): Potential spatial extent covered by the collection.\n", " temporal (TemporalExtent): Potential temporal extent covered by the collection.\n", "\n", " Attributes:\n", " spatial (SpatialExtent): Potential spatial extent covered by the collection.\n", " temporal (TemporalExtent): Potential temporal extent covered by the collection.\n", " \n" ] } ], "source": [ "print(pystac.Extent.__doc__)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "An Extent is comprised of a SpatialExtent and a TemporalExtent. These hold one or more bounding boxes and time intervals, respectively, that completely cover the items contained in the collections.\n", "\n", "Let's start with creating two new items - these will be core Items. We can set these items to implement the `eo` extension by specifying them in the `stac_extensions`." ] }, { "cell_type": "code", "execution_count": 49, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 49, "metadata": {}, "output_type": "execute_result" } ], "source": [ "collection_item = pystac.Item(id='local-image-col-1',\n", " geometry=footprint,\n", " bbox=bbox,\n", " datetime=datetime.utcnow(),\n", " properties={},\n", " stac_extensions=[pystac.Extensions.EO])\n", "\n", "collection_item.common_metadata.gsd = 0.3\n", "collection_item.common_metadata.platform = 'Maxar'\n", "collection_item.common_metadata.instruments = ['WorldView3']\n", "\n", "asset = pystac.Asset(href=img_path, \n", " media_type=pystac.MediaType.GEOTIFF)\n", "collection_item.ext.eo.set_bands(wv3_bands, asset)\n", "collection_item.add_asset('image', asset)\n", "\n", "collection_item2 = pystac.Item(id='local-image-col-2',\n", " geometry=footprint2,\n", " bbox=bbox2,\n", " datetime=datetime.utcnow(),\n", " properties={},\n", " stac_extensions=[pystac.Extensions.EO])\n", "\n", "collection_item2.common_metadata.gsd = 0.3\n", "collection_item2.common_metadata.platform = 'Maxar'\n", "collection_item2.common_metadata.instruments = ['WorldView3']\n", "\n", "asset2 = pystac.Asset(href=img_path,\n", " media_type=pystac.MediaType.GEOTIFF)\n", "collection_item2.ext.eo.set_bands([\n", " band for band in wv3_bands if band.name in [\"Red\", \"Green\", \"Blue\"]\n", "], asset2)\n", "\n", "collection_item2.add_asset('image', asset2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can use our two items' metadata to find out what the proper bounds are:" ] }, { "cell_type": "code", "execution_count": 50, "metadata": {}, "outputs": [], "source": [ "from shapely.geometry import shape\n", "\n", "unioned_footprint = shape(footprint).union(shape(footprint2))\n", "collection_bbox = list(unioned_footprint.bounds)\n", "spatial_extent = pystac.SpatialExtent(bboxes=[collection_bbox])" ] }, { "cell_type": "code", "execution_count": 51, "metadata": {}, "outputs": [], "source": [ "collection_interval = sorted([collection_item.datetime, collection_item2.datetime])\n", "temporal_extent = pystac.TemporalExtent(intervals=[collection_interval])" ] }, { "cell_type": "code", "execution_count": 52, "metadata": {}, "outputs": [], "source": [ "collection_extent = pystac.Extent(spatial=spatial_extent, temporal=temporal_extent)" ] }, { "cell_type": "code", "execution_count": 53, "metadata": {}, "outputs": [], "source": [ "collection = pystac.Collection(id='wv3-images',\n", " description='Spacenet 5 images over Moscow',\n", " extent=collection_extent,\n", " license='CC-BY-SA-4.0')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now if we add our items to our Collection, and our Collection to our Catalog, we get the following STAC that can be saved:" ] }, { "cell_type": "code", "execution_count": 54, "metadata": {}, "outputs": [], "source": [ "collection.add_items([collection_item, collection_item2])" ] }, { "cell_type": "code", "execution_count": 55, "metadata": {}, "outputs": [], "source": [ "catalog.clear_items()\n", "catalog.clear_children()\n", "catalog.add_child(collection)" ] }, { "cell_type": "code", "execution_count": 56, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "* \n", " * \n", " * \n", " * \n" ] } ], "source": [ "catalog.describe()" ] }, { "cell_type": "code", "execution_count": 57, "metadata": {}, "outputs": [], "source": [ "catalog.normalize_and_save(root_href=os.path.join(tmp_dir.name, 'stac-collection'), \n", " catalog_type=pystac.CatalogType.SELF_CONTAINED)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Cleanup\n", "\n", "Don't forget to clean up the temporary directory!" ] }, { "cell_type": "code", "execution_count": 58, "metadata": {}, "outputs": [], "source": [ "tmp_dir.cleanup()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Creating a STAC of imagery from Spacenet 5 data" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now, let's take what we've learned and create a Catalog with more data in it.\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Allowing PySTAC to read from AWS S3\n", "\n", "PySTAC aims to be virtually zero-dependency (notwithstanding the why-isn't-this-in-stdlib datetime-util), so it doesn't have the ability to read from or write to anything but the local file system. However, we can hook into PySTAC's IO in the following way. Learn more about how to use STAC_IO in the [documentation on the topic](https://pystac.readthedocs.io/en/latest/concepts.html#using-stac-io):" ] }, { "cell_type": "code", "execution_count": 59, "metadata": {}, "outputs": [], "source": [ "from urllib.parse import urlparse\n", "import boto3\n", "from pystac import STAC_IO\n", "\n", "def my_read_method(uri):\n", " parsed = urlparse(uri)\n", " if parsed.scheme == 's3':\n", " bucket = parsed.netloc\n", " key = parsed.path[1:]\n", " s3 = boto3.resource('s3')\n", " obj = s3.Object(bucket, key)\n", " return obj.get()['Body'].read().decode('utf-8')\n", " else:\n", " return STAC_IO.default_read_text_method(uri)\n", "\n", "def my_write_method(uri, txt):\n", " parsed = urlparse(uri)\n", " if parsed.scheme == 's3':\n", " bucket = parsed.netloc\n", " key = parsed.path[1:]\n", " s3 = boto3.resource(\"s3\")\n", " s3.Object(bucket, key).put(Body=txt)\n", " else:\n", " STAC_IO.default_write_text_method(uri, txt)\n", "\n", "STAC_IO.read_text_method = my_read_method\n", "STAC_IO.write_text_method = my_write_method" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We'll need a utility to list keys for reading the lists of files from S3:" ] }, { "cell_type": "code", "execution_count": 60, "metadata": {}, "outputs": [], "source": [ "# From https://alexwlchan.net/2017/07/listing-s3-keys/\n", "\n", "def get_s3_keys(bucket, prefix):\n", " \"\"\"Generate all the keys in an S3 bucket.\"\"\"\n", " s3 = boto3.client('s3')\n", " kwargs = {'Bucket': bucket, 'Prefix': prefix}\n", " while True:\n", " resp = s3.list_objects_v2(**kwargs)\n", " for obj in resp['Contents']:\n", " yield obj['Key']\n", "\n", " try:\n", " kwargs['ContinuationToken'] = resp['NextContinuationToken']\n", " except KeyError:\n", " break" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's make a STAC of imagery over Moscow as part of the Spacenet 5 challenge. As a first step, we can list out the imagery and extract IDs from each of the chips." ] }, { "cell_type": "code", "execution_count": 61, "metadata": {}, "outputs": [], "source": [ "moscow_training_chip_uris = list(get_s3_keys(bucket='spacenet-dataset', \n", " prefix='spacenet/SN5_roads/train/AOI_7_Moscow/PS-MS'))" ] }, { "cell_type": "code", "execution_count": 62, "metadata": {}, "outputs": [], "source": [ "import re\n", "\n", "chip_id_to_data = {}\n", "\n", "def get_chip_id(uri):\n", " return re.search(r'.*\\_chip(\\d+)\\.', uri).group(1)\n", "\n", "for uri in moscow_training_chip_uris:\n", " chip_id = get_chip_id(uri)\n", " chip_id_to_data[chip_id] = { 'img': 's3://spacenet-dataset/{}'.format(uri) }" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For this tutorial, we'll only take a subset of the data." ] }, { "cell_type": "code", "execution_count": 63, "metadata": {}, "outputs": [], "source": [ "chip_id_to_data = dict(list(chip_id_to_data.items())[:10])" ] }, { "cell_type": "code", "execution_count": 64, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'0': {'img': 's3://spacenet-dataset/spacenet/SN5_roads/train/AOI_7_Moscow/PS-MS/SN5_roads_train_AOI_7_Moscow_PS-MS_chip0.tif'},\n", " '1': {'img': 's3://spacenet-dataset/spacenet/SN5_roads/train/AOI_7_Moscow/PS-MS/SN5_roads_train_AOI_7_Moscow_PS-MS_chip1.tif'},\n", " '10': {'img': 's3://spacenet-dataset/spacenet/SN5_roads/train/AOI_7_Moscow/PS-MS/SN5_roads_train_AOI_7_Moscow_PS-MS_chip10.tif'},\n", " '100': {'img': 's3://spacenet-dataset/spacenet/SN5_roads/train/AOI_7_Moscow/PS-MS/SN5_roads_train_AOI_7_Moscow_PS-MS_chip100.tif'},\n", " '1000': {'img': 's3://spacenet-dataset/spacenet/SN5_roads/train/AOI_7_Moscow/PS-MS/SN5_roads_train_AOI_7_Moscow_PS-MS_chip1000.tif'},\n", " '1001': {'img': 's3://spacenet-dataset/spacenet/SN5_roads/train/AOI_7_Moscow/PS-MS/SN5_roads_train_AOI_7_Moscow_PS-MS_chip1001.tif'},\n", " '1002': {'img': 's3://spacenet-dataset/spacenet/SN5_roads/train/AOI_7_Moscow/PS-MS/SN5_roads_train_AOI_7_Moscow_PS-MS_chip1002.tif'},\n", " '1003': {'img': 's3://spacenet-dataset/spacenet/SN5_roads/train/AOI_7_Moscow/PS-MS/SN5_roads_train_AOI_7_Moscow_PS-MS_chip1003.tif'},\n", " '1004': {'img': 's3://spacenet-dataset/spacenet/SN5_roads/train/AOI_7_Moscow/PS-MS/SN5_roads_train_AOI_7_Moscow_PS-MS_chip1004.tif'},\n", " '1005': {'img': 's3://spacenet-dataset/spacenet/SN5_roads/train/AOI_7_Moscow/PS-MS/SN5_roads_train_AOI_7_Moscow_PS-MS_chip1005.tif'}}" ] }, "execution_count": 64, "metadata": {}, "output_type": "execute_result" } ], "source": [ "chip_id_to_data" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's turn each of those chips into a STAC Item that represents the image." ] }, { "cell_type": "code", "execution_count": 65, "metadata": {}, "outputs": [], "source": [ "chip_id_to_items = {}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We'll create core `Item`s for our imagery, but mark them with the `eo` extension as we did above, and store the `eo` data in a `Collection`.\n", "\n", "Note that the image CRS is in WGS:84 (Lat/Lng). If it wasn't, we'd have to reproject the footprint to WGS:84 in order to be compliant with the spec (which can easily be done with [pyproj](https://github.com/pyproj4/pyproj)).\n", "\n", "Here we're taking advantage of `rasterio`'s ability to read S3 URIs, which only grabs the GeoTIFF metadata and does not pull the whole file down." ] }, { "cell_type": "code", "execution_count": 66, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Processing s3://spacenet-dataset/spacenet/SN5_roads/train/AOI_7_Moscow/PS-MS/SN5_roads_train_AOI_7_Moscow_PS-MS_chip0.tif\n", "Processing s3://spacenet-dataset/spacenet/SN5_roads/train/AOI_7_Moscow/PS-MS/SN5_roads_train_AOI_7_Moscow_PS-MS_chip1.tif\n", "Processing s3://spacenet-dataset/spacenet/SN5_roads/train/AOI_7_Moscow/PS-MS/SN5_roads_train_AOI_7_Moscow_PS-MS_chip10.tif\n", "Processing s3://spacenet-dataset/spacenet/SN5_roads/train/AOI_7_Moscow/PS-MS/SN5_roads_train_AOI_7_Moscow_PS-MS_chip100.tif\n", "Processing s3://spacenet-dataset/spacenet/SN5_roads/train/AOI_7_Moscow/PS-MS/SN5_roads_train_AOI_7_Moscow_PS-MS_chip1000.tif\n", "Processing s3://spacenet-dataset/spacenet/SN5_roads/train/AOI_7_Moscow/PS-MS/SN5_roads_train_AOI_7_Moscow_PS-MS_chip1001.tif\n", "Processing s3://spacenet-dataset/spacenet/SN5_roads/train/AOI_7_Moscow/PS-MS/SN5_roads_train_AOI_7_Moscow_PS-MS_chip1002.tif\n", "Processing s3://spacenet-dataset/spacenet/SN5_roads/train/AOI_7_Moscow/PS-MS/SN5_roads_train_AOI_7_Moscow_PS-MS_chip1003.tif\n", "Processing s3://spacenet-dataset/spacenet/SN5_roads/train/AOI_7_Moscow/PS-MS/SN5_roads_train_AOI_7_Moscow_PS-MS_chip1004.tif\n", "Processing s3://spacenet-dataset/spacenet/SN5_roads/train/AOI_7_Moscow/PS-MS/SN5_roads_train_AOI_7_Moscow_PS-MS_chip1005.tif\n" ] } ], "source": [ "for chip_id in chip_id_to_data:\n", " img_uri = chip_id_to_data[chip_id]['img']\n", " print('Processing {}'.format(img_uri))\n", " bbox, footprint = get_bbox_and_footprint(img_uri)\n", "\n", " item = pystac.Item(id='img_{}'.format(chip_id), \n", " geometry=footprint,\n", " bbox=bbox,\n", " datetime=datetime.utcnow(),\n", " properties={},\n", " stac_extensions=[pystac.Extensions.EO]) \n", " \n", " item.common_metadata.gsd = 0.3\n", " item.common_metadata.platform = 'Maxar'\n", " item.common_metadata.instruments = ['WorldView3']\n", " \n", " item.ext.eo.bands = wv3_bands\n", " asset = pystac.Asset(href=img_uri,\n", " media_type=pystac.MediaType.COG)\n", " item.ext.eo.set_bands(wv3_bands, asset)\n", " item.add_asset(key='ps-ms', asset=asset)\n", " chip_id_to_items[chip_id] = item" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Creating the Collection\n", "\n", "All of these images are over Moscow. In Spacenet 5, we have a couple cities that have imagery; a good way to separate these collections of imagery. We can store all of the common `eo` metadata in the collection." ] }, { "cell_type": "code", "execution_count": 67, "metadata": {}, "outputs": [], "source": [ "from shapely.geometry import (shape, MultiPolygon)\n", "\n", "footprints = list(map(lambda i: shape(i.geometry).envelope, \n", " chip_id_to_items.values()))\n", "collection_bbox = MultiPolygon(footprints).bounds\n", "spatial_extent = pystac.SpatialExtent(bboxes=[collection_bbox])" ] }, { "cell_type": "code", "execution_count": 68, "metadata": {}, "outputs": [], "source": [ "datetimes = sorted(list(map(lambda i: i.datetime,\n", " chip_id_to_items.values())))\n", "temporal_extent = pystac.TemporalExtent(intervals=[[datetimes[0], datetimes[-1]]])" ] }, { "cell_type": "code", "execution_count": 69, "metadata": {}, "outputs": [], "source": [ "collection_extent = pystac.Extent(spatial=spatial_extent, temporal=temporal_extent)" ] }, { "cell_type": "code", "execution_count": 70, "metadata": {}, "outputs": [], "source": [ "collection = pystac.Collection(id='wv3-images',\n", " description='Spacenet 5 images over Moscow',\n", " extent=collection_extent,\n", " license='CC-BY-SA-4.0')" ] }, { "cell_type": "code", "execution_count": 71, "metadata": {}, "outputs": [], "source": [ "collection.add_items(chip_id_to_items.values())" ] }, { "cell_type": "code", "execution_count": 72, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "* \n", " * \n", " * \n", " * \n", " * \n", " * \n", " * \n", " * \n", " * \n", " * \n", " * \n" ] } ], "source": [ "collection.describe()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now, we can create a Catalog and add the collection." ] }, { "cell_type": "code", "execution_count": 73, "metadata": {}, "outputs": [], "source": [ "catalog = pystac.Catalog(id='spacenet5', description='Spacenet 5 Data (Test)')\n", "catalog.add_child(collection)" ] }, { "cell_type": "code", "execution_count": 74, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "* \n", " * \n", " * \n", " * \n", " * \n", " * \n", " * \n", " * \n", " * \n", " * \n", " * \n", " * \n" ] } ], "source": [ "catalog.describe()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Adding items with the label extension to the Spacenet 5 catalog\n", "\n", "We can use the [label extension](https://github.com/radiantearth/stac-spec/tree/v0.8.1/extensions/label) of the STAC spec to represent the training data in our STAC. For this, we need to grab the URIs of the GeoJSON of roads:" ] }, { "cell_type": "code", "execution_count": 75, "metadata": {}, "outputs": [], "source": [ "moscow_training_geojson_uris = list(get_s3_keys(bucket='spacenet-dataset',\n", " prefix='spacenet/SN5_roads/train/AOI_7_Moscow/geojson_roads_speed/'))" ] }, { "cell_type": "code", "execution_count": 76, "metadata": {}, "outputs": [], "source": [ "for uri in moscow_training_geojson_uris:\n", " chip_id = get_chip_id(uri)\n", " if chip_id in chip_id_to_data:\n", " chip_id_to_data[chip_id]['label'] = 's3://spacenet-dataset/{}'.format(uri)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We'll add the items to their own subcatalog; since they don't inherit the Collection's `eo` properties, they shouldn't go in the Collection." ] }, { "cell_type": "code", "execution_count": 77, "metadata": {}, "outputs": [], "source": [ "label_catalog = pystac.Catalog(id='spacenet-data-labels', description='Labels for Spacenet 5')\n", "catalog.add_child(label_catalog)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To see the required fields for the label extension we can check the pydocs on the `apply` method of the extension:" ] }, { "cell_type": "code", "execution_count": 78, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Applies label extension properties to the extended Item.\n", "\n", " Args:\n", " label_description (str): A description of the label, how it was created,\n", " and what it is recommended for\n", " label_type (str): An ENUM of either vector label type or raster label type. Use\n", " one of :class:`~pystac.LabelType`.\n", " label_properties (list or None): These are the names of the property field(s) in each\n", " Feature of the label asset's FeatureCollection that contains the classes\n", " (keywords from label:classes if the property defines classes).\n", " If labels are rasters, this should be None.\n", " label_classes (List[LabelClass]): Optional, but reqiured if ussing categorical data.\n", " A list of LabelClasses defining the list of possible class names for each\n", " label:properties. (e.g., tree, building, car, hippo)\n", " label_tasks (List[str]): Recommended to be a subset of 'regression', 'classification',\n", " 'detection', or 'segmentation', but may be an arbitrary value.\n", " label_methods: Recommended to be a subset of 'automated' or 'manual',\n", " but may be an arbitrary value.\n", " label_overviews (List[LabelOverview]): Optional list of LabelOverview classes\n", " that store counts (for classification-type data) or summary statistics (for\n", " continuous numerical/regression data).\n", " \n" ] } ], "source": [ "from pystac.extensions import label\n", "print(label.LabelItemExt.apply.__doc__)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This loop creates our label items and associates each to the appropriate source image Item." ] }, { "cell_type": "code", "execution_count": 79, "metadata": {}, "outputs": [], "source": [ "for chip_id in chip_id_to_data:\n", " img_item = collection.get_item('img_{}'.format(chip_id))\n", " label_uri = chip_id_to_data[chip_id]['label']\n", " \n", " label_item = pystac.Item(id='label_{}'.format(chip_id),\n", " geometry=img_item.geometry,\n", " bbox=img_item.bbox,\n", " datetime=datetime.utcnow(),\n", " properties={},\n", " stac_extensions=[pystac.Extensions.LABEL])\n", " label_item.ext.label.apply(label_description=\"SpaceNet 5 Road labels\",\n", " label_type=label.LabelType.VECTOR,\n", " label_tasks=['segmentation', 'regression'])\n", " label_item.ext.label.add_source(img_item)\n", " label_item.ext.label.add_geojson_labels(label_uri)\n", " \n", " label_catalog.add_item(label_item)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now we have a STAC of training data!" ] }, { "cell_type": "code", "execution_count": 80, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "* \n", " * \n", " * \n", " * \n", " * \n", " * \n", " * \n", " * \n", " * \n", " * \n", " * \n", " * \n", " * \n", " * \n", " * \n", " * \n", " * \n", " * \n", " * \n", " * \n", " * \n", " * \n", " * \n" ] } ], "source": [ "catalog.describe()" ] }, { "cell_type": "code", "execution_count": 81, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'type': 'Feature',\n", " 'stac_version': '1.0.0-beta.2',\n", " 'id': 'label_1',\n", " 'properties': {'label:description': 'SpaceNet 5 Road labels',\n", " 'label:type': 'vector',\n", " 'label:properties': None,\n", " 'label:tasks': ['segmentation', 'regression'],\n", " 'datetime': '2020-08-03T03:47:56.599629Z'},\n", " 'geometry': {'type': 'Polygon',\n", " 'coordinates': (((37.68191035616281, 55.73478210707574),\n", " (37.68191035616281, 55.73882710285011),\n", " (37.68595535193718, 55.73882710285011),\n", " (37.68595535193718, 55.73478210707574),\n", " (37.68191035616281, 55.73478210707574)),)},\n", " 'links': [{'rel': 'source', 'href': None, 'type': 'application/json'},\n", " {'rel': 'root', 'href': None, 'type': 'application/json'},\n", " {'rel': 'parent', 'href': None, 'type': 'application/json'}],\n", " 'assets': {'labels': {'href': 's3://spacenet-dataset/spacenet/SN5_roads/train/AOI_7_Moscow/geojson_roads_speed/SN5_roads_train_AOI_7_Moscow_geojson_roads_speed_chip1.geojson',\n", " 'type': 'application/geo+json'}},\n", " 'bbox': [37.68191035616281,\n", " 55.73478210707574,\n", " 37.68595535193718,\n", " 55.73882710285011],\n", " 'stac_extensions': ['label']}" ] }, "execution_count": 81, "metadata": {}, "output_type": "execute_result" } ], "source": [ "label_item = catalog.get_child('spacenet-data-labels').get_item('label_1')\n", "label_item.to_dict()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "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.6.5" } }, "nbformat": 4, "nbformat_minor": 2 }