Generating geomedian composites

Keywords data used; sentinel 2, data methods; geomedian, analysis; composites, dask, data methods; resample, data methods; groupby

Background

Individual remote sensing images can be affected by noisy data, including clouds, cloud shadows, and haze. To produce cleaner images that can be compared more easily across time, we can create ‘summary’ images or ‘composites’ that combine multiple images into one image to reveal the median or ‘typical’ appearance of the landscape for a certain time period.

One approach is to create a geomedian. A geomedian is based on a high-dimensional statistic called the ‘geometric median’ (Small 1990), which effectively trades a temporal stack of poor quality observations for a single high-quality pixel composite with reduced spatial noise (Roberts et al. 2017). In contrast to a standard median, a geomedian maintains the relationship between spectral bands. This allows us to conduct further analysis on the composite images just as we would on the original satellite images (e.g by allowing the calculation of common band indices, like NDVI).

All the data of the selected timeframe has to be loaded to compute a composite, so geomedians can be computationally intensive to calculate, especially over large areas or long timescales. To assist with such analyses, DE Africa hosts a pre-calculated Sentinel-2 annual geomedian as part of the Sentinel-2 GeoMAD service. This reduces the time and resource needed to calculate the geomedian if you are conducting analysis over an annual timescale. Instructions on how to use the geomedian from the Sentinel-2 GeoMAD can be found in the Datasets/GeoMAD.ipynb notebook.

For analysis on other timescales, such as investigating change over seasons, it is not possible to use the annual geomedian product. In those cases, it can be useful to calculate geomedians for that specific time period.

Description

In this notebook we will take of time series of noisy satellite images collected over six months and calculate a six-month geomedian composite which is largely free of clouds and other noisy data.

Geomedian computations are expensive in terms of memory, data bandwidth, and CPU usage. The ODC has some useful function, int_geomedian and xr_geomedian that allows dask to perform the computation in parallel across many threads to speed things up. In this notebook a local dask cluster is used, but the same approach should work using a larger, distributed dask cluster.


Getting started

To run this analysis, run all the cells in the notebook, starting with the “Load packages” cell.

Load packages

[1]:
%matplotlib inline

import numpy as np
import datacube
from odc.algo import to_f32, xr_geomedian, int_geomedian
import warnings
warnings.filterwarnings('ignore')

from deafrica_tools.datahandling import load_ard
from deafrica_tools.plotting import rgb
from deafrica_tools.dask import create_local_dask_cluster

Set up a dask cluster

This will help keep our memory use down and conduct the analysis in parallel. If you’d like to view the dask dashboard, click on the hyperlink that prints below the cell. You can use the dashboard to monitor the progress of calculations.

[2]:
create_local_dask_cluster()

Client

Cluster

  • Workers: 1
  • Cores: 2
  • Memory: 13.11 GB

Connect to the datacube

[3]:
dc = datacube.Datacube(app='Generating_geomedian_composites')

Load Sentinel-2 from the datacube

Here we are loading in a timeseries of cloud-masked Sentinel-2 satellite images through the datacube API using the load_ard function. This will provide us with some data to work with. To limit computation and memory this example uses only three optical bands (red, green, blue).

[4]:
# Set up centre of area of interest, and area to buffer coordinates by
lat, lon = -15.92, 46.35
buffer = 0.075

# Create a reusable query
query = {
    'x': (lon-buffer, lon+buffer),
    'y': (lat+buffer, lat-buffer),
    'time': ('2019-01', '2019-06'),
    'measurements': ['green',
                     'red',
                     'blue'],
    'resolution': (-20, 20),
    'group_by': 'solar_day',
    'output_crs': 'EPSG:6933'
}

Compared to the typical use of load_ard which by default returns data with floating point numbers containing NaN (i.e. float32), in this example we will set the dtype to 'native'. This will keep our data in its original integer data type (i.e. Int16), with nodata values marked with -999. Doing this will halve the amount of memory our data takes up, which can be extremely valuable when conducting large-scale analyses.

[5]:
# Load available data
ds = load_ard(dc=dc,
              products=['s2_l2a'],
              dask_chunks={'x':1000, 'y':1000},
              dtype='native',
              **query)

# Print output data
print(ds)
Using pixel quality parameters for Sentinel 2
Finding datasets
    s2_l2a
Applying pixel quality/cloud mask
Returning 36 time steps as a dask array
<xarray.Dataset>
Dimensions:      (time: 36, x: 724, y: 922)
Coordinates:
  * time         (time) datetime64[ns] 2019-01-04T07:14:01 ... 2019-06-28T07:...
  * y            (y) float64 -1.996e+06 -1.996e+06 ... -2.015e+06 -2.015e+06
  * x            (x) float64 4.465e+06 4.465e+06 ... 4.479e+06 4.479e+06
    spatial_ref  int32 6933
Data variables:
    green        (time, y, x) uint16 dask.array<chunksize=(1, 922, 724), meta=np.ndarray>
    red          (time, y, x) uint16 dask.array<chunksize=(1, 922, 724), meta=np.ndarray>
    blue         (time, y, x) uint16 dask.array<chunksize=(1, 922, 724), meta=np.ndarray>
Attributes:
    crs:           EPSG:6933
    grid_mapping:  spatial_ref

Plot timesteps in true colour

To visualise the data, use the pre-loaded rgb utility function to plot a true colour image for a series of timesteps. Black areas indicate where clouds or other invalid pixels in the image have been set to -999 to indicate no data.

The code below will plot three timesteps of the time series we just loaded.

Note: This step can be quite slow because the dask arrays being plotted must be computed first.

[6]:
# Set the timesteps to visualise
timesteps = [2, 3, 6]

# Generate RGB plots at each timestep
rgb(ds, index=timesteps)

../../../_images/sandbox_notebooks_Frequently_used_code_Generating_geomedian_composites_16_0.png

Generate a geomedian

As you can see above, most satellite images will have at least some areas masked out due to clouds or other interference between the satellite and the ground. Running the int_geomedian function will generate a geomedian composite by combining all the observations in our xarray.Dataset into a single, complete (or near complete) image representing the geometric median of the time period.

Note: Because our data was lazily loaded with dask, the geomedian algorithm itself will not be triggered until we call the .compute() method in the next step.

[7]:
geomedian = int_geomedian(ds)

Run the computation

The .compute() method will trigger the computation of the geomedian algorithm above. This will take about a few minutes to run; view the dask dashboard to check the progress.

[8]:
%%time
geomedian = geomedian.compute()
CPU times: user 883 ms, sys: 113 ms, total: 996 ms
Wall time: 52.9 s

If we print our result, you will see that the time dimension has now been removed and we are left with a single image that represents the geometric median of all the satellite images in our initial time series:

[9]:
geomedian
[9]:
<xarray.Dataset>
Dimensions:  (x: 724, y: 922)
Coordinates:
  * y        (y) float64 -1.996e+06 -1.996e+06 ... -2.015e+06 -2.015e+06
  * x        (x) float64 4.465e+06 4.465e+06 4.465e+06 ... 4.479e+06 4.479e+06
Data variables:
    green    (y, x) uint16 756 759 754 751 750 739 ... 1017 993 1071 1033 1034
    red      (y, x) uint16 1060 1091 1073 1080 1068 ... 1800 1710 1887 1824 1849
    blue     (y, x) uint16 365 369 368 365 372 367 ... 569 594 570 611 601 601
Attributes:
    crs:           EPSG:6933
    grid_mapping:  spatial_ref

Plot the geomedian composite

Plotting the result, we can see that the geomedian image is much more complete than any of the individual images. We can also use this data in downstream analysis as the relationships between the spectral bands are maintained by the geometric median statistic.

[10]:
# Plot the result
rgb(geomedian, size=10)

../../../_images/sandbox_notebooks_Frequently_used_code_Generating_geomedian_composites_24_0.png

Running geomedian on grouped or resampled timeseries

In the notebook Generating composites, built in functions such as mean and median are run on timeseries data that has been resampled or grouped.
We can use the same techniques with the geomedian function.

Resampling

First we will split the timeseries into the desired groups. Resampling can be used to create a new set of times at regular intervals:

  • grouped = da_scaled.resample(time=1M)

    • 'nD' - number of days (e.g. '7D' for seven days)

    • 'nM' - number of months (e.g. '6M' for six months)

    • 'nY' - number of years (e.g. '2Y' for two years)

Group By

Grouping works by looking at part of the date, but ignoring other parts. For instance, 'time.month' would group together all January data together, no matter what year it is from.

  • grouped = da_scaled.groupby('time.month')

    • 'time.day' - groups by the day of the month (1-31)

    • 'time.dayofyear' - groups by the day of the year (1-365)

    • 'time.week' - groups by week (1-52)

    • 'time.month' - groups by the month (1-12)

    • 'time.season' - groups into 3-month seasons:

      • 'DJF' December, Jaunary, February

      • 'MAM' March, April, May

      • 'JJA' June, July, August

      • 'SON' September, October, November

    • 'time.year' - groups by the year

