Vegetation Phenology¶

Keywords data used; sentinel-2, band index; NDVI, band index; EVI, phenology, analysis; time series

Background¶

Phenology is the study of plant and animal life cycles in the context of the seasons. It can be useful in understanding the life cycle trends of crops and how the growing seasons are affected by changes in climate. For more information, see the USGS page on deriving phenology from NDVI time-series

Description¶

This notebook demonstrates how to calculate vegetation phenology statistics using the DE Africa function xr_phenology. To detect changes in plant life for Sentinel-2, the script uses either the Normalized Difference Vegetation Index (NDVI) or the Enhanced Vegetation Index (EVI), which are common proxies for vegetation growth and health.

The outputs of this notebook can be used to assess spatio-temporal differences in the growing seasons of agriculture fields or native vegetation.

This notebook demonstrates the following steps:

1. Load cloud-masked Sentinel 2 data for an area of interest.

2. Calculate a vegetation proxy index (NDVI or EVI).

3. Generate a zonal time series of vegetation health

4. Complete and smooth the vegetation timeseries to remove gaps and noise.

5. Calculate phenology statistics on a simple 1D vegetation time series

6. Calculate per-pixel phenology statistics

7. Optional: Calculating generic temporal statistics usng the hdstats library

Getting started¶

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

Load packages¶

Load key Python packages and supporting functions for the analysis.

[1]:

%matplotlib inline

import os
import datacube
import numpy as np
import pandas as pd
import xarray as xr
import datetime as dt
import matplotlib.pyplot as plt

import deafrica_tools.temporal as ts
from deafrica_tools.datahandling import load_ard
from deafrica_tools.bandindices import calculate_indices
from deafrica_tools.plotting import display_map, rgb

from datacube.utils.aws import configure_s3_access
configure_s3_access(aws_unsigned=True, cloud_defaults=True)

/env/lib/python3.6/site-packages/geopandas/_compat.py:88: UserWarning: The Shapely GEOS version (3.7.2-CAPI-1.11.0 ) is incompatible with the GEOS version PyGEOS was compiled with (3.9.0-CAPI-1.16.2). Conversions between both will be slow.
shapely_geos_version, geos_capi_version_string


Connect to the datacube¶

Connect to the datacube so we can access DE Africa data. The app parameter is a unique name for the analysis which is based on the notebook file name.

[2]:

dc = datacube.Datacube(app='Vegetation_phenology')


Analysis parameters¶

The following cell sets important parameters for the analysis:

• veg_proxy: Band index to use as a proxy for vegetation health e.g. 'NDVI' or 'EVI'

• lat: The central latitude to analyse (e.g. -10.6996).

• lon: The central longitude to analyse (e.g. 35.2708).

• buffer: The number of square degrees to load around the central latitude and longitude. For reasonable loading times, set this as 0.1 or lower.

• time_range: The year range to analyse (e.g. ('2019-01', '2019-06')).

[3]:

# Set the vegetation proxy to use
veg_proxy = 'NDVI'

# Define area of interest
lat = 22.817
lon = 28.518
lon_buffer = 0.0175
lat_buffer = 0.004

# Set the range of dates for the analysis
time_range = ('2018-01', '2018-05')

[4]:

# Combine central lat,lon with buffer to get area of interest
lat_range = (lat-lat_buffer, lat+lat_buffer)
lon_range = (lon-lon_buffer, lon+lon_buffer)


View the selected location¶

The next cell will display the selected area on an interactive map. Feel free to zoom in and out to get a better understanding of the area you’ll be analysing. Clicking on any point of the map will reveal the latitude and longitude coordinates of that point.

[5]:

display_map(x=lon_range, y=lat_range)

[5]:


Load cloud-masked Sentinel-2 data¶

The first step is to load Sentinel-2 data for the specified area of interest and time range. The load_ard function is used here to load data that has been masked for cloud, shadow and quality filters, making it ready for analysis.

[6]:

# Create a reusable query
query = {
'y': lat_range,
'x': lon_range,
'time': time_range,
'measurements': ['red', 'green', 'blue', 'nir'],
'resolution': (-10, 10),
'output_crs': 'epsg:6933',
'group_by':'solar_day'
}

# Load available data from Sentinel-2
ds = load_ard(
dc=dc,
products=['s2_l2a'],
**query,
)

print(ds)

Using pixel quality parameters for Sentinel 2
Finding datasets
s2_l2a
Applying pixel quality/cloud mask
Loading 29 time steps
<xarray.Dataset>
Dimensions:      (time: 29, x: 339, y: 95)
Coordinates:
* time         (time) datetime64[ns] 2018-01-02T08:53:30 ... 2018-05-22T08:...
* y            (y) float64 2.837e+06 2.837e+06 ... 2.836e+06 2.836e+06
* x            (x) float64 2.75e+06 2.75e+06 2.75e+06 ... 2.753e+06 2.753e+06
spatial_ref  int32 6933
Data variables:
red          (time, y, x) float32 1144.0 2468.0 3684.0 ... 4796.0 4832.0
green        (time, y, x) float32 1010.0 1874.0 2602.0 ... 3322.0 3292.0
blue         (time, y, x) float32 377.0 954.0 1448.0 ... 2096.0 2098.0
nir          (time, y, x) float32 4616.0 4716.0 5036.0 ... 5660.0 5692.0
Attributes:
crs:           epsg:6933
grid_mapping:  spatial_ref


Once the load is complete, we can plot some of the images as as a true-colour image using the rgb function.

[7]:

rgb(ds, index=[0,5,10], col_wrap=1, size=3)


Compute band indices¶

This study measures the presence of vegetation through either the normalised difference vegetation index (NDVI) or the enhanced vegetation index (EVI). The index that will be used is dictated by the veg_proxy parameter that was set in the “Analysis parameters” section.

The normalised difference vegetation index (NDVI) requires the red and nir (near-infra red) bands. The formula is

\begin{split}\begin{aligned} \text{NDVI} & = \frac{(\text{NIR} - \text{Red})}{(\text{NIR} + \text{Red})} \\ \end{aligned}\end{split}

The Enhanced Vegetation Index requires the red, nir and blue bands. The formula is

\begin{split}\begin{aligned} \text{EVI} & = \frac{2.5 \times (\text{NIR} - \text{Red})}{(\text{NIR} + 6 \times \text{Red} - 7.5 \times \text{Blue} + 1)} \\ \end{aligned}\end{split}

Both indices are available through the calculate_indices function, imported from deafrica_bandindices.py. Here, we use collection='s2' since we’re working with Sentinel-2 data.

[8]:

# Calculate the chosen vegetation proxy index and add it to the loaded data set
ds = calculate_indices(ds, index=veg_proxy, collection='s2')


The vegetation proxy index should now appear as a data variable, along with the loaded measurements, in the ds object.

Plot the vegetation index over time¶

To get an idea of how the vegetation health changes throughout the year(s), we can plot a zonal time series over the region of interest. First we will do a simple plot of the zonal mean of the data.

[9]:

ds.NDVI.mean(['x', 'y']).plot.line('b-^', figsize=(11,4))
plt.title('Zonal mean of vegetation timeseries');


Interpolate vegetation time-series¶

Due to the infrequency of satellite passes or the presence of cloud obscuring the ground, our data may have gaps. Xarray has inbuilt methods such as .interpolate_na() to complete a time-series. While these functions are great for small datasets, they can become prohibitively slow at scale. DE Africa’s custom function fast_completion will remove any NaNs (Not a Number) very quickly, even over relatively large datasets.

We will test both methods below.

[10]:

#fill missing values using xarray's interpolate_na() method
ds.NDVI.interpolate_na(dim='time', method='linear').mean(['x', 'y']).plot.line('b-^', figsize=(11,4))

plt.title('Interpolated vegetation timeseries');


Alternatively, lets complete the timeseries using the DE Africa function deafrica_temporal_statistics.fast_complete()

[11]:

# complete timeseries using fast_completion
ndvi = ts.fast_completion(ds.NDVI)

# # plot the result
ndvi.mean(['x','y']).plot.line('b-^', figsize=(11,4));


Smoothing vegetation time-series¶

We may also wish to smooth a time series to remove noise. This can be accomplished in a number of ways, two of which we explore here. 1. By calculating a xarray.rolling mean() over a specified window-size. 2. By applying the deafrica_temporal_statistcs.smooth() function, which relies on the scipy.signal.wiener filter.

Below we will demonstrate this by first calculating a rolling mean across every three time steps. The larger the window-size, the smoother the curve will be, but at the cost of more granular detail in the curve.

[12]:

#smooth the data
ndvi_rolling = ndvi.mean(['x', 'y']).rolling(time=3, min_periods=1).mean()

#plot the smoothed data
ndvi_rolling.plot.line('b-^', figsize=(11, 4))
plt.title('Rolling mean vegetation time-series');


Alternatively, lets smooth the timeseries using deafrica_temporal_statistcs.smooth()

[13]:

#smooth the data
ndvi_smooth = ts.smooth(ndvi)

#plot the smoothed data
ndvi_smooth.mean(['x', 'y']).plot.line('b-^', figsize=(11,4))
plt.title("Wiener smoothed vegetation time-series");


Calculate phenology statistics using xr_phenology¶

The DE Africa function xr_phenology can calculate a number of land-surface phenology statistics that together describe the characteristics of a plant’s lifecycle. The function can calculate the following statistics on either a zonal timeseries (like the one above), or on a per-pixel basis:

SOS = DOY of start of season
POS = DOY of peak of season
EOS = DOY of end of season
vSOS = Value at start of season
vPOS = Value at peak of season
vEOS = Value at end of season
Trough = Minimum value of season
LOS = Length of season (DOY)
AOS = Amplitude of season (in value units)
ROG = Rate of greening
ROS = Rate of senescence


where DOY = day-of-year (Jan 1st = 0, Dec 31st = 365). By default the function will return all the statistics as an xarray.Dataset, to return only a subset of these statistics pass a list of the desired statistics to the function e.g. stats=['SOS', 'EOS', 'ROG'].

The xr_phenology function also allows for interpolating and/or smoothing the time-series in the same way as we did above, the interpolating/smoothing will occur before the statistics are calculated.

See the deafrica_temporal_statistics script for more information on each of the parameters in xr_phenology.

Zonal phenology statistics¶

To help us understand what these statistics refer too, lets first pass the simpler zonal mean (mean of all pixels in the image) time-series to the function and plot the results on the same curves as above.

[14]:

#calculate phenology on the zonal mean of the dataset
zonal_phen = ts.xr_phenology(
ds.NDVI.mean(['x', 'y']),
stats=['SOS', 'POS', 'EOS', 'vSOS', 'vPOS', 'vEOS'],
method_sos="first",
method_eos="last",
complete="linear",
smoothing="rolling_mean")

print(zonal_phen)

Completing using linear interp...
Smoothing with rolling mean...
Phenology...
POS
EOS
vSOS
vPOS
vEOS
<xarray.Dataset>
Dimensions:      ()
Coordinates:
spatial_ref  int32 6933
Data variables:
SOS          int16 2
POS          int16 82
EOS          int16 142
vSOS         float32 0.11271699
vPOS         float32 0.6186268
vEOS         float32 0.14192706


Plot the results with our statistcs annotated on the plot

[15]:

# Use DOY results to create a datetime object
year = str(ds.time.dt.year.values[0]) + " "
eos_dt = dt.datetime.strptime(year + str(zonal_phen.EOS.values), '%Y %j')
sos_dt = dt.datetime.strptime(year + str(zonal_phen.SOS.values), '%Y %j')
pos_dt = dt.datetime.strptime(year + str(zonal_phen.POS.values), '%Y %j')

#create plot
fig, ax = plt.subplots(figsize=(11, 4))
ax.plot(ndvi_rolling.time, ndvi_rolling, 'b-^')

#add start of season
ax.plot(sos_dt, zonal_phen.vSOS, 'or')
ax.annotate('SOS',
xy=(sos_dt, zonal_phen.vSOS.values),
xytext=(-15, 20),
textcoords='offset points',
arrowprops=dict(arrowstyle='-|>'))

#add end of season
ax.plot(eos_dt, zonal_phen.vEOS, 'or')
ax.annotate('EOS',
xy=(eos_dt, zonal_phen.vEOS.values),
xytext=(0, 20),
textcoords='offset points',
arrowprops=dict(arrowstyle='-|>'))

#add peak of season
ax.plot(pos_dt, zonal_phen.vPOS, 'or')
ax.annotate('POS',
xy=(pos_dt, zonal_phen.vPOS.values),
xytext=(-10, -25),
textcoords='offset points',
arrowprops=dict(arrowstyle='-|>'))

plt.ylabel('NDVI')
plt.title('Phenology statistics');


Per-pixel phenology statistics¶

We can now calculate the statistics for every pixel in our time-series and plot the results. In the code below we have changed the method_eos and method_sos parameters to 'median', this will estimate the beginning and end of the growing seasons as the median value of the slopes on the each side of the curve. The code below also demonstrates using the fast_complete and wiener methods for gap-filling and smoothing.

[16]:

#calculate phenology stats on every pixel in dataset
phen = ts.xr_phenology(
ds.NDVI,
method_sos='median',
method_eos='median',
complete='fast_complete',
smoothing='wiener'
).compute()

print(phen)

Completing using fast_complete...
Smoothing with wiener filter...
Phenology...
POS
EOS
Trough
vSOS
vPOS
vEOS
LOS
AOS
ROG
ROS
<xarray.Dataset>
Dimensions:      (x: 339, y: 95)
Coordinates:
* x            (x) float64 2.75e+06 2.75e+06 2.75e+06 ... 2.753e+06 2.753e+06
* y            (y) float64 2.837e+06 2.837e+06 ... 2.836e+06 2.836e+06
spatial_ref  int32 0
Data variables:
SOS          (y, x) int16 37 37 17 17 17 17 17 22 ... 67 17 47 82 82 22 72
POS          (y, x) int16 62 57 62 62 62 62 62 ... 107 107 107 107 107 107
EOS          (y, x) int16 102 97 97 77 77 97 97 ... 122 122 137 122 137 112
Trough       (y, x) float32 0.07334648 0.059050594 ... 0.048475552
vSOS         (y, x) float32 0.5318587 0.28643623 ... 0.07736354 0.077122964
vPOS         (y, x) float32 0.69627666 0.49028707 ... 0.09525073 0.09156355
vEOS         (y, x) float32 0.19818656 0.16363567 ... 0.08647453 0.086437546
LOS          (y, x) int16 65 60 80 60 60 80 80 45 ... 70 105 75 55 40 115 40
AOS          (y, x) float32 0.6229302 0.43123648 ... 0.046651375 0.043088
ROG          (y, x) float32 0.0065767188 0.010192542 ... 0.00041258824
ROS          (y, x) float32 -0.012452253 -0.008166285 ... -0.0010252019
Attributes:
grid_mapping:  spatial_ref


The phenology statistics have been calculated seperately for every pixel in the image. Let’s plot each of them to see the results.

[17]:

# set up figure
fig, ax = plt.subplots(nrows=5,
ncols=2,
figsize=(16, 13),
sharex=True,
sharey=True)

# set colorbar size
cbar_size = 0.7

# set aspect ratios
for a in fig.axes:
a.set_aspect('equal')

# start of season
phen.SOS.plot(ax=ax[0, 0],
cmap='magma_r',
vmax=300,
vmin=0,
cbar_kwargs=dict(shrink=cbar_size, label=None))
ax[0, 0].set_title('Start of Season (DOY)')
phen.vSOS.plot(ax=ax[0, 1],
cmap='YlGn',
vmax=0.8,
cbar_kwargs=dict(shrink=cbar_size, label=None))
ax[0, 1].set_title(veg_proxy+' at SOS')

# peak of season
phen.POS.plot(ax=ax[1, 0],
cmap='magma_r',
vmax=300,
vmin=0,
cbar_kwargs=dict(shrink=cbar_size, label=None))
ax[1, 0].set_title('Peak of Season (DOY)')
phen.vPOS.plot(ax=ax[1, 1],
cmap='YlGn',
vmax=0.8,
cbar_kwargs=dict(shrink=cbar_size, label=None))
ax[1, 1].set_title(veg_proxy+' at POS')

# end of season
phen.EOS.plot(ax=ax[2, 0],
cmap='magma_r',
vmax=300,
vmin=0,
cbar_kwargs=dict(shrink=cbar_size, label=None))
ax[2, 0].set_title('End of Season (DOY)')
phen.vEOS.plot(ax=ax[2, 1],
cmap='YlGn',
vmax=0.8,
cbar_kwargs=dict(shrink=cbar_size, label=None))
ax[2, 1].set_title(veg_proxy+' at EOS')

# Length of Season
phen.LOS.plot(ax=ax[3, 0],
cmap='magma_r',
vmax=300,
vmin=0,
cbar_kwargs=dict(shrink=cbar_size, label=None))
ax[3, 0].set_title('Length of Season (DOY)')

# Amplitude
phen.AOS.plot(ax=ax[3, 1],
cmap='YlGn',
vmax=0.8,
cbar_kwargs=dict(shrink=cbar_size, label=None))
ax[3, 1].set_title('Amplitude of Season')

# rate of growth
phen.ROG.plot(ax=ax[4, 0],
cmap='coolwarm_r',
vmin=-0.02,
vmax=0.02,
cbar_kwargs=dict(shrink=cbar_size, label=None))
ax[4, 0].set_title('Rate of Growth')

# rate of Sensescence
phen.ROS.plot(ax=ax[4, 1],
cmap='coolwarm_r',
vmin=-0.02,
vmax=0.02,
cbar_kwargs=dict(shrink=cbar_size, label=None))
ax[4, 1].set_title('Rate of Senescence')

plt.tight_layout();


Advanced: Calculating generic temporal statistics¶

In addition to the xr_phenology function, the DE Africa deafrica_temporal_statistics script contains another function for calculating generic time-series statistics, temporal_statistics. This function is built upon the hdstats library (a library of multivariate and high-dimensional statistics algorithms). This function accepts a 2 or 3D time-series of, for example, NDVI, and computes a number of summary statistics including: - discordance - discrete fourier transform coefficients (mean, std, and median) - median change - absolute change - complexity - central difference - number of peaks (very slow to run)

Below we will calculate a number of these statistics and plot them.

[18]:

statistics = ['discordance',
'f_mean',
'median_change',
'abs_change',
'complexity',
'central_diff']

ts_stats = ts.temporal_statistics(ds.NDVI, statistics)
print(ts_stats)

Completing...
Statistics:
discordance
f_mean
median_change
abs_change
complexity
central_diff
<xarray.Dataset>
Dimensions:        (x: 339, y: 95)
Coordinates:
* x              (x) float64 2.75e+06 2.75e+06 ... 2.753e+06 2.753e+06
* y              (y) float64 2.837e+06 2.837e+06 ... 2.836e+06 2.836e+06
Data variables:
discordance    (y, x) float32 0.04402538 -0.10557054 ... -0.2674018
f_mean_n1      (y, x) float32 1.5051695 0.84262234 ... 0.05562242 0.054607
f_mean_n2      (y, x) float32 0.39698583 0.24259503 ... 0.031354114
f_mean_n3      (y, x) float32 0.70754516 0.5903809 ... 0.025843346
median_change  (y, x) float32 -0.0007096678 -0.0012839809 ... -3.0945987e-05
abs_change     (y, x) float32 0.09669202 0.09073677 ... 0.00680635
complexity     (y, x) float32 11.885743 27.511564 ... 37.853767 29.473335
central_diff   (y, x) float32 0.0017447354 0.0010381076 ... -0.00018363212

[19]:

# set up figure
fig, axes = plt.subplots(nrows=4,
ncols=2,
figsize=(16, 13),
sharex=True,
sharey=True)

# set colorbar size
cbar_size = 0.5

# set aspect ratios
for a in fig.axes:
a.set_aspect('equal')

# set colorbar size
cbar_size = 0.7
stats = list(ts_stats.data_vars)

#plot
for ax,stat_1,stat_2 in zip(axes, stats[0:4], stats[4:8]):
ts_stats[stat_1].plot(ax=ax[0],cmap='cividis',cbar_kwargs=dict(shrink=cbar_size, label=None))
ax[0].set_title(stat_1)

ts_stats[stat_2].plot(ax=ax[1],cmap='plasma',cbar_kwargs=dict(shrink=cbar_size, label=None))
ax[1].set_title(stat_2)

plt.tight_layout();


Conclusions¶

In the example above, we can see these four fields are following the same cropping schedule and are therefore likely the same species of crop. We can also observe intra-field differences in the rates of growth, and in the NDVI values at different times of the season, which may be attributable to differences in soil quality, watering intensity, or other farming practices.

Phenology statistics are a powerful way to summarise the seasonal cycle of a plant’s life. Per-pixel plots of phenology can help us understand the timing of vegetation growth and sensecence across large areas and across diverse plant species as every pixel is treated as an independent series of observations. This could be important, for example, if we wanted to assess how the growing seasons are shifting as the climate warms.

Next steps¶

When you’re done, if you wish to run this code for another region, return to the “Analysis parameters” cell, modify some values (e.g. time_range, or lat/lon) and rerun the analysis.

For advanced users, xr_phenology could be used for generating phenology feature layers in a machine learning classifier (see Machine Learning with ODC for example of running ML models with ODC data). xr_phenology can be passed inside of the custom_func parameter in the deafrica_classificationtools.collect_training_data() function, allowing phenological statistics to be computed during the collection of training data. An example would look like this:

import sys
sys.path.append('../Scripts')
from deafrica_temporal_statistics import xr_phenology
from deafrica_classificationtools import collect_training_data

def phenology_stats(da):
stats = xr_phenology(da, complete='fast_complete')
return stats

training = collect_training_data(...,
custom_func=phenology_stats)


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:

[20]:

print(datacube.__version__)

1.8.4.dev52+g07bc51a5


Last Tested:

[21]:

from datetime import datetime
datetime.today().strftime('%Y-%m-%d')

[21]:

'2021-04-19'