Commit 1ba605f4 authored by Florian de Boissieu's avatar Florian de Boissieu
Browse files

add vignette to package

parent 74a291ce
......@@ -3,13 +3,12 @@ Title: DiversityMappR: an R package for α- and β-diversity mapping using remot
Version: 0.0.0.9000
Authors@R: c( person("Jean-Baptiste", "Feret", email = "jb.feret@teledetection.fr", role = c("aut", "cre")),
person("Florian", "de Boissieu", email = "florian.deboissieu@irstea.fr", role = c("ctb"), comment = "clean code, format as package"))
Description: this packages allows processing image data based on the method described in the following publication:
Féret, J.-B., Asner, G.P., 2014. Mapping tropical forest canopy diversity using high-fidelity imaging spectroscopy. Ecol. Appl. 24, 1289–1296. https://doi.org/10.1890/13-1824.1
It expects an image file as input, with a specific data format.
ENVI HDR image with BIL interleave required
License: What license it uses
Encoding: UTF-8
License: GPL3
LazyData: true
Imports:
dissUtils,
......@@ -28,3 +27,6 @@ Imports:
vegan,
zip
RoxygenNote: 6.1.1
Suggests: knitr,
rmarkdown
VignetteBuilder: knitr
......@@ -8,3 +8,6 @@ devtools::install_git('https://gitlab.irstea.fr/jean-baptiste.feret/diversitymap
credentials = git2r::cred_user_pass("uname", getPass::getPass()))
```
# 2 Tutorial
A tutorial script can be found in `Main_DiversityMapping.R`, showing the main steps of the processing. A tutorial vignette should soon be available.
# ===============================================================================
# DiversityMappR
# ===============================================================================
# PROGRAMMERS:
#
# Jean-Baptiste FERET <jb.feret@irstea.fr>
#
# Copyright 2019/06 Jean-Baptiste FERET
#
# DiversityMappR is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>
#
# ===============================================================================
################################################################################
## DEFINE PARAMETERS FOR DATASET TO BE PROCESSED ##
################################################################################
# path (absolute or relative) for the image to process
# expected to be in ENVI HDR format, BIL interleaved
Input.Image.File = system.file('extdata', 'RASTER', 'S2A_T33NUD_20180104_Subset', package = 'DiversityMappR')
Check.Data.Format(Input.Image.File)
# convert the image using Convert.Raster2BIL if not in the proper format
Input.Image.File = Convert.Raster2BIL(Raster.Path = Input.Image.File,
Sensor = 'SENTINEL_2A',
Convert.Integer = TRUE,
Output.Directory = '~/test')
# full path for the Mask raster corresponding to image to process
# expected to be in ENVI HDR format, 1 band, integer 8bits
# expected values in the raster: 0 = masked, 1 = selected
# set to FALSE if no mask available
Input.Mask.File = FALSE
# relative or absolute path for the Directory where results will be stored
# For each image processed, a subdirectory will be created after its name
Output.Dir = 'RESULTS'
# SPATIAL RESOLUTION
# resolution of spatial units for alpha and beta diversity maps (in pixels), relative to original image
# if Res.Map = 10 for images with 10 m spatial resolution, then spatial units will be 10 pixels x 10m = 100m x 100m surfaces
# rule of thumb: spatial units between 0.25 and 4 ha usually match with ground data
# too small Spatial.Res results in low number of pixels per spatial unit, hence limited range of variation of diversity in the image
Spatial.Res = 10
# PCA FILTERING: Set to TRUE if you want second filtering based on PCA outliers to be processed. Slower
FilterPCA = TRUE
################################################################################
## Check if the image format is compatible with codes (ENVI BIL) ##
################################################################################
Check.Data.Format(Input.Image.File)
################################################################################
## DEFINE PARAMETERS FOR METHOD ##
################################################################################
nbCPU = 4
MaxRAM = 0.5
nbclusters = 50
################################################################################
## PROCESS IMAGES ##
################################################################################
# 1- Filter data in order to discard non vegetated / shaded / cloudy pixels
NDVI.Thresh = 0.5
Blue.Thresh = 500
NIR.Thresh = 1500
print("PERFORM RADIOMETRIC FILTERING")
ImPathShade = Perform.Radiometric.Filtering(Input.Image.File,Input.Mask.File,Output.Dir,
NDVI.Thresh = NDVI.Thresh, Blue.Thresh = Blue.Thresh,
NIR.Thresh = NIR.Thresh)
# 2- Compute PCA for a random selection of pixels in the raster
print("PERFORM PCA ON RASTER")
PCA.Files = Perform.PCA.Image(Input.Image.File,ImPathShade,Output.Dir,FilterPCA=TRUE,nbCPU=nbCPU,MaxRAM = MaxRAM)
# 3- Select principal components from the PCA raster
Select.Components(Input.Image.File,Output.Dir,PCA.Files,File.Open = TRUE)
################################################################################
## MAP ALPHA AND BETA DIVERSITY ##
################################################################################
print("MAP SPECTRAL SPECIES")
Map.Spectral.Species(Input.Image.File,Output.Dir,PCA.Files,nbCPU=nbCPU,MaxRAM=MaxRAM)
print("MAP ALPHA DIVERSITY")
# Index.Alpha = c('Shannon','Simpson')
Index.Alpha = c('Shannon')
Map.Alpha.Diversity(Input.Image.File,Output.Dir,Spatial.Res,nbCPU=nbCPU,MaxRAM=MaxRAM,Index.Alpha = Index.Alpha)
print("MAP BETA DIVERSITY")
Map.Beta.Diversity(Input.Image.File,Output.Dir,Spatial.Res,nbCPU=nbCPU,MaxRAM=MaxRAM)
################################################################################
## COMPUTE ALPHA AND BETA DIVERSITY FROM FIELD PLOTS ##
################################################################################
# location of the spectral species raster needed for validation
TypePCA = 'SPCA'
Dir.Raster = file.path(Output.Dir,basename(Input.Image.File),TypePCA,'SpectralSpecies')
Name.Raster = 'SpectralSpecies'
Path.Raster = file.path(Dir.Raster,Name.Raster)
# location of the directory where shapefiles used for validation are saved
vect = system.file('extdata', 'VECTOR', package = 'DiversityMappR')
Shannon.All = list()
# list vector data
Path.Vector = Get.List.Shp(vect)
Name.Vector = tools::file_path_sans_ext(basename(Path.Vector))
# read raster data including projection
RasterStack = stack(Path.Raster)
Projection.Raster = Get.Projection(Path.Raster,'raster')
# get alpha and beta diversity indicators corresponding to shapefiles
Biodiv.Indicators = Get.Diversity.From.Plots(Raster = Path.Raster, Plots = Path.Vector,NbClusters = nbclusters)
# if no name
Biodiv.Indicators$Name.Plot = seq(1,length(Biodiv.Indicators$Shannon[[1]]),by = 1)
Shannon.RS = c(Biodiv.Indicators$Shannon)[[1]]
####################################################
# write RS indicators
####################################################
# write indicators for alpha diversity
Path.Results = paste(Output.Dir,'/',basename(Input.Image.File),'/',TypePCA,'/VALIDATION/',sep='')
dir.create(Path.Results, showWarnings = FALSE,recursive = TRUE)
write.table(Shannon.RS, file = paste(Path.Results,"ShannonIndex.csv",sep=''), sep="\t", dec=".", na=" ", row.names = Biodiv.Indicators$Name.Plot, col.names= F,quote=FALSE)
Results = data.frame(Name.Vector, Biodiv.Indicators$Richness, Biodiv.Indicators$Fisher, Biodiv.Indicators$Shannon,Biodiv.Indicators$Simpson)
names(Results) = c("ID_Plot", "Species_Richness", "Fisher", "Shannon", "Simpson")
write.table(Results, file = paste(Path.Results,"AlphaDiversity.csv",sep=''), sep="\t", dec=".", na=" ", row.names = F, col.names= T,quote=FALSE)
# write indicators for beta diversity
BC_mean = Biodiv.Indicators$BCdiss
colnames(BC_mean) = rownames(BC_mean) = Biodiv.Indicators$Name.Plot
write.table(BC_mean, file = paste(Path.Results,"BrayCurtis.csv",sep=''), sep="\t", dec=".", na=" ", row.names = F, col.names= T,quote=FALSE)
---
title: "Tutorial for DiversityMappR"
author: "Jean-Baptiste Féret, Florian de Boissieu"
date: "`r Sys.Date()`"
output:
html_vignette:
number_sections: true
vignette: >
%\VignetteIndexEntry{Tutorial}
%\VignetteEngine{knitr::rmarkdown}
\usepackage[utf8]{inputenc}
---
This tutorial aims at describing the processing workflow and giving the associated code to compute $\alpha$ and $\beta$ diversity maps on an extraction of Sentinel-2 image taken over Cameroun forest. The workflow is composed of the following steps:
* define the processing parameters
* input / output files paths
* output spatial resolution
* computing options
* compute the $\alpha$ and $\beta$ diversity maps:
* compute PCA and select best components
* compute the diversity maps
* validate results comparing to field plots measurements
# Processing parameters
## Input / Output files
The input images are expected to be in ENVI HDR format, BIL interleaved. To check if the flormat is good use fucntion `Check.Data.Format`.
If not they should be converted with function `Convert.Raster2BIL`.
A mask can also be set to work on a selected part of the input image. The mask is expected to be a raster in the same format as the image (ENVI HDR), with values 0 = masked or 1 = selected. If no mask is to be used set `Input.Mask.File = FALSE`.
```
Input.Image.File = system.file('extdata', 'RASTER', 'S2A_T33NUD_20180104_Subset', package = 'DiversityMappR')
Check.Data.Format(Input.Image.File)
Input.Image.File = Convert.Raster2BIL(Raster.Path = Input.Image.File,
Sensor = 'SENTINEL_2A',
Convert.Integer = TRUE,
Output.Directory = '~/test')
Input.Mask.File = FALSE
```
The output directory defined with `Output.Dir` will contain all the results. For each image processed, a subdirectory will be automatically created after its name.
```
Output.Dir = 'RESULTS'
```
## Spatial resolution
The algorithm estimates \alpha and \beta diversity within a window, that is also the output spatial resolution. It is defined in number of pixel s of the input image with parameter `Spatial.Res`, e.g. `Spatial.Res = 10` meaning a window of 10x10 pixels. It will be the spatial resolution of the ouput rasters.
As a rule of thumb, spatial units between 0.25 and 4 ha usually match with ground data.
A Spatial.Res too small results in low number of pixels per spatial unit, hence limited range of variation of diversity in the image.
In this example, the spatial resolution of the input raster. Setting `Spatial.Res = 10` will result in diversity maps of spatial resolution 100x100m.
```
Spatial.Res = 10
```
## PCA filtering
If set to `TRUE`, a second filtering based on PCA outliers is processed.
```
FilterPCA = TRUE
```
## Computing options
The use of computing ressources can be controled with the following parameters:
* `nbCPU` controls the parallelisation of the processing,
* `MaxRAM` controls the size in GB of the input image chunks processed by each thread,
* `nbclusters` controls the number of clusters (or centroids) used in kmeans of each thread. The larger the value the longer the computation time.
```
nbCPU = 4
MaxRAM = 0.5
nbclusters = 50
```
# Main processing worflow
## Mask non vegetated / shaded / cloudy pixels
```
NDVI.Thresh = 0.5
Blue.Thresh = 500
NIR.Thresh = 1500
print("PERFORM RADIOMETRIC FILTERING")
ImPathShade = Perform.Radiometric.Filtering(Input.Image.File, Input.Mask.File, Output.Dir,
NDVI.Thresh = NDVI.Thresh, Blue.Thresh = Blue.Thresh,
NIR.Thresh = NIR.Thresh)
```
## PCA
A pixel-based PCA is run on the input image across the spectral bands to select the most interesting spectral information relative to spectral diversity and remove shaded pixels, spatial noise and sensor artefacts. This PCA band selection left to user judgement, wrinting to a file the bands to keep. The file is automatically created and ready to edit with function `Select.Components`. One band number by line is expected in this file.
For this example PCA bands 1, 2 and 5 should be kept writting the following lines in file `selected_components.txt` opened for edition:
```
1
2
5
```
Here is the code to perform PCA and select PCA bands:
```
print("PERFORM PCA ON RASTER")
PCA.Files = Perform.PCA.Image(Input.Image.File, ImPathShade, Output.Dir,
FilterPCA = TRUE, nbCPU = nbCPU, MaxRAM = MaxRAM)
print("Select PCA components for diversity estimations")
Select.Components(Input.Image.File, Output.Dir, PCA.Files, File.Open = TRUE)
```
## $\alpha$ and $\beta$ diversity maps
```
print("MAP SPECTRAL SPECIES")
Map.Spectral.Species(Input.Image.File, Output.Dir, PCA.Files,
nbCPU = nbCPU, MaxRAM = MaxRAM)
print("MAP ALPHA DIVERSITY")
# Index.Alpha = c('Shannon','Simpson')
Index.Alpha = c('Shannon')
Map.Alpha.Diversity(Input.Image.File, Output.Dir, Spatial.Res,
nbCPU = nbCPU, MaxRAM = MaxRAM, Index.Alpha = Index.Alpha)
print("MAP BETA DIVERSITY")
Map.Beta.Diversity(Input.Image.File, Output.Dir, Spatial.Res,
nbCPU = nbCPU, MaxRAM = MaxRAM)
```
# Validation
The folowing code computes $\alpha$ and $\beta$ diversity from field plots and extracts the corresponding diversity index from previouly computed rasters in order to have a validation analysis.
```
# location of the spectral species raster needed for validation
TypePCA = 'SPCA'
Dir.Raster = file.path(Output.Dir,basename(Input.Image.File),TypePCA,'SpectralSpecies')
Name.Raster = 'SpectralSpecies'
Path.Raster = file.path(Dir.Raster,Name.Raster)
# location of the directory where shapefiles used for validation are saved
vect = system.file('extdata', 'VECTOR', package = 'DiversityMappR')
Shannon.All = list() # ??
# list vector data
Path.Vector = Get.List.Shp(vect)
Name.Vector = tools::file_path_sans_ext(basename(Path.Vector))
# read raster data including projection
RasterStack = stack(Path.Raster)
Projection.Raster = Get.Projection(Path.Raster,'raster')
# get alpha and beta diversity indicators corresponding to shapefiles
Biodiv.Indicators = Get.Diversity.From.Plots(Raster = Path.Raster, Plots = Path.Vector,NbClusters = nbclusters)
# if no name
Biodiv.Indicators$Name.Plot = seq(1,length(Biodiv.Indicators$Shannon[[1]]),by = 1)
Shannon.RS = c(Biodiv.Indicators$Shannon)[[1]]
```
The tables are then written to tab-seperated files.
```
# write RS indicators
####################################################
# write indicators for alpha diversity
Path.Results = file.path(Output.Dir, basename(Input.Image.File), TypePCA, 'VALIDATION')
dir.create(Path.Results, showWarnings = FALSE, recursive = TRUE)
ShannonIndexFile <- file.path(Path.Results, "ShannonIndex.tab")
write.table(Shannon.RS, file = ShannonIndexFile, sep = "\t", dec = ".", na = " ",
row.names = Biodiv.Indicators$Name.Plot, col.names= F, quote=FALSE)
Results = data.frame(Name.Vector, Biodiv.Indicators$Richness, Biodiv.Indicators$Fisher, Biodiv.Indicators$Shannon, Biodiv.Indicators$Simpson)
names(Results) = c("ID_Plot", "Species_Richness", "Fisher", "Shannon", "Simpson")
write.table(Results, file = paste(Path.Results,"AlphaDiversity.tab",sep=''), sep="\t", dec=".", na=" ", row.names = F, col.names= T,quote=FALSE)
# write indicators for beta diversity
BC_mean = Biodiv.Indicators$BCdiss
colnames(BC_mean) = rownames(BC_mean) = Biodiv.Indicators$Name.Plot
write.table(BC_mean, file = paste(Path.Results,"BrayCurtis.csv",sep=''), sep="\t", dec=".", na=" ", row.names = F, col.names= T,quote=FALSE)
```
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment