How to create STAC Catalogs#

STAC Community Sprint, Arlington, November 7th 2019#

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 in Arlington, VA in November 2019, updated to work with current PySTAC.

This tutorial will require the boto3, rasterio, and shapely libraries:

[1]:
%pip install boto3 rasterio shapely pystac --quiet
Note: you may need to restart the kernel to use updated packages.

We can import pystac and access most of the functionality we need with the single import:

[2]:
import pystac

Creating a catalog from a local file#

To give us some material to work with, lets download a single image from the Spacenet 5 challenge. We’ll use a temporary directory to save off our single-item STAC.

[3]:
import os
import urllib.request
from tempfile import TemporaryDirectory

tmp_dir = TemporaryDirectory()
img_path = os.path.join(tmp_dir.name, "image.tif")
[4]:
url = (
    "https://spacenet-dataset.s3.amazonaws.com/"
    "spacenet/SN5_roads/train/AOI_7_Moscow/MS/"
    "SN5_roads_train_AOI_7_Moscow_MS_chip996.tif"
)
urllib.request.urlretrieve(url, img_path)
[4]:
('/tmp/tmpdsdpun_y/image.tif', <http.client.HTTPMessage at 0x7fc4f8339ad0>)

We want to create a Catalog. Let’s check the docs for Catalog to see what information we’ll need.

[5]:
?pystac.Catalog
Init signature:
pystac.Catalog(
    id: 'str',
    description: 'str',
    title: 'Optional[str]' = None,
    stac_extensions: 'Optional[List[str]]' = None,
    extra_fields: 'Optional[Dict[str, Any]]' = None,
    href: 'Optional[str]' = None,
    catalog_type: 'CatalogType' = ABSOLUTE_PUBLISHED,
)
Docstring:
A PySTAC Catalog represents a STAC catalog in memory.

A Catalog is a :class:`~pystac.STACObject` that may contain children,
which are instances of :class:`~pystac.Catalog` or :class:`~pystac.Collection`,
as well as :class:`~pystac.Item` s.

Args:
    id : Identifier for the catalog. Must be unique within the STAC.
    description : Detailed multi-line description to fully explain the catalog.
        `CommonMark 0.29 syntax <https://commonmark.org/>`_ MAY be used for rich
        text representation.
    title : Optional short descriptive one-line title for the catalog.
    stac_extensions : Optional list of extensions the Catalog implements.
    href : Optional HREF for this catalog, which be set as the
        catalog's self link's HREF.
    catalog_type : Optional catalog type for this catalog. Must
        be one of the values in :class:`~pystac.CatalogType`.
File:           ~/pystac/pystac/catalog.py
Type:           ABCMeta
Subclasses:     Collection

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.

[6]:
catalog = pystac.Catalog(id="test-catalog", description="Tutorial catalog.")

There are no children or items in the catalog, since we haven’t added anything yet.

[7]:
print(list(catalog.get_children()))
print(list(catalog.get_items()))
[]
[]

We’ll now create an Item to represent the image. Check the pydocs to see what you need to supply:

[8]:
?pystac.Item
Init signature:
pystac.Item(
    id: 'str',
    geometry: 'Optional[Dict[str, Any]]',
    bbox: 'Optional[List[float]]',
    datetime: 'Optional[Datetime]',
    properties: 'Dict[str, Any]',
    start_datetime: 'Optional[Datetime]' = None,
    end_datetime: 'Optional[Datetime]' = None,
    stac_extensions: 'Optional[List[str]]' = None,
    href: 'Optional[str]' = None,
    collection: 'Optional[Union[str, Collection]]' = None,
    extra_fields: 'Optional[Dict[str, Any]]' = None,
    assets: 'Optional[Dict[str, Asset]]' = None,
)
Docstring:
An Item is the core granular entity in a STAC, containing the core metadata
that enables any client to search or crawl online catalogs of spatial 'assets' -
satellite imagery, derived data, DEM's, etc.

