The best way to get an introduction to the package ‘spatialwarnings’ is through our freely-available paper, which describes the scientific background behind early-warning signals, and how they can be computed with the package. The purpose of this document is to provide a more technical introduction, and answer more advanced questions/issues. Please note that if you make a significant use of our package in your work, we would appreciate that you cite the above paper.

This document assumes some basic familiarity with R code. All the required files and source code needed to build this document are available there.

A 5-minutes introduction to spatialwarnings

As ecological systems degrade along gradients, several “Early-Warning signals” have been suggested in the literature to monitor such degradation. In practice, they are indicators that measure a property of an ecological system, whose trend along a gradient (or in time) is expected to change before an abrupt shift in ecosystem condition. For example, the spatial variability (e.g. variation in vegetation cover) of a given ecosystem is expected to rise before some regime shifts.

A variety of such indicators have been suggested in the literature: the package spatialwarnings focuses on computing those that are based on spatial patterns. As a result the base type of data used by spatialwarnings are matrices (2D arrays of numbers), that typically come from raster data (e.g. aerial images). For example, using the package, we can compute the spatial variance of the following matrix, which has been suggested as a widely-applicable EWS (Guttal et al. 2009):


# Load the package and enable parallel processing
library(spatialwarnings) 
plan(multicore)

data(serengeti) # get more information on this dataset by using ?serengeti

# Extract and display matrix from one of the example datasets
example_matrix <- serengeti[[1]]
display_matrix(example_matrix)

Here, the function raw_cg_variance() can be used to compute the variance on the coarse-grained matrix:

# This function returns the coarse-grained spatial variance when fed a matrix.
# See ?raw_cg_variance for more details about its computation.
raw_cg_variance(example_matrix)
#>   variance 
#> 0.01057542

When working with indicators, we are often interested in how they change along a gradient rather than in a single value. A typical use-case is to have several aerial images (matrices), each corresponding to a given location along a gradient. The usual task is to compute indicator values on each image, and display how their values change along the gradient.

spatialwarnings provides all of what is needed for such task. By storing matrices in a list, indicators can be computed on all of them at once. In the following example, we compute the spatial variance on a list of matrices (R object serengeti), which are aerial snapshots taken along a spatial gradient of rainfall in Serengeti, Tanzania:

trend <- compute_indicator(serengeti, raw_cg_variance)
trend
#> Spatial Early-Warning: raw_cg_variance 
#> 
#>  13 matrices (size: 250x250)
#> 
#>  Mat. # variance
#>       1    0.011
#>       2    0.012
#>       3    0.015
#>       4    0.022
#>       5    0.024
#>       6    0.031
#>       7    0.034
#>       8    0.041
#>       9    0.040
#>      10    0.040
#>      11    0.054
#>      12    0.074
#>      13    0.131
#> 
#> The following methods are available: 
#> as.data.frame indictest plot summary

The package has computed the spatial variance for all matrices and displayed a text summary. We can now plot the trend along the gradient by calling the generic function plot() on the returned object. Here the example dataset is along a gradient of increasing rainfall, so we will use the rainfall values (contained in the R object serengeti.rain) as our x-axis in a trend plot:

plot(trend, along = serengeti.rain) 

Because the tree cover changes along the gradient, this may affect the indicator trends, which may then not reflect the proximity to the shift, but rather changes in cover. Using spatialwarnings, we assess whether the indicator values deviate from their null expectation (their expected value given the vegation cover). This is done by randomizing the spatial structure of the matrix, and recomputing indicator values on such matrix:

variance_test <- indictest(trend)
variance_test
#> Spatial Early-Warning: raw_cg_variance 
#> 
#>  13 matrices (size: 250x250)
#> 
#>  Mat # variance P>null    
#>      1    0.011      0 ***
#>      2    0.012      0 ***
#>      3    0.015      0 ***
#>      4    0.022      0 ***
#>      5    0.024      0 ***
#>      6    0.031      0 ***
#>      7    0.034      0 ***
#>      8    0.041      0 ***
#>      9    0.040      0 ***
#>     10    0.040      0 ***
#>     11    0.054      0 ***
#>     12    0.074      0 ***
#>     13    0.131      0 ***
#> 
#>  Null model: perm (999 null matrices used)
#>  Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1 
#> 
#> The following methods are available:
#> as.data.frame plot summary

Here all observed values of spatial variance are above their null distribution (P-value indistiguishable from zero). Again, we can plot trends and investigate how these null values compare to the indicator trends:

plot(variance_test)

The grey ribbon indicates the 0.05 and 0.95 quantiles of the null distribution (they appear as a thin grey line on the graph).

spatialwarnings allows computing any indicator following such three-step workflow. For convenience, some indicators are already included and can be computed altogether at once. For example, the spatial variance above is part of the so-called “generic indicators”, which also includes lag-1 spatial autocorrelation and skewness. We can compute and display all of them at once using the generic_sews function:


# Compute all generic indicators at once
generic_trend <- generic_sews(serengeti)

# Here we adjust and customize the plot using ggplot2 directives 
plot(generic_trend, along = serengeti.rain) + 
  geom_vline(xintercept = 733, color = "red", linetype = "dashed") +
  labs(x = "Annual rainfall",
       y = "Mean cover/indicator value",
       title = paste("Early warning signals of a shift in tree cover in", 
                     "Serengeti, Tanzania (Eby et al. 2016)"), 
       subtitle = paste("Grey ribbons indicate the 5-95% quantiles of the null", 
                        "distribution"))

Which indicators are available in spatialwarnings?

spatialwarnings implements the following indicators found in the literature:

  • lag-1 autocorrelation (Moran’s I, Dakos et al. 2010)
  • Variance (Guttal et al. 2008)
  • Skewness (Guttal et al. 2008)
  • SDR Ratio (Kéfi et al. 2014)
  • Patch-size distribution shape (Kéfi et al. 2011)
  • Power-law range (Berdugo et al. 2017)
  • Flowlength (Rodriguez et al. 2017)
  • Kolmogorov complexity (Dakos et al. 2017)

A complete list of the related functions can be found by accessing the package help main page, using ?spatialwarnings.

Do not hesitate to get in touch through Github if you want to see this list grow! Implementing your own indicator is also relatively easy, allowing you to easily try out new spatial metrics (see further down in this document).

What do the reported P-values mean?

The choice made in spatialwarnings is to report P-values that are low when the indicator value is above the null distribution. This is motivated by the fact that most indicators tend to have increasing values near a possible transition. For example, a P-value of 0.01 means that the observed indicator value is above 99% of the values observed in the null distribution.

However, using this convention means that indicators which are expected to show significant deviation when below their corresponding null distribution will show apparently non-significant P-values (i.e. close to one).

spatialwarnings is slow !

While a best effort is made to make spatialwarnings as fast as possible, it relies heavily on permutating matrices and recomputing indicators, which can take a while to compute on personal computers. You can enable parallel processing to alleviate this. In that case, when computing indicators on lists of matrices, spatialwarnings will use one core per matrix. Parallel processing can be enabled using the function plan() (provided by the future framework):

plan(multisession)

Note that the future package provides many other ways to parallelize computations (e.g. across multiple computers in a cluster). For more information, please refer to the official manual.

How can I deal with missing values in the data?

Put simply, there is no single way to deal with missing values (NAs), this is why it’s up to the user of the package to deal with those before computing indicators. It depends on the meaning of those NAs.

If the matrix is has continuous values, then NAs generally represent missing measurements. In this case, interpolation may be an option, but computing indicators on interpolated data may be lead to wrong conclusions (because it increases autocorrelation in the data, which is by itself an indicator !), see e.g. this blog post.

If the matrix has discrete (TRUE/FALSE) values, then NAs may represent either (i) missing measurements, and in this case you are in the above case or (ii) a pixel that has been observed, but where the value represents the non-focal state (i.e. what should be in fact, a FALSE value). In this case, it should be safe to replace the NAs in the matrix by FALSE values.

For example, a matrix could contain TRUE values where the pixel contains forest and NA if it contains any other thing(buildings, grassland, etc.). If you are interested in the spatial dynamics of forest patches, then it should be safe to replace those NAs by FALSE values and compute indicators.

How can I add another indicator?

‘spatialwarnings’ provides the function create_indicator, which allows the user to define new indicators, and use them as if they were *_sews functions (such as generic_sews, which is used in the introduction of this document). This way we only focus on defining the spatial metric, and ‘spatialwarnings’ handles the rest for us such as testing significance or plotting results.

The process is in two steps, we first define in R a function that computes the metric. This function should take a matrix as input, and return a single, numerical value. Here, we define a function that returns the maximum patch size in a matrix.

# This function takes a matrix and a returns a single value.
get_maxpatchsize <- function(mat) {
  max(patchsizes(mat))
}

We now apply this function to a matrix or a set of matrices by passing our data and the above function to compute_indicator():

# Create the indicator function
maxpatch_indic <- compute_indicator(serengeti, get_maxpatchsize)

# Display the results as a plot
plot(maxpatch_indic, along = serengeti.rain)

Trends and significance of custom indicators can be also assessed using the generic functions plot() and indictest():

# Apply this function on the serengeti dataset. We reduce the number of
# permutations when testing significance to speed up computations. 
maxpatch_indic <- indictest(maxpatch_indic, nulln = 99)

# Display the trends, now with significance ribbons
plot(maxpatch_indic, along = serengeti.rain)

Please note that it is good practice to have an indicator function that returns values with names. Otherwise ‘spatialwarnings’ assigns default names to the returned values, such as ‘indic_1’, which appears in the previous plot. As we often work with several spatial metrics at once, this can get quickly confusing. In the snippet below we rewrite our function to return named values: these names will be used in text summaries and plots.


# This function takes a matrix and a returns a single value, but this time 
# it adds names to the returned value.
get_maxpatchsize <- function(mat) {
  c(maxpatchsize = max(patchsizes(mat)))
}
maxpatch_indic <- compute_indicator(serengeti, get_maxpatchsize)

# Display the results as a plot. The header now displays the name of the value
plot(maxpatch_indic, along = serengeti.rain)

Technical considerations

Using parameters in indicator functions

If your spatial metric requires parameters for its computation, compute_indicator() will take care of handling them for you:


# Return the estimated truncation of the patch-size distribution 
psd_quantile <- function(mat, log, q) { 
  psd <- patchsizes(mat)
  if ( log ) { 
    psd <- log10(psd)
  }
  a <- quantile(psd, q)
  names(a) <- paste0("psd_quantile_", q)
  return(a)
}

quantiles_indic <- compute_indicator(forestgap, psd_quantile, 
                                     log = TRUE, q = 0.95)

summary(quantiles_indic)
#> Spatial Early-Warning: psd_quantile 
#> 
#>  9 matrices (size: 400x400)
#> 
#>  Mat. # psd_quantile_0.95
#>       1              2.84
#>       2              0.37
#>       3              0.70
#>       4              1.40
#>       5              1.43
#>       6              1.00
#>       7              0.70
#>       8              0.48
#>       9              0.30
#> 
#> The following methods are available: 
#> 

Returning multiple values

Indicator functions can also return multiple values at once, for example, the following indicator function will work with ‘spatialwarnings’:


multi_indic_function <- function(mat) { 
  c(mean     = mean(mat), 
    sd       = sd(coarse_grain(mat, subsize = 4)), 
    coef_var = sd(coarse_grain(mat, subsize = 4)) / mean(mat))
}

multi_indics <- compute_indicator(forestgap, multi_indic_function)
summary(multi_indics)
#> Spatial Early-Warning: multi_indic_function 
#> 
#>  9 matrices (size: 400x400)
#> 
#>  Mat. #  mean    sd coef_var
#>       1 0.918 0.077    0.084
#>       2 0.805 0.111    0.137
#>       3 0.689 0.127    0.184
#>       4 0.581 0.133    0.229
#>       5 0.465 0.133    0.287
#>       6 0.344 0.126    0.367
#>       7 0.230 0.108    0.470
#>       8 0.111 0.080    0.720
#>       9 0.053 0.056    1.053
#> 
#> The following methods are available: 
#> as.data.frame indictest plot summary

If you want to distribute a new indicator with the package, do not hesitate to open a new topic on our Github tracker!

Can I use Raster* objects with ‘spatialwarnings’?

Raster* objects are used by the package raster to encapsulate raster data, for example data read from Geotiff images. These objects can contain a single band (RasterLayer objects, with one value per pixel) or multiple bands (RasterStack/RasterBrick objects, with several values per pixel). Each band of a raster object is, by definition, a matrix of values.

Base spatialwarnings cannot use RasterLayer objects directly, but a companion package spatialwarningsGis (available there) provides extensions to work with these objects. You can install the package using devtools:

devtools::install_github('spatial-ews/spatialwarningsGis')
#> Skipping install of 'spatialwarningsGis' from a github remote, the SHA1 (d2a14dda) has not changed since last install.
#>   Use `force = TRUE` to force installation
library(spatialwarningsGis)

You can now use raster objects transparently with spatialwarnings, they will be converted to matrices internally and without extra work for the user. A workflow with RasterLayer object could then look like the following:


# It makes no sense computing indicators on those images, they just are
# example geotiffs
example_files <- 
  paste0("https://download.osgeo.org/geotiff/samples/spot/chicago/", 
         c("SP27GTIF.TIF","UTM2GTIF.TIF"))

# Read the list of files using functions from the package 'raster'
list_of_raster_objects <- lapply(example_files, function(f) {
  tmpfile <- tempfile()
  download.file(f, destfile = tmpfile)
  raster(tmpfile)
})

# ...and use them in spatialwarnings
generic_sews(list_of_raster_objects)
#> Warning in fun(mat, ...): Input matrix has continous values but will be coarse-
#> grained anyway. Set subsize=1 to disable coarse graining.

#> Warning in fun(mat, ...): Input matrix has continous values but will be coarse-
#> grained anyway. Set subsize=1 to disable coarse graining.
#> Spatial Early-Warning: Generic indicators 
#> 
#>  2 matrices (size: 929x699)
#> 
#>  Mat. # variance skewness moran mean
#>       1     1177     0.68  0.64  115
#>       2     1175     0.68  0.63  115
#> 
#> The following methods are available: 
#> 

Right now some metadata of the raster object is lost in the process (extent, resolution, etc.). This information could be used by ‘spatialwarnings’ in a future release to adjust output (for example, adjust distance units when displaying the r-spectrum).

Please note that spatialwarnings will not use the multi-band objects RasterStack/RasterBrick as the implemented indicators only work with univariate values. It is unknown which band should be picked in multi-band objects to compute the indicators. You need to extract RasterLayers from these objects first, then use spatialwarnings.

Additional support for other formats representing raster data will be added to spatialwarningsGis.

How can I identify the periodicity in data?

EWS available in spatialwarnings assume that stress does not affect the periodicity of the spatial structure, as changes in periodicity may mask or alter trends in indicator values. Before computing the EWS, it is therefore needed to check for any possible periodicity in the input data. In this section, we contrast two images to show how the r-spectrum can be used to highlight periodicity (or its absence).


# Read images
image_periodic <- readPNG('./patterned_bush_niger.png')
image_nonper   <- readPNG('./non_patterned_spain.png')

# The images have three bands (R/G/B). We transform them into a black
# and white image using principal component analysis (PCA)
summarise_pca <- function(arr) {
  values <- matrix(as.vector(arr), ncol = 3)
  pca <- prcomp(values)
  values <- pca[["x"]][ ,1]
  matrix(values, ncol = ncol(arr), nrow = nrow(arr))
}

# Transform into one-band (black and white image) and compute r-spectrum.
image_periodic_pca <- summarise_pca(image_periodic)
rspec_periodic <- rspectrum(image_periodic_pca)

image_nonper_pca <- - summarise_pca(image_nonper)
rspec_nonper <- rspectrum(image_nonper_pca)

The periodic image below (tiger bush in Niger 1) displays a typical banded regular pattern (a). Its scale (in number of pixels) is reflected by a hump in the r-spectrum around a size of ~ 15px (b). This corresponds to the width of one vegetation band in the image (~30m in reality).


img <- ggplot(mat2longdf(image_periodic_pca)) +
        geom_raster(aes(x = x, y = y, fill = value)) +
        scale_fill_gradient(low = "black", high = "white") +
        scale_y_reverse() +
        theme_minimal() +
        theme(legend.position = "none") +
        labs(x = "Pixel coordinate",
            y = "Pixel coordinate",
            title = paste0(lettercount(), ") Image of periodic vegetation"))

rsp <- ggplot(rspec_periodic) +
         geom_point(aes(x = dist, y = rspec), pch = 20) +
         scale_x + scale_y +
         theme_minimal() +
         labs(x = "Distance (number of pixels)",
             y = "r-spectrum value (power)",
             title = paste0(lettercount(), ") r-spectrum of periodic image"))

gridExtra::grid.arrange(img, rsp, ncol = 2)

This image displays strong periodicity and the indicators in spatialwarnings should be used with care to draw conclusions from it.

In contrast, an aperiodic image displays no such hump in its r-spectrum. The image below (c, arid grassland in Spain) is aperiodic, as shown by the decreasing r-spectrum (d). Indicators available in spatialwarnings may (in principle) be used on this image.


img <- ggplot(mat2longdf(image_nonper_pca)) +
        geom_raster(aes(x = x, y = y, fill = value)) +
        scale_fill_gradient(low = "black", high = "white") +
        scale_y_reverse() +
        theme_minimal() +
        theme(legend.position = "none") +
        labs(x = "Pixel coordinate",
            y = "Pixel coordinate",
            title = paste0(lettercount(), ") Image of non-periodic vegetation"))

rsp <- ggplot(rspec_nonper) +
         geom_point(aes(x = dist, y = rspec), pch = 20) +
         scale_x + scale_y +
         theme_minimal() +
         labs(x = "Distance (number of pixels)",
             y = "r-spectrum value (power)",
             title = paste0(lettercount(), ") r-spectrum of non-periodic image"))

gridExtra::grid.arrange(img, rsp, ncol = 2)

Converting multi-band images

Raster images from remote sensing often come with multiple bands, because of the way images are stored digitally (with red/blue/green channels), but also because multiple sensors can be used to capture a single image (e.g. a combination of visible/near-infrared sensors). These images are sometimes represented as arrays in R (matrices that are extended with a third dimension, “depth”).

As spatialwarnings computes indicators on matrix objects, these arrays need to be first transformed into matrices (effectively arrays with depth one). This requires collapsing the multi-dimensional data of each pixel to a single value. In addition, some indicators (e.g. patch-based indicators) rely on classified, TRUE/FALSE data that define which pixels belong to a patch and which do not. The classification algorithm employed is likely to be very system-dependent, but we provide a possible example below.

In what follows, we use a small example to show how to carry these two processes and apply the spatialwarnings package on images. Using an aerial image stored as an R/G/B PNG image, we classify each pixel as vegetated/non-vegetated or summarize the multi-channel pixel values to a single numeric value. We then compute indicators on the resulting matrix.

Note that in many cases, other methods can be used to derive univariate indices from remote sensing data that may be more appropriate. For example, a typical one-dimensional index for vegetation data is NDVI (Normalized Difference Vegetation Index), which measures the extent of green vegetation in a given pixel and is obtained as the normalized difference between the red a near-infrared bands of a multi-band image.

Classifying an RGB image to compute patch-based indicators

We first load the required packages and read the image in R.


# Read image
datadir <- "../figs/images/"
img1 <- readPNG('./crau_quercus_encroachment.png')

# Display image
grid::grid.raster(img1)