import requests
import folium
import folium.plugins
from folium import Map, TileLayer
from pystac_client import Client
import branca
import pandas as pd
import matplotlib.pyplot as plt
GRA²PES Greenhouse Gas and Air Quality Species
Run this notebook
You can launch this notebook in the US GHG Center JupyterHub by clicking the link below.
Approach
- Identify available dates and temporal frequency of observations for the given collection using the GHGC API
/stac
endpoint. The collection processed in this notebook is the Vulcan Fossil Fuel CO₂ Emissions Data product. - Pass the STAC item into the raster API
/stac/tilejson.json
endpoint. - Using
folium.plugins.DualMap
, we will visualize two tiles (side-by-side), allowing us to compare time points. - After the visualization, we will perform zonal statistics for a given polygon.
About the Data
The Greenhouse gas And Air Pollutants Emissions System (GRA2PES) dataset at the GHG Center is an aggregated, regridded, monthly high-resolution (0.036 x 0.036°) data product with emissions of both greenhouse gases and air pollutants developed in a consistent framework. The dataset contains emissions over the contiguous United States covering major anthropogenic sectors, including energy, industrial fuel combustion and processes, commercial and residential combustion, oil and gas production, on-road and off-road transportation, etc. (see Table 1 in the Scientific Details section below for a full sector list). Fossil fuel CO2 (ffCO2) emissions are developed along with those of air pollutants including CO, NOx, SOx, and PM2.5 with consistency in spatial and temporal distributions. Emissions by sectors are grouped into point and area sources, reported as column totals in units of metric tons per km2 per month. Spatial-temporal surrogates are developed to distribute CO2 emissions to grid cells to keep consistency between greenhouse gases and air quality species. The current version of GRA2PES is for 2021. Long-term emissions and more greenhouse gas species (e.g., methane) are under development and will be added in the future.
For more information regarding this dataset, please visit the GRA2PES Greenhouse Gas and Air Quality Species, Version 1 data overview page.
Install the Required Libraries
Required libraries are pre-installed on the GHG Center Hub. If you need to run this notebook elsewhere, please install them with this line in a code cell:
%pip install requests folium rasterstats pystac_client pandas matplotlib –quiet
Querying the STAC API
First, we are going to import the required libraries. Once imported, they allow better executing a query in the GHG Center Spatio Temporal Asset Catalog (STAC) Application Programming Interface (API) where the granules for this collection are stored.
# Provide STAC and RASTER API endpoints
= "https://earth.gov/ghgcenter/api/stac"
STAC_API_URL = "https://earth.gov/ghgcenter/api/raster"
RASTER_API_URL
# Please use the collection name similar to the one used in the STAC collection.
# Name of the collection for Vulcan Fossil Fuel CO₂ Emissions, Version 4.
= "gra2pes-ghg-monthgrid-v1" collection_name
# Fetch the collection from STAC collections using the appropriate endpoint
# the 'requests' library allows a HTTP request possible
= requests.get(f"{STAC_API_URL}/collections/{collection_name}").json() collection_graapes
Examining the contents of our collection
under the temporal
variable, we see that the data is available from January 2010 to December 2021. By looking at the dashboard:time density
, we observe that the data is periodic with year time density.
# Create a function that would search for the above data collection in the STAC API
def get_item_count(collection_id):
= 0
count = f"{STAC_API_URL}/collections/{collection_id}/items"
items_url
while True:
= requests.get(items_url)
response
if not response.ok:
print("error getting items")
exit()
= response.json()
stac += int(stac["context"].get("returned", 0))
count next = [link for link in stac["links"] if link["rel"] == "next"]
if not next:
break
= next[0]["href"]
items_url
return count
# Apply the above function and check the total number of items available within the collection
= get_item_count(collection_name)
number_of_items = requests.get(f"{STAC_API_URL}/collections/{collection_name}/items?limit={number_of_items}").json()["features"]
items_graapes print(f"Found {len(items_vulcan)} items")
Found 12 items
# To access the year value from each item more easily, this will let us query more explicitly by year and month (e.g., 2020-02)
= {item["properties"]["start_datetime"][:7]: item for item in items_graapes}
items # rh = Heterotrophic Respiration
= "co2" asset_name
= {"max":items[list(items.keys())[0]]["assets"][asset_name]["raster:bands"][0]["histogram"]["max"], "min":items[list(items.keys())[0]]["assets"][asset_name]["raster:bands"][0]["histogram"]["min"]} rescale_values
Now, we will pass the item id, collection name, asset name, and the rescaling factor
to the Raster API
endpoint. We will do this twice, once for 2021-01 and again for 2021-05, so that we can visualize each event independently.
= "spectral_r" # please refer to matplotlib library if you'd prefer choosing a different color ramp.
color_map # For more information on Colormaps in Matplotlib, please visit https://matplotlib.org/stable/users/explain/colors/colormaps.html
# To change the year and month of the observed parameter, you can modify the "items['YYYY-MM']" statement
# For example, you can change the current statement "items['2003-12']" to "items['2016-10']"
= requests.get(
_202101_tile f"{RASTER_API_URL}/collections/{items['2021-01']['collection']}/items/{items['2021-01']['id']}/tilejson.json?collection={items['2021-01']['collection']}&item={items['2021-01']['id']}"
f"&assets={asset_name}"
f"&color_formula=gamma+r+1.05&colormap_name={color_map}"
f"&rescale=0,150",
).json() _202101_tile
{'tilejson': '2.2.0',
'version': '1.0.0',
'scheme': 'xyz',
'tiles': ['https://dev.ghg.center/api/raster/collections/gra2pes-co2-monthgrid-v1/items/gra2pes-co2-monthgrid-v1-202101/tiles/WebMercatorQuad/{z}/{x}/{y}@1x?collection=gra2pes-co2-monthgrid-v1&item=gra2pes-co2-monthgrid-v1-202101&assets=co2&color_formula=gamma+r+1.05&colormap_name=spectral_r&rescale=0%2C150'],
'minzoom': 0,
'maxzoom': 24,
'bounds': [-137.3143, 18.173376, -58.58229999999702, 52.229376000001295],
'center': [-97.94829999999851, 35.20137600000065, 0]}
= requests.get(
_202105_tile f"{RASTER_API_URL}/collections/{items['2021-05']['collection']}/items/{items['2021-05']['id']}/tilejson.json?collection={items['2021-05']['collection']}&item={items['2021-05']['id']}"
f"&assets={asset_name}"
f"&color_formula=gamma+r+1.05&colormap_name={color_map}"
f"&rescale=0,150",
).json() _202105_tile
{'tilejson': '2.2.0',
'version': '1.0.0',
'scheme': 'xyz',
'tiles': ['https://dev.ghg.center/api/raster/collections/gra2pes-co2-monthgrid-v1/items/gra2pes-co2-monthgrid-v1-202105/tiles/WebMercatorQuad/{z}/{x}/{y}@1x?collection=gra2pes-co2-monthgrid-v1&item=gra2pes-co2-monthgrid-v1-202105&assets=co2&color_formula=gamma+r+1.05&colormap_name=spectral_r&rescale=0%2C150'],
'minzoom': 0,
'maxzoom': 24,
'bounds': [-137.3143, 18.173376, -58.58229999999702, 52.229376000001295],
'center': [-97.94829999999851, 35.20137600000065, 0]}
Visualizing Total Fossil Fuel CO₂ Emissions
= folium.plugins.DualMap(location=(34, -118), zoom_start=6)
map_
# Define the first map layer with the CO2 Flux data for December 2022
= TileLayer(
map_layer_202101 =_202101_tile["tiles"][0], # Path to retrieve the tile
tiles="GHG", # Set the attribution
attr='2021-01 Total CO2 Fossil Fuel Emissions', # Title for the layer
name=True, # The layer can be overlaid on the map
overlay=0.8, # Adjust the transparency of the layer
opacity
)# Add the first layer to the Dual Map
map_layer_202101.add_to(map_.m1)
= TileLayer(
map_layer_202105 =_202105_tile["tiles"][0], # Path to retrieve the tile
tiles="GHG", # Set the attribution
attr='2021-05 Total CO2 Emissions', # Title for the layer
name=True, # The layer can be overlaid on the map
overlay=0.8, # Adjust the transparency of the layer
opacity
)# Add the first layer to the Dual Map
map_layer_2021.add_to(map_.m2)
map_
Summary
In this notebook we have successfully explored, analyzed, and visualized the STAC collection for GRA2PES greenhouse gases Emissions, Version 1 dataset.
- Install and import the necessary libraries
- Fetch the collection from STAC collections using the appropriate endpoints
- Count the number of existing granules within the collection
- Map and compare the total CO₂ emissions for two distinctive months/years
If you have any questions regarding this user notebook, please contact us using the feedback form.