Args:
    id : Provider identifier. Must be unique within the STAC.
    geometry : Defines the full footprint of the asset represented by this
        item, formatted according to
        `RFC 7946, section 3.1 (GeoJSON) <https://tools.ietf.org/html/rfc7946>`_.
    bbox :  Bounding Box of the asset represented by this item
        using either 2D or 3D geometries. The length of the array must be 2*n
        where n is the number of dimensions. Could also be None in the case of a
        null geometry.
    datetime : datetime associated with this item. If None,
        a start_datetime and end_datetime must be supplied.
    properties : A dictionary of additional metadata for the item.
    start_datetime : Optional start datetime, part of common metadata. This value
        will override any `start_datetime` key in properties.
    end_datetime : Optional end datetime, part of common metadata. This value
        will override any `end_datetime` key in properties.
    stac_extensions : Optional list of extensions the Item implements.
    href : Optional HREF for this item, which be set as the item's
        self link's HREF.
    collection : The Collection or Collection ID that this item
        belongs to.
    extra_fields : Extra fields that are part of the top-level JSON
        properties of the Item.
    assets : A dictionary mapping string keys to :class:`~pystac.Asset` objects. All
        :class:`~pystac.Asset` values in the dictionary will have their
        :attr:`~pystac.Asset.owner` attribute set to the created Item.
File:           ~/pystac/pystac/item.py
Type:           ABCMeta
Subclasses:

Using rasterio, 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 that most likely has no NoData values.

[9]:
import rasterio
from shapely.geometry import Polygon, mapping


def get_bbox_and_footprint(raster_uri):
    with rasterio.open(raster_uri) as ds:
        bounds = ds.bounds
        bbox = [bounds.left, bounds.bottom, bounds.right, bounds.top]
        footprint = Polygon(
            [
                [bounds.left, bounds.bottom],
                [bounds.left, bounds.top],
                [bounds.right, bounds.top],
                [bounds.right, bounds.bottom],
            ]
        )

        return (bbox, mapping(footprint))
[10]:
bbox, footprint = get_bbox_and_footprint(img_path)
print(bbox)
print(footprint)
[37.6616853489879, 55.73478197572927, 37.66573047610874, 55.73882710285011]
{'type': 'Polygon', 'coordinates': (((37.6616853489879, 55.73478197572927), (37.6616853489879, 55.73882710285011), (37.66573047610874, 55.73882710285011), (37.66573047610874, 55.73478197572927), (37.6616853489879, 55.73478197572927)),)}

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.

[11]:
from datetime import datetime

item = pystac.Item(
    id="local-image",
    geometry=footprint,
    bbox=bbox,
    datetime=datetime.utcnow(),
    properties={},
)

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.

[12]:
assert item.get_parent() is None
[13]:
catalog.add_item(item)
[13]:
[14]:
item.get_parent()
[14]:

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.

[15]:
catalog.describe()
* <Catalog id=test-catalog>
  * <Item id=local-image>

Adding Assets#

We’ve created an Item, but there aren’t any assets associated with it. Let’s create one:

[16]:
?pystac.Asset
Init signature:
pystac.Asset(
    href: 'str',
    title: 'Optional[str]' = None,
    description: 'Optional[str]' = None,
    media_type: 'Optional[str]' = None,
    roles: 'Optional[List[str]]' = None,
    extra_fields: 'Optional[Dict[str, Any]]' = None,
) -> 'None'
Docstring:
An object that contains a link to data associated with an Item or Collection that
can be downloaded or streamed.

Args:
    href : Link to the asset object. Relative and absolute links are both
        allowed.
    title : Optional displayed title for clients and users.
    description : A description of the Asset providing additional details,
        such as how it was processed or created. CommonMark 0.29 syntax MAY be used
        for rich text representation.
    media_type : Optional description of the media type. Registered Media Types
        are preferred. See :class:`~pystac.MediaType` for common media types.
    roles : Optional, Semantic roles (i.e. thumbnail, overview,
        data, metadata) of the asset.
    extra_fields : Optional, additional fields for this asset. This is used
        by extensions as a way to serialize and deserialize properties on asset
        object JSON.
File:           ~/pystac/pystac/asset.py
Type:           type
Subclasses:
[17]:
item.add_asset(
    key="image", asset=pystac.Asset(href=img_path, media_type=pystac.MediaType.GEOTIFF)
)

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:

[18]:
import json

print(json.dumps(item.to_dict(), indent=4))
{
    "type": "Feature",
    "stac_version": "1.0.0",
    "id": "local-image",
    "properties": {
        "datetime": "2023-10-12T15:35:17.290343Z"
    },
    "geometry": {
        "type": "Polygon",
        "coordinates": [
            [
                [
                    37.6616853489879,
                    55.73478197572927
                ],
                [
                    37.6616853489879,
                    55.73882710285011
                ],
                [
                    37.66573047610874,
                    55.73882710285011
                ],
                [
                    37.66573047610874,
                    55.73478197572927
                ],
                [
                    37.6616853489879,
                    55.73478197572927
                ]
            ]
        ]
    },
    "links": [
        {
            "rel": "root",
            "href": null,
            "type": "application/json"
        },
        {
            "rel": "parent",
            "href": null,
            "type": "application/json"
        }
    ],
    "assets": {
        "image": {
            "href": "/tmp/tmpdsdpun_y/image.tif",
            "type": "image/tiff; application=geotiff"
        }
    },
    "bbox": [
        37.6616853489879,
        55.73478197572927,
        37.66573047610874,
        55.73882710285011
    ],
    "stac_extensions": []
}

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.

Saving the catalog#

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:

[19]:
print(catalog.get_self_href() is None)
print(item.get_self_href() is None)
True
True

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’s recommendations on how to lay out a catalog.

[20]:
catalog.normalize_hrefs(os.path.join(tmp_dir.name, "stac"))

Now that we’ve normalized to a root directory (the temporary directory), we see that the self links are set:

[21]:
print(catalog.get_self_href())
print(item.get_self_href())
/tmp/tmpdsdpun_y/stac/catalog.json
/tmp/tmpdsdpun_y/stac/local-image/local-image.json

We can now call save on the catalog, which will recursively save all the STAC objects to their respective self HREFs.

Save requires a CatalogType to be set. You can review the API docs on CatalogType to see what each type means (unfortunately help doesn’t show docstrings for attributes).

[22]:
catalog.save(catalog_type=pystac.CatalogType.SELF_CONTAINED)
[23]:
!ls {tmp_dir.name}/stac/*
/tmp/tmpdsdpun_y/stac/catalog.json

/tmp/tmpdsdpun_y/stac/local-image:
local-image.json
[24]:
with open(catalog.self_href) as f:
    print(f.read())
{
  "type": "Catalog",
  "id": "test-catalog",
  "stac_version": "1.0.0",
  "description": "Tutorial catalog.",
  "links": [
    {
      "rel": "root",
      "href": "./catalog.json",
      "type": "application/json"
    },
    {
      "rel": "item",
      "href": "./local-image/local-image.json",
      "type": "application/json"
    }
  ]
}
[25]:
with open(item.self_href) as f:
    print(f.read())
{
  "type": "Feature",
  "stac_version": "1.0.0",
  "id": "local-image",
  "properties": {
    "datetime": "2023-10-12T15:35:17.290343Z"
  },
  "geometry": {
    "type": "Polygon",
    "coordinates": [
      [
        [
          37.6616853489879,
          55.73478197572927
        ],
        [
          37.6616853489879,
          55.73882710285011
        ],
        [
          37.66573047610874,
          55.73882710285011
        ],
        [
          37.66573047610874,
          55.73478197572927
        ],
        [
          37.6616853489879,
          55.73478197572927
        ]
      ]
    ]
  },
  "links": [
    {
      "rel": "root",
      "href": "../catalog.json",
      "type": "application/json"
    },
    {
      "rel": "parent",
      "href": "../catalog.json",
      "type": "application/json"
    }
  ],
  "assets": {
    "image": {
      "href": "/tmp/tmpdsdpun_y/image.tif",
      "type": "image/tiff; application=geotiff"
    }
  },
  "bbox": [
    37.6616853489879,
    55.73478197572927,
    37.66573047610874,
    55.73882710285011
  ],
  "stac_extensions": []
}

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:

[26]:
catalog.save(catalog_type=pystac.CatalogType.ABSOLUTE_PUBLISHED)

Now the links included in the STAC item are all absolute:

[27]:
with open(item.get_self_href()) as f:
    print(f.read())
{
  "type": "Feature",
  "stac_version": "1.0.0",
  "id": "local-image",
  "properties": {
    "datetime": "2023-10-12T15:35:17.290343Z"
  },
  "geometry": {
    "type": "Polygon",
    "coordinates": [
      [
        [
          37.6616853489879,
          55.73478197572927
        ],
        [
          37.6616853489879,
          55.73882710285011
        ],
        [
          37.66573047610874,
          55.73882710285011
        ],
        [
          37.66573047610874,
          55.73478197572927
        ],
        [
          37.6616853489879,
          55.73478197572927
        ]
      ]
    ]
  },
  "links": [
    {
      "rel": "root",
      "href": "/tmp/tmpdsdpun_y/stac/catalog.json",
      "type": "application/json"
    },
    {
      "rel": "parent",
      "href": "/tmp/tmpdsdpun_y/stac/catalog.json",
      "type": "application/json"
    },
    {
      "rel": "self",
      "href": "/tmp/tmpdsdpun_y/stac/local-image/local-image.json",
      "type": "application/json"
    }
  ],
  "assets": {
    "image": {
      "href": "/tmp/tmpdsdpun_y/image.tif",
      "type": "image/tiff; application=geotiff"
    }
  },
  "bbox": [
    37.6616853489879,
    55.73478197572927,
    37.66573047610874,
    55.73882710285011
  ],
  "stac_extensions": []
}

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():

[28]:
catalog.make_all_asset_hrefs_relative()
catalog.save(catalog_type=pystac.CatalogType.SELF_CONTAINED)
[29]:
with open(item.get_self_href()) as f:
    print(f.read())
{
  "type": "Feature",
  "stac_version": "1.0.0",
  "id": "local-image",
  "properties": {
    "datetime": "2023-10-12T15:35:17.290343Z"
  },
  "geometry": {
    "type": "Polygon",
    "coordinates": [
      [
        [
          37.6616853489879,
          55.73478197572927
        ],
        [
          37.6616853489879,
          55.73882710285011
        ],
        [
          37.66573047610874,
          55.73882710285011
        ],
        [
          37.66573047610874,
          55.73478197572927
        ],
        [
          37.6616853489879,
          55.73478197572927
        ]
      ]
    ]
  },
  "links": [
    {
      "rel": "root",
      "href": "../catalog.json",
      "type": "application/json"
    },
    {
      "rel": "parent",
      "href": "../catalog.json",
      "type": "application/json"
    }
  ],
  "assets": {
    "image": {
      "href": "../../image.tif",
      "type": "image/tiff; application=geotiff"
    }
  },
  "bbox": [
    37.6616853489879,
    55.73478197572927,
    37.66573047610874,
    55.73882710285011
  ],
  "stac_extensions": []
}

Creating an Item that implements the EO extension#

In the code above our item only implemented the core STAC Item specification. With 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 to add band information.

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:

[30]:
from pystac.extensions.eo import Band

# From: https://www.spaceimagingme.com/downloads/sensors/datasheets/DG_WorldView3_DS_2014.pdf

wv3_bands = [
    Band.create(
        name="Coastal", description="Coastal: 400 - 450 nm", common_name="coastal"
    ),
    Band.create(name="Blue", description="Blue: 450 - 510 nm", common_name="blue"),
    Band.create(name="Green", description="Green: 510 - 580 nm", common_name="green"),
    Band.create(
        name="Yellow", description="Yellow: 585 - 625 nm", common_name="yellow"
    ),
    Band.create(name="Red", description="Red: 630 - 690 nm", common_name="red"),
    Band.create(
        name="Red Edge", description="Red Edge: 705 - 745 nm", common_name="rededge"
    ),
    Band.create(
        name="Near-IR1", description="Near-IR1: 770 - 895 nm", common_name="nir08"
    ),
    Band.create(
        name="Near-IR2", description="Near-IR2: 860 - 1040 nm", common_name="nir09"
    ),
]

Notice that we used the .create method create new band information.

We can now create an Item, enable the eo extension, add the band information and add it to our catalog:

[31]:
eo_item = pystac.Item(
    id="local-image-eo",
    geometry=footprint,
    bbox=bbox,
    datetime=datetime.utcnow(),
    properties={},
)
eo_item.ext.add("eo")
eo_item.ext.eo.bands = wv3_bands

There are also common metadata fields that we can use to capture additional information about the WorldView 3 imagery:

[32]:
eo_item.common_metadata.platform = "Maxar"
eo_item.common_metadata.instruments = ["WorldView3"]
eo_item.common_metadata.gsd = 0.3
[33]:
eo_item
[33]:

We can use the eo extension to add bands to the assets we add to the item:

[34]:
asset = pystac.Asset(href=img_path, media_type=pystac.MediaType.GEOTIFF)
eo_item.add_asset("image", asset)
asset.ext.eo.bands = wv3_bands

If we look at the asset, we can see the appropriate band indexes are set:

[35]:
asset
[35]:

Let’s clear the in-memory catalog, add the EO item, and save to a new STAC:

[36]:
catalog.clear_items()
list(catalog.get_items())
[36]:
[]
[37]:
catalog.add_item(eo_item)
list(catalog.get_items())
[37]:
[<Item id=local-image-eo>]
[38]:
catalog.normalize_and_save(
    root_href=os.path.join(tmp_dir.name, "stac-eo"),
    catalog_type=pystac.CatalogType.SELF_CONTAINED,
)

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:

[39]:
catalog2 = pystac.read_file(os.path.join(tmp_dir.name, "stac-eo", "catalog.json"))
[40]:
assert isinstance(catalog2, pystac.Catalog)
list(catalog2.get_items())
[40]:
[<Item id=local-image-eo>]
[41]:
item: pystac.Item = next(catalog2.get_items(recursive=True))
[42]:
assert item.ext.has("eo")
[43]:
item.assets["image"].ext.eo.bands
[43]:
[<Band name=Coastal>,
 <Band name=Blue>,
 <Band name=Green>,
 <Band name=Yellow>,
 <Band name=Red>,
 <Band name=Red Edge>,
 <Band name=Near-IR1>,
 <Band name=Near-IR2>]

Collections#

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.

First we’ll get another image, and it’s bbox and footprint:

[44]:
url2 = (
    "https://spacenet-dataset.s3.amazonaws.com/"
    "spacenet/SN5_roads/train/AOI_7_Moscow/MS/"
    "SN5_roads_train_AOI_7_Moscow_MS_chip997.tif"
)
img_path2 = os.path.join(tmp_dir.name, "image.tif")
urllib.request.urlretrieve(url2, img_path2)
[44]:
('/tmp/tmpdsdpun_y/image.tif', <http.client.HTTPMessage at 0x7fc4aa12fed0>)
[45]:
bbox2, footprint2 = get_bbox_and_footprint(img_path2)

We can take a look at the pydocs for Collection to see what information we need to supply in order to satisfy the spec.

[46]:
?pystac.Collection
Init signature:
pystac.Collection(
    id: 'str',
    description: 'str',
    extent: 'Extent',
    title: 'Optional[str]' = None,
    stac_extensions: 'Optional[List[str]]' = None,
    href: 'Optional[str]' = None,
    extra_fields: 'Optional[Dict[str, Any]]' = None,
    catalog_type: 'Optional[CatalogType]' = None,
    license: 'str' = 'proprietary',
    keywords: 'Optional[List[str]]' = None,
    providers: 'Optional[List[Provider]]' = None,
    summaries: 'Optional[Summaries]' = None,
    assets: 'Optional[Dict[str, Asset]]' = None,
)
Docstring:
A Collection extends the Catalog spec with additional metadata that helps
enable discovery.

Args:
    id : Identifier for the collection. Must be unique within the STAC.
    description : Detailed multi-line description to fully explain the
        collection. `CommonMark 0.29 syntax <https://commonmark.org/>`_ MAY
        be used for rich text representation.
    extent : Spatial and temporal extents that describe the bounds of
        all items contained within this Collection.
    title : Optional short descriptive one-line title for the
        collection.
    stac_extensions : Optional list of extensions the Collection
        implements.
    href : Optional HREF for this collection, which be set as the
        collection's self link's HREF.
    catalog_type : Optional catalog type for this catalog. Must
        be one of the values in :class`~pystac.CatalogType`.
    license :  Collection's license(s) as a
        `SPDX License identifier <https://spdx.org/licenses/>`_,
        `various`, or `proprietary`. If collection includes
        data with multiple different licenses, use `various` and add a link for
        each. Defaults to 'proprietary'.
    keywords : Optional list of keywords describing the collection.
    providers : Optional list of providers of this Collection.
    summaries : An optional map of property summaries,
        either a set of values or statistics such as a range.
    extra_fields : Extra fields that are part of the top-level
        JSON properties of the Collection.
    assets : A dictionary mapping string keys to :class:`~pystac.Asset` objects. All
        :class:`~pystac.Asset` values in the dictionary will have their
        :attr:`~pystac.Asset.owner` attribute set to the created Collection.
File:           ~/pystac/pystac/collection.py
Type:           ABCMeta
Subclasses:

Beyond what a Catalog requires, a Collection requires a license, and an Extent that describes the range of space and time that the items it hold occupy.

[47]:
?pystac.Extent
Init signature:
pystac.Extent(
    spatial: 'SpatialExtent',
    temporal: 'TemporalExtent',
    extra_fields: 'Optional[Dict[str, Any]]' = None,
)
Docstring:
Describes the spatiotemporal extents of a Collection.

Args:
    spatial : Potential spatial extent covered by the collection.
    temporal : Potential temporal extent covered by the collection.
    extra_fields : Dictionary containing additional top-level fields defined on the
        Extent object.
File:           ~/pystac/pystac/collection.py
Type:           type
Subclasses:

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.

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.

[48]:
collection_item = pystac.Item(
    id="local-image-col-1",
    geometry=footprint,
    bbox=bbox,
    datetime=datetime.utcnow(),
    properties={},
)

collection_item.common_metadata.gsd = 0.3
collection_item.common_metadata.platform = "Maxar"
collection_item.common_metadata.instruments = ["WorldView3"]

asset = pystac.Asset(href=img_path, media_type=pystac.MediaType.GEOTIFF)
collection_item.add_asset("image", asset)
asset.ext.add("eo")
asset.ext.eo.bands = wv3_bands

collection_item2 = pystac.Item(
    id="local-image-col-2",
    geometry=footprint2,
    bbox=bbox2,
    datetime=datetime.utcnow(),
    properties={},
)

collection_item2.common_metadata.gsd = 0.3
collection_item2.common_metadata.platform = "Maxar"
collection_item2.common_metadata.instruments = ["WorldView3"]

asset2 = pystac.Asset(href=img_path, media_type=pystac.MediaType.GEOTIFF)
collection_item2.add_asset("image", asset2)
asset2.ext.add("eo")
asset2.ext.eo.bands = [
    band for band in wv3_bands if band.name in ["Red", "Green", "Blue"]
]

We can use our two items’ metadata to find out what the proper bounds are:

[49]:
from shapely.geometry import shape

unioned_footprint = shape(footprint).union(shape(footprint2))
collection_bbox = list(unioned_footprint.bounds)
spatial_extent = pystac.SpatialExtent(bboxes=[collection_bbox])
[50]:
collection_interval = sorted([collection_item.datetime, collection_item2.datetime])
temporal_extent = pystac.TemporalExtent(intervals=[collection_interval])
[51]:
collection_extent = pystac.Extent(spatial=spatial_extent, temporal=temporal_extent)
[52]:
collection = pystac.Collection(
    id="wv3-images",
    description="Spacenet 5 images over Moscow",
    extent=collection_extent,
    license="CC-BY-SA-4.0",
)

Now if we add our items to our Collection, and our Collection to our Catalog, we get the following STAC that can be saved:

[53]:
collection.add_items([collection_item, collection_item2])
[53]:
[<Link rel=item target=<Item id=local-image-col-1>>,
 <Link rel=item target=<Item id=local-image-col-2>>]
[54]:
catalog.clear_items()
catalog.clear_children()
catalog.add_child(collection)
[54]:
[55]:
catalog.describe()
* <Catalog id=test-catalog>
    * <Collection id=wv3-images>
      * <Item id=local-image-col-1>
      * <Item id=local-image-col-2>
[56]:
catalog.normalize_and_save(
    root_href=os.path.join(tmp_dir.name, "stac-collection"),
    catalog_type=pystac.CatalogType.SELF_CONTAINED,
)

Cleanup#

Don’t forget to clean up the temporary directory!

[57]:
tmp_dir.cleanup()

Creating a STAC of imagery from Spacenet 5 data#

Now, let’s take what we’ve learned and create a Catalog with more data in it.

Allowing PySTAC to read from AWS S3#

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 customize I/O in STAC from the documentation:

[58]:
from typing import Any, Union
from urllib.parse import urlparse

import boto3

from pystac import Link
from pystac.stac_io import DefaultStacIO


class CustomStacIO(DefaultStacIO):
    def __init__(self):
        self.s3 = boto3.resource("s3")
        super().__init__()

    def read_text(self, source: Union[str, Link], *args: Any, **kwargs: Any) -> str:
        parsed = urlparse(source)
        if parsed.scheme == "s3":
            bucket = parsed.netloc
            key = parsed.path[1:]

            obj = self.s3.Object(bucket, key)
            return obj.get()["Body"].read().decode("utf-8")
        else:
            return super().read_text(source, *args, **kwargs)

    def write_text(
        self, dest: Union[str, Link], txt: str, *args: Any, **kwargs: Any
    ) -> None:
        parsed = urlparse(dest)
        if parsed.scheme == "s3":
            bucket = parsed.netloc
            key = parsed.path[1:]
            self.s3.Object(bucket, key).put(Body=txt, ContentEncoding="utf-8")
        else:
            super().write_text(dest, txt, *args, **kwargs)

We’ll need a utility to list keys for reading the lists of files from S3:

[59]:
# From https://alexwlchan.net/2017/07/listing-s3-keys/
from botocore import UNSIGNED
from botocore.config import Config


def get_s3_keys(bucket, prefix):
    """Generate all the keys in an S3 bucket."""
    s3 = boto3.client("s3", config=Config(signature_version=UNSIGNED))
    kwargs = {"Bucket": bucket, "Prefix": prefix}
    while True:
        resp = s3.list_objects_v2(**kwargs)
        for obj in resp["Contents"]:
            yield obj["Key"]

        try:
            kwargs["ContinuationToken"] = resp["NextContinuationToken"]
        except KeyError:
            break

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.

[60]:
moscow_training_chip_uris = list(
    get_s3_keys(
        bucket="spacenet-dataset", prefix="spacenet/SN5_roads/train/AOI_7_Moscow/PS-MS/"
    )
)
[61]:
import re

chip_id_to_data = {}


def get_chip_id(uri):
    return re.search(r".*\_chip(\d+)\.", uri).group(1)


for uri in moscow_training_chip_uris:
    chip_id = get_chip_id(uri)
    chip_id_to_data[chip_id] = {"img": "s3://spacenet-dataset/{}".format(uri)}

For this tutorial, we’ll only take a subset of the data.

[62]:
chip_id_to_data = dict(list(chip_id_to_data.items())[:10])
[63]:
chip_id_to_data
[63]:
{'0': {'img': 's3://spacenet-dataset/spacenet/SN5_roads/train/AOI_7_Moscow/PS-MS/SN5_roads_train_AOI_7_Moscow_PS-MS_chip0.tif'},
 '1': {'img': 's3://spacenet-dataset/spacenet/SN5_roads/train/AOI_7_Moscow/PS-MS/SN5_roads_train_AOI_7_Moscow_PS-MS_chip1.tif'},
 '10': {'img': 's3://spacenet-dataset/spacenet/SN5_roads/train/AOI_7_Moscow/PS-MS/SN5_roads_train_AOI_7_Moscow_PS-MS_chip10.tif'},
 '100': {'img': 's3://spacenet-dataset/spacenet/SN5_roads/train/AOI_7_Moscow/PS-MS/SN5_roads_train_AOI_7_Moscow_PS-MS_chip100.tif'},
 '1000': {'img': 's3://spacenet-dataset/spacenet/SN5_roads/train/AOI_7_Moscow/PS-MS/SN5_roads_train_AOI_7_Moscow_PS-MS_chip1000.tif'},
 '1001': {'img': 's3://spacenet-dataset/spacenet/SN5_roads/train/AOI_7_Moscow/PS-MS/SN5_roads_train_AOI_7_Moscow_PS-MS_chip1001.tif'},
 '1002': {'img': 's3://spacenet-dataset/spacenet/SN5_roads/train/AOI_7_Moscow/PS-MS/SN5_roads_train_AOI_7_Moscow_PS-MS_chip1002.tif'},
 '1003': {'img': 's3://spacenet-dataset/spacenet/SN5_roads/train/AOI_7_Moscow/PS-MS/SN5_roads_train_AOI_7_Moscow_PS-MS_chip1003.tif'},
 '1004': {'img': 's3://spacenet-dataset/spacenet/SN5_roads/train/AOI_7_Moscow/PS-MS/SN5_roads_train_AOI_7_Moscow_PS-MS_chip1004.tif'},
 '1005': {'img': 's3://spacenet-dataset/spacenet/SN5_roads/train/AOI_7_Moscow/PS-MS/SN5_roads_train_AOI_7_Moscow_PS-MS_chip1005.tif'}}

Let’s turn each of those chips into a STAC Item that represents the image.

[64]:
chip_id_to_items = {}

We’ll create core Items for our imagery, but mark them with the eo extension as we did above, and store the eo data in a Collection.

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).

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.

[65]:
import os

os.environ["AWS_NO_SIGN_REQUEST"] = "true"

for chip_id in chip_id_to_data:
    img_uri = chip_id_to_data[chip_id]["img"]
    print("Processing {}".format(img_uri))
    bbox, footprint = get_bbox_and_footprint(img_uri)

    item = pystac.Item(
        id="img_{}".format(chip_id),
        geometry=footprint,
        bbox=bbox,
        datetime=datetime.utcnow(),
        properties={},
    )

    item.common_metadata.gsd = 0.3
    item.common_metadata.platform = "Maxar"
    item.common_metadata.instruments = ["WorldView3"]

    item.ext.add("eo")
    item.ext.eo.bands = wv3_bands
    asset = pystac.Asset(href=img_uri, media_type=pystac.MediaType.COG)
    item.add_asset(key="ps-ms", asset=asset)
    asset.ext.eo.bands = wv3_bands
    chip_id_to_items[chip_id] = item
Processing s3://spacenet-dataset/spacenet/SN5_roads/train/AOI_7_Moscow/PS-MS/SN5_roads_train_AOI_7_Moscow_PS-MS_chip0.tif
Processing s3://spacenet-dataset/spacenet/SN5_roads/train/AOI_7_Moscow/PS-MS/SN5_roads_train_AOI_7_Moscow_PS-MS_chip1.tif
Processing s3://spacenet-dataset/spacenet/SN5_roads/train/AOI_7_Moscow/PS-MS/SN5_roads_train_AOI_7_Moscow_PS-MS_chip10.tif
Processing s3://spacenet-dataset/spacenet/SN5_roads/train/AOI_7_Moscow/PS-MS/SN5_roads_train_AOI_7_Moscow_PS-MS_chip100.tif
Processing s3://spacenet-dataset/spacenet/SN5_roads/train/AOI_7_Moscow/PS-MS/SN5_roads_train_AOI_7_Moscow_PS-MS_chip1000.tif
Processing s3://spacenet-dataset/spacenet/SN5_roads/train/AOI_7_Moscow/PS-MS/SN5_roads_train_AOI_7_Moscow_PS-MS_chip1001.tif
Processing s3://spacenet-dataset/spacenet/SN5_roads/train/AOI_7_Moscow/PS-MS/SN5_roads_train_AOI_7_Moscow_PS-MS_chip1002.tif
Processing s3://spacenet-dataset/spacenet/SN5_roads/train/AOI_7_Moscow/PS-MS/SN5_roads_train_AOI_7_Moscow_PS-MS_chip1003.tif
Processing s3://spacenet-dataset/spacenet/SN5_roads/train/AOI_7_Moscow/PS-MS/SN5_roads_train_AOI_7_Moscow_PS-MS_chip1004.tif
Processing s3://spacenet-dataset/spacenet/SN5_roads/train/AOI_7_Moscow/PS-MS/SN5_roads_train_AOI_7_Moscow_PS-MS_chip1005.tif

Creating the Collection#

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.

[66]:
from shapely.geometry import MultiPolygon, shape

footprints = list(map(lambda i: shape(i.geometry).envelope, chip_id_to_items.values()))
collection_bbox = MultiPolygon(footprints).bounds
spatial_extent = pystac.SpatialExtent(bboxes=[collection_bbox])
[67]:
datetimes = sorted(list(map(lambda i: i.datetime, chip_id_to_items.values())))
temporal_extent = pystac.TemporalExtent(intervals=[[datetimes[0], datetimes[-1]]])
[68]:
collection_extent = pystac.Extent(spatial=spatial_extent, temporal=temporal_extent)
[69]:
collection = pystac.Collection(
    id="wv3-images",
    description="Spacenet 5 images over Moscow",
    extent=collection_extent,
    license="CC-BY-SA-4.0",
)
[70]:
collection.add_items(chip_id_to_items.values())
[70]:
[<Link rel=item target=<Item id=img_0>>,
 <Link rel=item target=<Item id=img_1>>,
 <Link rel=item target=<Item id=img_10>>,
 <Link rel=item target=<Item id=img_100>>,
 <Link rel=item target=<Item id=img_1000>>,
 <Link rel=item target=<Item id=img_1001>>,
 <Link rel=item target=<Item id=img_1002>>,
 <Link rel=item target=<Item id=img_1003>>,
 <Link rel=item target=<Item id=img_1004>>,
 <Link rel=item target=<Item id=img_1005>>]
[71]:
collection.describe()
* <Collection id=wv3-images>
  * <Item id=img_0>
  * <Item id=img_1>
  * <Item id=img_10>
  * <Item id=img_100>
  * <Item id=img_1000>
  * <Item id=img_1001>
  * <Item id=img_1002>
  * <Item id=img_1003>
  * <Item id=img_1004>
  * <Item id=img_1005>

Now, we can create a Catalog and add the collection.

[72]:
catalog = pystac.Catalog(id="spacenet5", description="Spacenet 5 Data (Test)")
catalog.add_child(collection)
[72]:
[73]:
catalog.describe()
* <Catalog id=spacenet5>
    * <Collection id=wv3-images>
      * <Item id=img_0>
      * <Item id=img_1>
      * <Item id=img_10>
      * <Item id=img_100>
      * <Item id=img_1000>
      * <Item id=img_1001>
      * <Item id=img_1002>
      * <Item id=img_1003>
      * <Item id=img_1004>
      * <Item id=img_1005>