Here we will resample into three two-monthly groups ('2M'), with the group starting at the start of the month (represented by the 'S' at the end).

[11]:
grouped = ds.resample(time='2MS')
grouped
[11]:
DatasetResample, grouped over '__resample_dim__'
3 groups with labels 2019-01-01, ..., 2019-05-01.

Now we will apply the int_geomedian function to each resampled group using the map method.

Instead of calling int_geomedian(ds) on the entire array, we pass the int_geomedian function to map to apply it separately to each resampled group.

[12]:
geomedian_grouped = grouped.map(int_geomedian)

We can now trigger the computation, and watch progress using the dask dashboard.

[13]:
%%time
geomedian_grouped = geomedian_grouped.compute()
CPU times: user 1.08 s, sys: 163 ms, total: 1.24 s
Wall time: 56.2 s

We can plot the output geomedians, and see the change in the landscape over the year:

[14]:
rgb(geomedian_grouped, col='time', col_wrap=4)
../../../_images/sandbox_notebooks_Frequently_used_code_Generating_geomedian_composites_32_0.png

Advanced: Geomedian on float arrays

The ODC has a useful function, xr_geomedian that allows for calcuating geomedians on a xarray.Dataset (as well as xr.DataArrays and numpy arrays) with a float data type.

To demonstrate this we will reload our dataset using load_ard, but this time removing the parameter dtype='native'. This will return our dataset in dtype Float32.

[15]:
# Load available data
ds = load_ard(dc=dc,
              products=['s2_l2a'],
              dask_chunks={'x':1000, 'y':1000},
              **query)

# Print output data
print(ds)
Using pixel quality parameters for Sentinel 2
Finding datasets
    s2_l2a
Applying pixel quality/cloud mask
Returning 36 time steps as a dask array
<xarray.Dataset>
Dimensions:      (time: 36, x: 724, y: 922)
Coordinates:
  * time         (time) datetime64[ns] 2019-01-04T07:14:01 ... 2019-06-28T07:...
  * y            (y) float64 -1.996e+06 -1.996e+06 ... -2.015e+06 -2.015e+06
  * x            (x) float64 4.465e+06 4.465e+06 ... 4.479e+06 4.479e+06
    spatial_ref  int32 6933
Data variables:
    green        (time, y, x) float32 dask.array<chunksize=(1, 922, 724), meta=np.ndarray>
    red          (time, y, x) float32 dask.array<chunksize=(1, 922, 724), meta=np.ndarray>
    blue         (time, y, x) float32 dask.array<chunksize=(1, 922, 724), meta=np.ndarray>
Attributes:
    crs:           EPSG:6933
    grid_mapping:  spatial_ref

Note: xr_geomedian has several parameters we can set that will control its functionality.

  • Setting num_thread=1 will disable the internal threading and instead allow parallelisation with dask.

  • The eps parameter controls the number of iterations to conduct; a good default is 1e-7.

  • For numerical stability, it can also be advisable to scale surface reflectance float values in the dataset to 0-1 (instead of 0-10,000 as is the default for Sentinel-2). We can do this by using the helper functions to_f32. We do this in the code cell below before we compute the geomedian. Note, this is not an essential step.

[16]:
sr_max_value = 10000                 # maximum value for SR in the loaded product
scale, offset = (1/sr_max_value, 0)  # differs per product, aim for 0-1 values in float32

#scale the values using the f_32 util function
ds_scaled = to_f32(ds,
                   scale=scale,
                   offset=offset)
[17]:
geomedian = xr_geomedian(ds_scaled,
                         num_threads=1,
                         eps=1e-7,
                         ).compute()
[18]:
rgb(geomedian)
../../../_images/sandbox_notebooks_Frequently_used_code_Generating_geomedian_composites_38_0.png

Additional information

License: The code in this notebook is licensed under the Apache License, Version 2.0. Digital Earth Africa data is licensed under the Creative Commons by Attribution 4.0 license.

Contact: If you need assistance, please post a question on the Open Data Cube Slack channel or on the GIS Stack Exchange using the open-data-cube tag (you can view previously asked questions here). If you would like to report an issue with this notebook, you can file one on Github.

Compatible datacube version:

[19]:
print(datacube.__version__)
1.8.4.dev52+g07bc51a5

Last Tested:

[20]:
from datetime import datetime
datetime.today().strftime('%Y-%m-%d')
[20]:
'2021-04-14'