Visualizing MAAP STAC Dataset with MosaicJSON

Authors: Samuel Ayers (UAH), Alex Mandel (DevSeed), Aimee Barciauskas (DevSeed)

Date: July 23, 2021

Description: In this notebook, we visualize SRTM Cloud-Optimized GeoTIFFs (COGs) from MAAP’s STAC using a generated mosaic from MAAP’s TiTiler.

Run This Notebook

To access and run this tutorial within MAAP’s Algorithm Development Environment (ADE), please refer to the “Getting started with the MAAP” section of our documentation.

Disclaimer: it is highly recommended to run a tutorial within MAAP’s ADE, which already includes packages specific to MAAP, such as maap-py. Running the tutorial outside of the MAAP ADE may lead to errors.

Note About the Data

The NASA Shuttle Radar Topographic Mission (SRTM) has provided digital elevation data (DEMs) for over 80% of the globe. This data is currently distributed free of charge by USGS and is available for download from the National Map Seamless Data Distribution System, or the USGS FTP site.

At MAAP, we’ve converted this elevation data into Cloud-Optimized GeoTIFFs (COGs) so they can be efficiently queried and visualized. These COGs are available in the MAAP STAC.

Additional Resources

Importing and Installing Packages

To be able to run this notebook you’ll need the following requirements:

  • rasterio

  • folium

  • requests

  • pystac-client

  • cogeo-mosaic (Optional)

If the packages below are not installed already, uncomment the following cell:

[1]:
# %pip install rasterio
# %pip install folium
# %pip install requests
# %pip install pystac-client
# %pip install cogeo-mosaic --pre
[2]:
import requests

from pystac_client import Client

from pprint import pprint

from rasterio.features import bounds as featureBounds

from folium import Map, TileLayer, GeoJson

Fetch SRTM COG STAC Items

[3]:
cat = Client.open('https://stac.maap-project.org/')

items = list(
    cat.search(
        collections="SRTMGL1_COD",
        bbox=[4, 42, 16, 48],
        max_items=120
    ).items_as_dicts(),
)

Map the Data Bounds

[4]:
geojson = {"type": "FeatureCollection", "features": items}

bounds = featureBounds(geojson)
zoom_start = 5

m = Map(
    tiles="OpenStreetMap",
    location=((bounds[1] + bounds[3]) / 2, (bounds[0] + bounds[2]) / 2),
    zoom_start=zoom_start,
)

geo_json = GeoJson(
    data=geojson,
    style_function=lambda x: {
        "opacity": 1,
        "dashArray": "1",
        "fillOpacity": 0,
        "weight": 1,
    },
)
geo_json.add_to(m)
m
[4]:
Make this Notebook Trusted to load map: File -> Trust Notebook

Create Mosaic

We’re using the TiTiler deployed by MAAP

[5]:
titiler_endpoint = "https://titiler.maap-project.org"  # MAAP titiler endpoint

To begin, we’ll pull our COG:

[6]:
cog_info = requests.get(
    f"{titiler_endpoint}/cog/info",
    params={
        "url": geojson["features"][0]["assets"]["cog_default"]["href"],
    },
).json()
pprint(cog_info)
{'band_descriptions': [['b1', '']],
 'band_metadata': [['b1', {}]],
 'bounds': [15.99986111111111,
            47.999861111111116,
            17.000138888888888,
            49.00013888888889],
 'colorinterp': ['gray'],
 'count': 1,
 'driver': 'GTiff',
 'dtype': 'int16',
 'height': 3601,
 'maxzoom': 12,
 'minzoom': 8,
 'nodata_type': 'Nodata',
 'nodata_value': -32768.0,
 'overviews': [2, 4, 8, 16],
 'width': 3601}

Next, we will create the mosaic using the geojson from above. SRTMGL1 COGs have a “cog default” asset type, so we can create a mosaic of these type=”image/tiff” assets. We can get access to these assets by using the accessor function.

[7]:
from cogeo_mosaic.mosaic import MosaicJSON

mosaicdata = MosaicJSON.from_features(
    geojson.get("features"),
    minzoom=cog_info["minzoom"],
    maxzoom=cog_info["maxzoom"],
    accessor=lambda feature: feature["assets"]["cog_default"]["href"],
)

Alternatively, we can build a MosaicJSON using a list of files within MAAP’s ADE by converting the local “my-private”, “my-public”, and “shared-buckets” paths to their respective AWS S3 prefixes like so:

from maap.maap import MAAP
maap = MAAP(maap_host='api.maap-project.org')
username = maap.profile.account_info()["username"]

local_path = "/local/path/to/files/"

files = glob.glob(os.path.join(dps_output, "*.tif"), recursive=False)

def local_to_s3(url):
    ''' A Function to convert local paths to s3 urls'''
    if url.startswith("my-private-bucket"):
        return url.replace("my-private-bucket", f"s3://maap-ops-workspace/{username}")

    if url.startswith("my-public-bucket"):
        return url.replace("my-public-bucket", f"s3://maap-ops-workspace/shared/{username}")

    if url.startswith("shared-buckets"):
        return url.replace("shared-buckets", "s3://maap-ops-workspace/shared")

tiles = [local_to_s3(file) for file in files]

mosaicdata = MosaicJSON.from_urls(tiles, minzoom=9, maxzoom=16)

Now we will upload the mosaicjson to the TiTiler:

[8]:
mosaic_links = requests.post(
    url=f"{titiler_endpoint}/mosaics",
    headers={
        "Content-Type": "application/vnd.titiler.mosaicjson+json",
    },
    json=mosaicdata.model_dump(exclude_none=True),
).json()

pprint(mosaic_links)
{'id': 'a6739144-b9ab-4ef6-82c3-f092100858cb',
 'links': [{'href': 'https://titiler.maap-project.org/mosaics/a6739144-b9ab-4ef6-82c3-f092100858cb',
            'rel': 'self',
            'title': 'Self',
            'type': 'application/json'},
           {'href': 'https://titiler.maap-project.org/mosaics/a6739144-b9ab-4ef6-82c3-f092100858cb/mosaicjson',
            'rel': 'mosaicjson',
            'title': 'MosaicJSON',
            'type': 'application/json'},
           {'href': 'https://titiler.maap-project.org/mosaics/a6739144-b9ab-4ef6-82c3-f092100858cb/tilejson.json',
            'rel': 'tilejson',
            'title': 'TileJSON',
            'type': 'application/json'},
           {'href': 'https://titiler.maap-project.org/mosaics/a6739144-b9ab-4ef6-82c3-f092100858cb/tiles/{z}/{x}/{y}',
            'rel': 'tiles',
            'title': 'Tiles',
            'type': 'application/json'},
           {'href': 'https://titiler.maap-project.org/mosaics/a6739144-b9ab-4ef6-82c3-f092100858cb/WMTSCapabilities.xml',
            'rel': 'wmts',
            'title': 'WMTS',
            'type': 'application/json'}]}

The response from the post request gives endpoints for different services (eg. mosaicjson, tilejson, tiles, wmts, etc). We’re fetching the tilejson endpoint.

[9]:
tilejson_endpoint = list(
    filter(lambda x: x.get("rel") == "tilejson", dict(mosaic_links)["links"])
)
tilejson_endpoint
[9]:
[{'href': 'https://titiler.maap-project.org/mosaics/a6739144-b9ab-4ef6-82c3-f092100858cb/tilejson.json',
  'rel': 'tilejson',
  'type': 'application/json',
  'title': 'TileJSON'}]

Display Tiles

NOTE: The important bit is the “tiles” endpoint returned from f"{titiler_endpoint}/mosaics. This endpoint (e.g. https://titiler.maap-project.org/mosaics/{mosaic_id}/tiles/{z}/{x}/{y}) could be used in any map client which can tile x,y,z layers.

Read more about this endpoint at MAAP’s TiTiler docs.

[10]:
params = {"colormap_name": "viridis", "rescale": "0,4000"}

r_te = requests.get(tilejson_endpoint[0]["href"], params=params).json()

tiles = TileLayer(tiles=f"{r_te['tiles'][0]}", opacity=1, attr="USGS")

tiles.add_to(m)
m
[10]:
Make this Notebook Trusted to load map: File -> Trust Notebook
[ ]: