Skip to content

API Documentation

This part of the project documentation focuses on an information-oriented approach. Use it as a reference for the technical implementation of the Spectral Recovery project code.

src.spectral_recovery.indices

Methods for computing spectral indices.

Most functions are decorated with compatible_with and requires_bands decorators, which check that the input stack is compatible with the function and that the stack contains the required bands.

Most notably, exports the compute_indices function, which computes a stack of spectral indices from a stack of images and str of index names.

compute_indices(image_stack, indices, constants={}, **kwargs)

Compute spectral indices using the spyndex package.

Parameters:

Name Type Description Default
image_stack DataArray

stack of images.

required
indices list of str

list of spectral indices to compute

required
constants dict of flt

constant and value pairs e.g {"L": 0.5}

{}
kwargs dict

Additional kwargs for wrapped spyndex.computeIndex function.

{}
Returns
required

src.spectral_recovery.metrics

Methods for computing recovery metrics.

dnbr(ra, params={'timestep': 5})

Per-pixel dNBR.

The absolute change in a spectral index’s value at a point in the restoration monitoring window from the start of the restoration monitoring window. The default is the change that has occurred 5 years into the restoration from the start of the restoration.

Parameters:

Name Type Description Default
ra RestorationArea

The restoration area to compute dnbr for.

required
params Dict

Parameters to customize metric computation. dnbr uses the 'timestep' parameter with default = {"timestep": 5}

{'timestep': 5}

Returns:

Name Type Description
dnbr_v DataArray

DataArray containing the dNBR value for each pixel.

r80p(ra, params={'percent_of_target': 80, 'timestep': 5})

Per-pixel R80P.

The extent to which the trajectory has reached 80% of the recovery target value. The metric commonly uses the maximum value from the 4th or 5th year of restoration window to show the extent to which a pixel has reached 80% of the target value 5 years into the restoration window. However for monitoring purposes, this tool uses the selected timestep or defaults to the current timestep to provide up to date recovery progress. 80% of the recovery target value is the default, however this can be changed by modifying the value of percent.

Parameters:

Name Type Description Default
ra RestorationArea

The restoration area to compute r80p for.

required
params Dict

Parameters to customize metric computation. r80p uses the 'timestep' and 'percent_of_target' parameters with default = {"percent_of_target": 80, "timestep": 5}.

{'percent_of_target': 80, 'timestep': 5}

Returns:

Name Type Description
r80p_v DataArray

DataArray containing the R80P value for each pixel.

register_metric(f)

Add function and name to global name/func dict

rri(ra, params={'timestep': 5})

Per-pixel RRI.

A modified version of the commonly used RI, the RRI accounts for noise in trajectory by using the maximum from the 4th or 5th year in monitoring window. The metric relates recovery magnitude to disturbance magnitude, and is the change in index value in 4 or 5 years divided by the change due to disturbance.

Parameters:

Name Type Description Default
ra RestorationArea

The restoration area to compute r80p for.

required
params Dict

Parameters to customize metric computation. r80p uses the 'timestep' and 'use_dist_avg' parameters with default = {"timestep": 5}.

{'timestep': 5}

Returns:

Name Type Description
rri_v DataArray

DataArray containing the RRI value for each pixel.

y2r(ra, params={'percent_of_target': 80})

Per-pixel Y2R.

The length of time taken (in time steps/years) for a given pixel to first reach 80% of its recovery target value. The percent can be modified by changing the value of percent.

Parameters:

Name Type Description Default
ra RestorationArea

The restoration area to compute r80p for.

required
params Dict

Parameters to customize metric computation. r80p uses the 'percent_of_target' parameter with default = {"percent_of_target": 80}

{'percent_of_target': 80}

Returns:

Name Type Description
y2r_v DataArray

DataArray containing the number of years taken for each pixel to reach the recovery target value. NaN represents pixels that have not yet reached the recovery target value.

year_dt(dt, dt_type='int')

Get int or str representation of year from datetime-like object.

yryr(ra, params={'timestep': 5})

Per-pixel YrYr.

The average annual recovery rate relative to a fixed time interval during the restoration monitoring window. The default is the first 5 years of the restoration window, however this can be changed by specifying the parameter timestep.

Parameters:

Name Type Description Default
ra RestorationArea

The restoration area to compute yryr for.

required
params Dict

Parameters to customize metric computation. yryr uses the 'timestep' parameter with default = {"timestep": 5}

{'timestep': 5}

Returns:

Name Type Description
yryr_v DataArray

DataArray containing the YrYr value for each pixel.

src.spectral_recovery.plotting

HandlerFilledBetween

Bases: HandlerPatch

Custom Patch Handler for trajectory windows.

Draws Patch objects with left and right edges coloured/dashed to match the style of trajectory window Patches in the plots.

plot_ra(ra, reference_start, reference_end, path=None, legend=True)

Create spectral trajectory plot of the RestorationArea (ra)

Parameters:

Name Type Description Default
ra RestorationArea

The restoration area to plot.

required
path str

The path to save the plot to.

None

plot_spectral_trajectory(timeseries_data, restoration_polygons, recovery_target, reference_start=None, reference_end=None, path=None)

Plot the spectral trajectory of the restoration polygon

Parameters:

Name Type Description Default
timeseries_data DataArray

Timeseries data (annual composites)

required
restoration_polygons GeoDataFrame

Restoration polygon and dates

required
indices list of str

Indices to visualize trajectory for

required
indices_constants dict

Constant values for indices

required
recovery_target_method callable

Recovery target method to derive recovery target values

required

src.spectral_recovery.restoration

Restoration Area class and helper methods.

The RestorationArea class coordinates the spectral data, dates, polygons, and recovery target logic/computation, that is used to fully define a restoration area. The expectation is for RestorationArea instances to be passed to recovery metric methods, so that each method can have encapsulated access to relevant restoration site information.

RestorationArea

A Restoration Area (RA).

A RestorationArea object validates and holds the locations, spectral data, dates, and recovery target(s) that define a restoration area.

Attributes:

Name Type Description
full_timeseries DataArray

A 4D (band, time, y, x) DataArray of images.

timeseries_start datetime

The first year of the timeseries.

timeseries_end datetime

The last year of the timeseries.

restoration_site GeoDataFrame

The spatial deliniation of the restoration event. There must only be one geometry in the GeoDataframe and it must be of type shapely.Polygon or shapely.MultiPolygon.

disturbance_start str

The start year of the disturbance window.

restoration_start str

The start year of the restoration window.

restoration_image_stack DataArray

The image stack which fully contains the restoration site. Derived (clipped) from full_timeseries. This is the stack used by recovery metric methods when computing metrics.

recovery_target DataArray

The recovery target values.

disturbance_start: str property

Start year of the disturbance window.

A str taken from first column of the restoration_site geopandas.GeoDataFrame. Represents the start year of the disturbance window. Must be within the temporal range of the full_timeseries property.

Raises:

Type Description
ValueError
  • If disturbance start year greater than restoration year.
  • If disturbance start year is not within temporal range of full_timeseries.

recovery_target: xr.DataArray property writable

Recovery target of the RestorationArea.

restoration_image_stack: xr.DataArray property

Restoration image stack.

The image stack containing the restoration site. Clipped to the bounding box of the restoration polygon.

restoration_site: gpd.GeoDataFrame property writable

Restoration site GeoDataFrame

GeoDataFrame contains a Shapely.Polygon and 2 or 4 str columns. Polygon defines the area of the restoration site while attributes define the disturbance start, restoration start, reference end, and reference start years respectively.

restoration_start: str property

Start year of the restoration window.

A str taken from second column of the restoration_site geopandas.GeoDataFrame. Represents the start year of the restoration window. Must be within the temporal range of the full_timeseries property.

Raises:

Type Description
ValueError
  • If restoration start year less than disturbance start year.
  • If restoration start year is not within temporal range of full_timeseries.

timeseries_end: np.datetime64 property

The final year of the timeseries

timeseries_start: np.datetime64 property

The first year of the timeseries

src.spectral_recovery.targets

Methods for computing recovery targets

median_target(polygon, timeseries_data, reference_start, reference_end, scale)

Median target method parameterized on scale.

Sequentially computes the median over time and, optionally, the spatial dimensions (x and y). If there is a "poly_id" dimension, representing each individual polygon in a multi-polygon reference input, then the median is automatically computed along that dimension after the time and space dimensions. This results in a single target value for each band, based on the time, y, x and poly_id dims.

Parameters:

Name Type Description Default
polygon GeoDataFrame

The polygon/area to compute a recovery target for.

required
timeseries_data DataArrah

The timeseries of indices to derive the recovery target from. Must contain band, time, y, and x dimensions.

required
reference_start str

Start year of reference window. Must exist in timeseries_data's time coordinates.

required
reference_end str

End year of reference window. Must exist in timeseries_data's time coordinates.

required
scale (polygon, pixel)

The scale to compute target for. Either 'polygon' which results in one value per-band (median of the polygon(s) across time), or 'pixel' which results in a value for each pixel per-band (median of each pixel across time).

if not ((scale == "polygon") or (scale == "pixel")): raise ValueError(f"scale must be 'polygon' or 'pixel' ('{scale}' provided)") self.scale = scale

"polygon"

Returns:

Name Type Description
median_t DataArray

DataArray of the median recovery target. If scale="polygon", then median_t has dimensions "band" and optionally, "poly_id". If scale="pixel", has dimensions "band", "y" and "x" and optionally, "poly_id".

window_target(polygon, timeseries_data, reference_start, reference_end, N=3, na_rm=False)

Windowed recovery target method, parameterized on window size.

The windowed method first computes the median along the time dimension and then for each pixel p in the restoration site polygon, computes the mean of a window of NxN pixels centred on pixel p, setting the mean to the recovery target value.

Implementation is based on raster focal method in R.

Parameters:

Name Type Description Default
polygon GeoDataFrame

The polygon/area to compute a recovery target for.

required
timeseries_data DataArrah

The timeseries of indices to derive the recovery target from. Must contain band, time, y, and x dimensions.

required
reference_start str

Start year of reference window. Must exist in timeseries_data's time coordinates.

required
reference_end str

End year of reference window. Must exist in timeseries_data's time coordinates.

required
N int

Size of the window (NxN). Must be odd. Default is 3.

3

src.spectral_recovery.io.raster

Functions for reading and writing raster data .

Handles reading timeseries of TIFs into a single DataArray, ensures band names and attributes are consistent. Also handles writing.

read_timeseries(path_to_tifs, band_names=None, path_to_mask=None, array_type='dask')

Reads and stacks a list of tifs into a 4D DataArray.

Parameters:

Name Type Description Default
path_to_tifs list of str

List of paths to TIFs or path to directory containing TIFs.

required
band_names dict

Dictionary mapping band numbers to band names. If not provided, band names will be read from the TIFs band descriptions.

None
path_to_mask str

Path to a 2D data mask to apply over all TIFs.

None
array_type (dask, numpy)

The type of array to use store data, either numpy or dask. NumPy arrays will be loaded into memory while Dask arrays will be lazily evaluated until being explicitly loaded into memory with a .compute() call. Default is "numpy".

"dask"

Returns:

Name Type Description
stacked_data DataArray

A 4D DataArray containing all rasters passed in path_to_tifs and optionally masked. The 'band' dimension coordinates will be either enums.Index or enums.BandCommon types, and 'time' dimension will be datetime object dervied from the filename.

Notes

Files must be named in the format 'YYYY.tif' where 'YYYY' is a valid year.

src.spectral_recovery.io.polygon

read_restoration_polygons(path, disturbance_start=None, restoration_start=None)

Read restoration polygons

A loose wrapper of the geopandas.read_file function. If check_dates=True then this function will check that the vector file at path contains 2 or 4 columns containing str or int values (the restoration site dates).

Parameters:

Name Type Description Default
path str

path to restoration polygon vector file

required

src.scripts.cli

cli(ctx, tif_dir, rest_poly, out, reference=None, indices=None, mask=None)

Compute recovery metrics.

This script will compute recovery metrics over the area of REST_POLY using spectral data from annual composites in TIF_DIR. Recovery targets will be derived over REF_POLYGON between reference start and end year.

 TIF_DIR Path to a directory containing annual composites. OUT Path to directory to write output rasters. REST_POLY Path to the restoration area polygon. REFERNCE (optional) Path to reference polygon(s).