Landsat 8 NDVI Analysis on the Cloud

This notebook demonstrates a "Cloud-native" analysis of Normalized Difference Vegetation Index (NDVI) using Landsat 8 data.

What is unique about this workflow is that no data is downloaded to our local computer! All calculations are performed in memory across many distributed machines on AWS.

This workflow is possible because the Landsat 8 data is stored in Cloud-Optimized Geotiff format, which can be accessed remotely via xarray and rasterio Python libraries. Distributed computing is enabled through a Pangeo JupyterHub deployment with Dask Kubernetes.

About Landsat 8:

About the Landsat archive:

Date: August 30, 2018

Created by: Scott Henderson ([email protected]), Daniel Rothenberg

Updated to use hvplot/holoviews by Ryan Abernathy and Rich Signell ([email protected])

In [ ]:
# Import required libraries
import os
import pandas as pd
import rasterio
import xarray as xr
import requests

from dask_gateway import Gateway
from dask.distributed import Client
from dask.distributed import wait, progress

import hvplot.xarray
import hvplot.pandas

import as ccrs
import holoviews as hv
In [ ]:
# Print package versions
print('xarray version: ', xr.__version__)
print('rasterio version: ', rasterio.__version__)
print('hvplot version: ', hvplot.__version__)
In [ ]:
# Set environment variables for cloud-optimized-geotiffs efficiency

Use NASA Common Metadata Repository (CMR) to get Landsat 8 images

NASA CMR is a new unified way to search for remote sensing assests across many archive centers. If you prefer a graphical user interface, NASA Earthdata Search is built on top of CMR. CMR returns download links through the USGS (, but the same archive is mirrored as a (Google Public Dataset)[], so we'll make a function that queries CMR and returns URLs to the imagery stored on Google Cloud.

In [ ]:
def query_cmr_landsat(collection='Landsat_8_OLI_TIRS_C1',tier='T1', path=47, row=27):
    """Query NASA CMR for Collection1, Tier1 Landsat scenes from a specific path and row."""
    data = [f'short_name={collection}',

    query = '' + '&'.join(data)

    r = requests.get(query, timeout=100)
    df = pd.DataFrame(r.json()['feed']['entry'])
    # Save results to a file
    #print('Saved results to cmr-result.json')
    #with open('cmr-result.json', 'w') as j:
    #    j.write(r.text)
    return df
In [ ]:
def make_google_archive(pids, bands):
    """Turn list of product_ids into pandas dataframe for NDVI analysis."""
    path =  pids[0].split('_')[2][1:3]
    row =  pids[0].split('_')[2][-2:]
    baseurl = f'{path}/0{row}'
#    baseurl = f's3://landsat-pds/c1/L8/0{path}/0{row}'    # not sure there is an AWS equivalent here
    dates = [pd.to_datetime(x.split('_')[3]) for x in pids]
    df = pd.DataFrame(dict(product_id=pids, date=dates))
    for band in bands:
        df[band] = [f'{baseurl}/{x}/{x}_{band}.TIF' for x in pids]
    return df
In [ ]:
df = query_cmr_landsat()
In [ ]:
pids = df.title.tolist()
df = make_google_archive(pids, ['B4', 'B5'])
In [ ]:
In [ ]:
image_url = df.iloc[0]['B4']
In [ ]:

Launch Dask Kubernetes Cluster

This will allow us to distribute our analysis across many machines. In the default configuration for Pangeo Binder, each worker has 2 vCPUs and 7Gb of RAM. It may take several minutes to initialize these workers and make them available to Dask.

In [ ]:
from dask_gateway import Gateway

gateway = Gateway()
cluster = gateway.new_cluster()
In [ ]:
# Attach Dask to the cluster
client = Client(cluster)

Examine a single band Landsat image

The rasterio library allows us to read Geotiffs on the web without downloading the entire image. Xarray has a built-in load_rasterio() function that allows us to open the file as a DataArray. Xarray also uses Dask for lazy reading, so we want to make sure the native block tiling of the image matches the dask "chunk size". These dask chunks are automatically distributed among all our workers when a computation is requested, so ideally they will fit in the worker memory. A chunk size of 2048x2048 with a float32 datatype implies a 16Mb array.

In [ ]:
# Load with rasterio
image_url = df.iloc[0]['B4']
with as src:
In [ ]:
# Note that the blocksize of the image is 256 by 256, so we want xarray to use some multiple of that
xchunk = 2048
ychunk = 2048
da = xr.open_rasterio(image_url, chunks={'band': 1, 'x': xchunk, 'y': ychunk})
In [ ]:
# If we request to compute something or plot these arrays, the necessary data chunks will be accessed on cloud storage:
# Watch the Dask dashboard to see the worker activity when this command is run:
# Note that no data is stored on the disk here, it's all in memory
band1 = da.sel(band=1).persist()
In [ ]:
display(band1.hvplot(rasterize=True, width=600, height=400, cmap='viridis'))
In [ ]:
# skip this because it takes minutes to run and doesn't use the dask workers.

# here we use the CRS info (epsg:32610 = UTM zone 10n) to plot in lon/lat 
# rather than in projected coordinates.
if 0:
    crs = ccrs.UTM(zone='10n')
    display(band1.hvplot(crs=crs, rasterize=True, width=600, height=400, cmap='viridis'))

Load all Landsat bands into an xarray dataset

Often we want to analyze a time series of satellite imagery, but we are constrained by computational resources. So we either download all the images, extract a small subset and then do our analysis. Or, we coarsen the resolution of all our images so that the entire set fits into our computer RAM. Because this notebook is running on Google Cloud with access to many resources in our Kube Cluster, we no longer have to worry about the computational constraints, and can conduct our analysis at full resoution!

First we need to construct an xarray dataset object (which has data variables 'band4' and 'band5' in a n-dimensional array with x-coordinates representing UTM easting, y-coordinates representing UTM northing, and a time coordinate representing the image acquisition date).

There are different ways to go about this, but we will load our images with a timestamp index since each image is taken on a different date. Typically, this is a chore if our images are not on the same grid to begin with, but xarray knows how to automatically align images based on their georeferenced coordinates.

In [ ]:
# Note that these landsat images are not necessarily the same shape or on the same grid:
for image_url in df.B4[:5]:
    with as src:
        print(src.shape, src.bounds)
In [ ]:
def create_multiband_dataset(row, bands=['B4','B5'], chunks={'band': 1, 'x': 2048, 'y': 2048}):
    '''A function to load multiple landsat bands into an xarray dataset '''
    # Each image is a dataset containing both band4 and band5
    datasets = []
    for band in bands:
        url = row[band]
        da = xr.open_rasterio(url, chunks=chunks)
        da = da.squeeze().drop(labels='band')
        ds = da.to_dataset(name=band)

    DS = xr.merge(datasets)
    return DS
In [ ]:
# Merge all acquisitions into a single large Dataset
datasets = []
for i,row in df.iterrows():
        ds = create_multiband_dataset(row)
    except Exception as e:
        print('ERROR loading, skipping acquistion!')
In [ ]:
DS = xr.concat(datasets, dim=pd.DatetimeIndex(, name='time'))
print('Dataset size (Gb): ', DS.nbytes/1e9)
In [ ]:

Note that xarray has automatically expanded the dimensions to include the maximum extents of all the images, also the chunksize has been automatically adjusted.

There is definitely some room for improvement here from a computational efficiency standpoint - in particular the dask chunks are no longer aligned with the image tiles. This is because each image starts at different coordinates and has different shapes, but xarray uses a single chunk size for the entire datasets. There will also be many zeros in this dataset, so future work could take advantage of sparse arrays.

These points aside, our Dask Cluster will automatically parallelize our computations for us, so we can not worry too much about optimal efficiency and just go ahead and run our analysis!

Browse interactively using hvplot

In [ ]:
display(DS['B4'].hvplot('x', 'y', groupby='time', rasterize=True, width=600, height=400, cmap='viridis'))

Distributed NDVI computations

Set up our NDVI dataset. Note that NDVI is not actually computed until we call the Dask compute(), persist(), or call other functions such as plot() that require actually operate on the data!

In [ ]:
NDVI = (DS['B5'] - DS['B4']) / (DS['B5'] + DS['B4'])

Plot NDVI on specific date (full resolution)

Only data for a single landsat acquisition date is pulled from Cloud storage

In [ ]:
s = NDVI.sel(time=day, method='nearest')
In [ ]:
del s['time']
In [ ]:
display(s.hvplot('x', 'y', rasterize=True, width=600, height=400, cmap='viridis', label=day))

Mean NDVI for a range of dates

This example calculates the mean NDVI per-pixel (30m) for 2013-2014, storing result in local RAM. This takes a while...

In [ ]:
ndvi = NDVI.sel(time=slice('2013-01-01', '2014-01-01')).mean(dim='time').persist()
In [ ]:
In [ ]:
display(ndvi.hvplot('x','y', rasterize=True, width=600, height=400, cmap='viridis'))

# Point of interest we'll extract a timeseries from
#plt.plot(562370, 5312519, 'ko')

Extract region of interest Farmland near Everett, WA (Ebey Island) and resample to monthly mean average

We expect to see higher NDVI values in the summer months, corresponding to dense vegetation

In [ ]:
# lat, lon to northing, easting
# 47.962940 --> 5312519
# -122.164483--> 562370
#+ 5 km buffer
#EPSG:32610 WGS 84 / UTM zone 10N
xcen = 562370
ycen = 5312519
buf = 5000  # look at point +/- 5km
ds = NDVI.sel(x=slice(xcen-buf,xcen+buf), y=slice(ycen-buf,ycen+buf))
timeseries = ds.resample(time='1MS').mean().persist()
In [ ]:
In [ ]:
s = timeseries.to_series()
(s.hvplot(width=700, height=300, legend=False) * s.hvplot.scatter(width=700, height=300, legend=False)).relabel('Mean NDVI')

Plot subset of all NDVI arrays at full resolution for acquisitions in 2015

In [ ]:
ds2015 = ds.sel(time=slice('2015-01-01', '2016-01-01'))
nt = len(ds2015)

Getting small multiple plots going with hvplot is a bit challenging. Need to use Layout from holoviews:

In [ ]:

dss = ds.sel(time=slice('2015-01-01', '2016-01-01'))
ncols = 5

plots = []
for i in range(nt):
    ds_panel = dss.isel(time=i)

    #if last plot in row, add colorbar and make it wider
    is_last_in_row = (i+1)%ncols == 0
    height = 200
    width = 150 if not is_last_in_row else 200

    p = (ds_panel
       .hvplot('x', 'y', rasterize=True, width=width, height=height, cmap='viridis', 
               xaxis=False, yaxis=False, colorbar=is_last_in_row)


Plot subset of all NDVI arrays at full resolution for acquisitions in 2015

In [ ]:
display(NDVI.hvplot('x','y',groupby='time', rasterize=True, width=700, height=500, cmap='viridis'))

In conclusion

  • This notebook demonstrates the power of storing data publically in the Cloud as optimized geotiffs - scientists can conduct scalable analysis without downloading the data to a local machine. Only derived subsets and figures need to be downloaded!
  • We used a crude NDVI calculation, designed to demonstrate the syntax and tools - a proper analysis should take into account cloud masks and other corrections
In [ ]:
In [ ]: