diff --git a/DESCRIPTION b/DESCRIPTION index c84bddf..f2ce9bc 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -48,9 +48,7 @@ Suggests: knitr, magick, matrixStats, - raster, rmarkdown, - sp, spThin, stars, testthat (>= 3.0.0), diff --git a/R/data.R b/R/data.R index bec11a6..496da89 100644 --- a/R/data.R +++ b/R/data.R @@ -127,30 +127,6 @@ "sample_filt_data" -#' @name sample_biome_data -#' @title Biome classification raster for southern Africa. -#' @description -#' Categorical RasterLayer cropped to southern Africa at 0.08 degree resolution from OpenLandMap -#' Potential Distribution of Biomes (Hengl et al., 2018). -#' @format A RasterLayer -#' \describe{ -#' \item{class}{RasterLayer} -#' \item{dimensions}{4839, 3243, 15692877 (nrow, ncol, ncell)} -#' \item{resolution}{0.008983153, 0.008983153 (x, y)} -#' \item{extent}{11.71845, 40.85081, -47.89832, -4.428839 (xmin, xmax, ymin, ymax)} -#' \item{crs}{"+proj=longlat +datum=WGS84 +no_defs"} -#' \item{source}{biome_type_2001-01-01.tif } -#' \item{names}{biome_type_2001-01-01.tif } -#' \item{values}{Numerical categorical value ranging from 0, 255 (min, max).} -#' } -#' @docType data -#' @references -#' Hengl T, Walsh MG, Sanderman J, Wheeler I, Harrison SP, Prentice IC. (2018) Global Mapping of -#' Potential Natural Vegetation: An Assessment of Machine Learning Algorithms for Estimating Land -#' Potential. PeerJ Preprints. -"sample_biome_data" - - #' @name sample_events_data #' @title Sample e-Bird sampling event records @@ -176,7 +152,6 @@ #' \doi{10.2173/ebirdst.2020} #' #' GBIF.org (12 July 2021) GBIF Occurrence Download \doi{10.15468/dl.ppcu6q} - "sample_events_data" @@ -212,25 +187,3 @@ #' hazards infrared precipitation with stations-a new environmental record for monitoring extremes". #' Scientific Data 2, 150066. "sample_cov_data" - -#' @name sample_proj_rast -#' @title Distribution suitability projections for red-billed quelea in southern Africa -#' @description -#' RasterBrick of distribution suitability projections for red-billed quelea across southern at one -#' degree resolution for the dates: "2018-01-01", "2018-04-01", "2018-07-01" and "2018-10-01". A -#' value of 1 represents high suitability and a value of 0 low suitability. -#' @format A RasterBrick -#' \describe{ -#' \item{class}{RasterBrick} -#' \item{dimensions}{31, 30, 930, 4 (nrow, ncol, ncell, nlayers)} -#' \item{resolution}{1, 1 (x, y)} -#' \item{extent}{11.6901, 41.6901, -35.43802, -4.438023 (xmin, xmax, ymin, ymax)} -#' \item{crs}{"+proj=longlat +datum=WGS84 +no_defs"} -#' \item{source}{memory} \item{names}{ X2018.01.01_proportional, X2018.04.01_proportional, -#' X2018.07.01_proportional, X2018.10.01_proportional } -#' \item{min values}{Numerical minimum distribution suitability projected in each layer.} -#' \item{max values}{Numerical maximum distribution suitability projected in each layer.} -#' } -#' @docType data -"sample_proj_rast" - diff --git a/R/dynamic_proj.R b/R/dynamic_proj.R index a73fcb3..2a55d18 100644 --- a/R/dynamic_proj.R +++ b/R/dynamic_proj.R @@ -34,7 +34,7 @@ #' Default is "+proj=longlat +datum=WGS84". #'@param proj.prj a character string, the coordinate reference system desired for output projection #' rasters. Default is assumed to be the same as prj. -#'@param spatial.mask an object of class `Raster`, `sf` or `Spatial`, representing a mask in which +#'@param spatial.mask an object of class `SpatRaster` or`sf` polygon, representing a mask in which #' NA cells in the mask layer are removed from the projection covariates. #'@details Function projects a model object or list of model objects onto projection covariate data #' frames for each projection date given. @@ -190,8 +190,13 @@ dynamic_proj <- function(dates, # Convert mask to SPDF for use with raster::mask if (!missing(spatial.mask)) { - spatial.mask<-convert_to_sf(spatial.mask,prj) - # spatial.mask<-sf::as_Spatial(spatial.mask) + + spatial.mask <- convert_to_sf(spatial.mask, prj) + + if(inherits(spatial.mask, "sfc_POLYGON")){ + spatial.mask <- terra::vect(spatial.mask) + } + } @@ -499,7 +504,7 @@ dynamic_proj <- function(dates, binaryrast <- terra::rast(as.matrix(cbind(projection_df[, "x"], projection_df[, "y"], - SDMbinary), crs = prj), + SDMbinary)), crs = prj, type="xyz") } @@ -528,7 +533,7 @@ dynamic_proj <- function(dates, if (cov.file.type == "csv") { abundancerast <- terra::rast(as.matrix(cbind(projection_df[, "x"], projection_df[, "y"], - SAMpred), crs = prj), + SAMpred)), crs = prj, type="xyz") } @@ -554,8 +559,8 @@ dynamic_proj <- function(dates, if (cov.file.type == "csv") { proportionalrast <- terra::rast(as.matrix(cbind(projection_df[, "x"], projection_df[, "y"], - SDMpred), crs = prj), - type="xyz") + SDMpred)), crs = prj, + type = "xyz") } if (!missing(spatial.mask)) { @@ -579,7 +584,7 @@ dynamic_proj <- function(dates, if (cov.file.type == "csv") { stackedrast <- terra::rast(as.matrix(cbind(projection_df[, "x"], projection_df[, "y"], - stacked), crs = prj), + stacked)), crs = prj, type="xyz") } diff --git a/R/dynamic_proj_covariates.R b/R/dynamic_proj_covariates.R index eedddaa..8882ddd 100644 --- a/R/dynamic_proj_covariates.R +++ b/R/dynamic_proj_covariates.R @@ -4,9 +4,9 @@ #'stacked and then exported as a covariate data frame or raster stack for each projection date. #' #'@param dates a character string, vector of dates in format "YYYY-MM-DD". -#'@param spatial.ext optional; the spatial extent to crop explanatory variable rasters to. Object of -#' class `Extent`, `RasterLayer`, `sf`, `SpatialPolygonsDataFrame`, `polygon` or numeric vector -#' listing xmin, xmax, ymin and ymax in order. +#'@param spatial.ext optional; the spatial extent to crop explanatory variable +#' rasters to. Object of class `SpatExtent`, `SpatRaster`, an `sf` polygon or +#' numeric vector listing xmin, xmax, ymin and ymax in order. #'@param varnames a character string, the unique names for each explanatory variable. #'@param spatial.res.degrees optional; a numeric value, the spatial resolution in degrees for #' projection rasters to be resampled to. Required if `spatial.ext` given. @@ -24,7 +24,7 @@ #'@param save.drive.folder optional; a character string, Google Drive folder to save projection #' covariates to. Folder must be uniquely named within Google Drive. Do not provide path. #'@param cov.file.type a character string, the type of file to export projection covariates as. One -#' of: `tif` (raster stack) or `csv`(data frame). +#' of: `tif` (SpatRaster with multiple layers) or `csv`(data frame). #'@param prj a character string, the coordinate reference system desired for projection covariates. #' Default is "+proj=longlat +datum=WGS84". #'@param cov.prj a character string, the coordinate reference system desired for output projection @@ -54,9 +54,10 @@ #'date and explanatory variable name, then the function will error. #' #'# Processing rasters -#'If required, rasters are cropped and resampled to the same spatial extent and resolution. If -#'`spatial.mask` is given, then cells with NA in this mask layer are removed from the returned -#'projection covariates. See `raster::mask()` in R package `raster` for details. +#'If required, rasters are cropped and resampled to the same spatial extent and +#'resolution. If `spatial.mask` is given, then cells with NA in this mask layer +#'are removed from the returned projection covariates. See `terra::mask()` in R +#'package `terra` for details (Hijmans et al., 2022). #' #'Rasters are then stacked and reprojected if `cov.prj` is different to `prj`. #' @@ -105,7 +106,7 @@ #' #'#' # Spatial buffering of static rasters (optional) #' -#' Using the `focal` function from `raster` R package (Hijmans et al., 2015), +#' Using the `focal` function from `terra` R package (Hijmans et al., 2022), #' `GEE.math.fun` is calculated across the spatial buffer area from the record #' co-ordinate. The spatial buffer area used is specified by the argument #' `moving.window.matrix`, which dictates the neighbourhood of cells @@ -129,6 +130,9 @@ #'@returns Exports combined covariates in "csv" or "tif" file for each projection date to the local #'directory or Google Drive folder. #'@export +#'@references +#'Hijmans, R.J., Bivand, R., Forner, K., Ooms, J., Pebesma, E. and Sumner, M.D., +#'2022. Package 'terra'. Maintainer: Vienna, Austria. #'@examplesIf googledrive::drive_has_token() #' #'data("sample_extent_data") @@ -238,12 +242,6 @@ dynamic_proj_covariates <- function(dates, stop("Provide save.directory or save.drive.folder to export data.frame.") } - # If mask if sf polygon, convert to spatial polygons dataframe for raster:: mask - #if (!missing(spatial.mask)) { - ## if (any(class(spatial.mask) == "sf")) { - # spatial.mask<-sf::as_Spatial(spatial.mask) - # } - # } # Process spatial extent given for cropping rasters before stacking into covariate data frame @@ -251,20 +249,6 @@ dynamic_proj_covariates <- function(dates, if (!missing(spatial.ext)) { - if (!any(class(spatial.ext) %in% c("numeric", - "SpatialPolygonsDataFrame", - "Extent", - "RasterLayer", - "Polygon", - "SpatRaster", - "SpatExtent", - "sf"))) { - - stop("Please check spatial.ext is of the correct class") - - } - - # Numeric extent to co-ords if (is.numeric(spatial.ext) && length(spatial.ext) != 4) { @@ -436,9 +420,18 @@ dynamic_proj_covariates <- function(dates, r <- terra::setValues(r, 1:terra::ncell(r)) if(!missing(spatial.mask)) { + + if(inherits(spatial.mask, "sfc_POLYGON")){ + spatial.mask <- terra::vect(spatial.mask) + } + + if("sf" %in% class(spatial.mask)){ + spatial.mask <- terra::vect(spatial.mask) + } + # Mask to original spatial.ext, if fails keep original. Depending on spatial.ext type. tryCatch({ - r <- terra::mask(r, spatial.ext) + r <- terra::mask(r, spatial.mask) }, error = function(error_message) { r <- r message("spatial.mask could not be used. Check valid input type.") @@ -453,6 +446,16 @@ dynamic_proj_covariates <- function(dates, if (!length(static.resample.method) == 1) { raster <- terra::resample(raster, r, method = static.resample.method[sr]) } + + if(!missing(spatial.mask)) { + tryCatch({ + raster <- terra::mask(raster, spatial.mask) + }, error = function(error_message) { + raster <- raster + message("spatial.mask could not be used. Check valid input type.") + })} + + } terra::crs(raster) <- prj @@ -522,10 +525,15 @@ dynamic_proj_covariates <- function(dates, terra::res(r) <- spatial.res.degrees r <- terra::setValues(r, 1:terra::ncell(r)) + if(!missing(spatial.mask)) { + + if(inherits(spatial.mask, "sfc_POLYGON")){ + spatial.mask <- terra::vect(spatial.mask) + } # Mask to original spatial.ext, if fails keep original. Depending on spatial.ext type. tryCatch({ - r <- terra::mask(r, spatial.ext) + r <- terra::mask(r, spatial.mask) }, error = function(error_message) { r <- r message("spatial.mask could not be used. Check valid input type.") @@ -540,6 +548,17 @@ dynamic_proj_covariates <- function(dates, if (!length(resample.method) == 1) { raster <- terra::resample(raster, r, method = resample.method[v]) } + + if(!missing(spatial.mask)) { + # Mask to original spatial.ext, if fails keep original. Depending on spatial.ext type. + tryCatch({ + raster <- terra::mask(raster, spatial.mask) + }, error = function(error_message) { + raster <- raster + message("spatial.mask could not be used. Check valid input type.") + })} + + } terra::crs(raster) <- prj @@ -557,7 +576,7 @@ dynamic_proj_covariates <- function(dates, names(stack) <- varnames_all # Label each layer in stack as variable if (!prj == cov.prj) { - stack <- terra::project(stack, crs = cov.prj) + stack <- terra::project(stack, cov.prj) } cov.file.type <- match.arg(cov.file.type, choices = c("tif", "csv")) diff --git a/R/extract_buffered_coords.R b/R/extract_buffered_coords.R index aafbe0e..1275368 100644 --- a/R/extract_buffered_coords.R +++ b/R/extract_buffered_coords.R @@ -52,7 +52,7 @@ #' #' # Spatial dimension #' -#' Using the `focal` function from `raster` R package (Hijmans et al., 2015), `GEE.math.fun` is +#' Using the `focal` function from `terra` R package (Hijmans et al., 2022), `GEE.math.fun` is #' calculated across the spatial buffer area from the record co-ordinate. The spatial buffer area #' used is specified by the argument `moving.window.matrix`, which dictates the neighbourhood of #' cells surrounding the cell containing the occurrence record to include in this calculation. @@ -101,7 +101,7 @@ #' # Aggregation factor #' #' `agg.factor` given represents the factor to aggregate `RasterLayer` data with function -#' `aggregate` in `raster` R package (Hijmans et al., 2015). Aggregation uses the `GEE.math.fun` as +#' `aggregate` in `terra` R package (Hijmans et al., 2022). Aggregation uses the `GEE.math.fun` as #' the function. Following aggregation spatial buffering using the moving window matrix occurs. #' This is included to minimise computing time if data are of high spatial resolution and a large #' spatial buffer is needed. Ensure to calculate `get_moving_window()` with the spatial resolution @@ -151,9 +151,8 @@ #' D'Agostino McGowan L., and Bryan J., 2022. googledrive: An Interface to Google Drive. #' , . #' -#' Hijmans, R. J., Van Etten, J., Cheng, J., Mattiuzzi, M., Sumner, M., Greenberg, J. A., -#' Lamigueiro, O. P., Bevan, A., Racine, E. B. & Shortridge, A. 2015. Package ‘raster’. R package, -#' 734. +#'Hijmans, R.J., Bivand, R., Forner, K., Ooms, J., Pebesma, E. and Sumner, M.D., +#'2022. Package 'terra'. Maintainer: Vienna, Austria. #'@return Returns details of successful explanatory variable extractions. #'@export #'@examplesIf googledrive::drive_has_token() diff --git a/R/extract_buffered_raster.R b/R/extract_buffered_raster.R index fcc10e9..378933f 100644 --- a/R/extract_buffered_raster.R +++ b/R/extract_buffered_raster.R @@ -3,8 +3,8 @@ #'Extract rasters for spatially buffered and temporally dynamic explanatory variables at each #'projection date using Google Earth Engine. #'@param dates a character string, vector of dates in format "YYYY-MM-DD". -#'@param spatial.ext the spatial extent for the extracted raster. Object from which extent can be -#' extracted of class `Extent`, `RasterLayer`,`SpatialPolygonsDataFrame`, `sf` or `polygon` or +#'@param spatial.ext the spatial extent for the extracted raster. Object from which extent +#' can be extracted of class `SpatExtent`, `SpatRaster`, `sf` polygon or #' numeric vector listing xmin, xmax, ymin and ymax in order. #'@param datasetname a character string, the Google Earth Engine dataset to extract data from. #'@param bandname a character string, the Google Earth Engine dataset bandname to extract data for. @@ -62,7 +62,7 @@ #' #' # Spatial dimension #' -#' Using the `focal` function in `raster` R package (Hijmans et al., 2015), `GEE.math.fun` is +#' Using the `focal` function in `terra` R package (Hijmans et al., 2022), `GEE.math.fun` is #' calculated across the spatial buffer area from each cell in `spatial.ext`. The spatial buffer #' area used is defined by `moving.window matrix`, which dictates the neighbourhood of cells #' surrounding each cell in `spatial.ext` to include in the calculation. @@ -90,8 +90,8 @@ #' #' # Aggregation factor #' -#' `agg.factor` given represents the factor to aggregate `RasterLayer` data with function -#' `aggregate` in `raster` R package (Hijmans et al., 2015). Aggregation uses the `GEE.math.fun` as +#' `agg.factor` given represents the factor to aggregate `SpatRaster` data with function +#' `aggregate` in `terra` R package (Hijmans et al., 2022). Aggregation uses the `GEE.math.fun` as #' the function. Following aggregation spatial buffering using the moving window matrix occurs. #' This is included to minimise computing time if data are of high spatial resolution and a large #' spatial buffer is needed. Ensure to calculate `get_moving_window()` with the spatial resolution @@ -158,9 +158,8 @@ #' D'Agostino McGowan L., and Bryan J., 2022. googledrive: An Interface to Google Drive. #' , . #' -#' Hijmans, R. J., Van Etten, J., Cheng, J., Mattiuzzi, M., Sumner, M., Greenberg, J. A., -#' Lamigueiro, O. P., Bevan, A., Racine, E. B. & Shortridge, A. 2015. Package ‘raster’. R package, -#' 734. +#'Hijmans, R.J., Bivand, R., Forner, K., Ooms, J., Pebesma, E. and Sumner, M.D., +#'2022. Package 'terra'. Maintainer: Vienna, Austria. #'@return Returns details of successful explanatory variable raster extractions for each projection #' date. #'@export diff --git a/R/extract_dynamic_raster.R b/R/extract_dynamic_raster.R index c7714d2..b368e8c 100644 --- a/R/extract_dynamic_raster.R +++ b/R/extract_dynamic_raster.R @@ -4,7 +4,7 @@ #'Earth Engine. #'@param dates a character string, vector of dates in format "YYYY-MM-DD". #'@param spatial.ext the spatial extent for the extracted raster. Object from which extent can be -#' extracted of class `Extent`, `RasterLayer`, `SpatialPolygonsDataFrame`, `sf` or `polygon` or +#' extracted of class `SpatExtent`, `SpatRaster`, an `sf` polygon or a #' numeric vector listing xmin, xmax, ymin and ymax in order. #'@param datasetname a character string, the Google Earth Engine dataset to extract data from. #'@param bandname a character string, the Google Earth Engine dataset bandname to extract data for. diff --git a/R/extract_static_coords.R b/R/extract_static_coords.R index f9a7675..beef3ad 100644 --- a/R/extract_static_coords.R +++ b/R/extract_static_coords.R @@ -6,15 +6,15 @@ #'@param occ.data a data frame, with columns for occurrence record co-ordinates #' and dates with column names as follows; record longitude as "x", latitude as #' "y", and associated explanatory variable data. -#'@param static.rasters a RasterStack of one or more rasters to extracted data -#' from. +#'@param static.rasters a `SpatRaster` containing one or more SpatRaster layers +#' to extract data from. #'@param extraction.method a character string or vector, the methods to extract -#' data from raster using `raster` package `extract` function. One of `simple` +#' data from SpatRaster using `terra` package `extract` function. One of `simple` #' or `bilinear`. If `simple` values for the cell a point falls in are #' returned. If `bilinear` the returned values are interpolated from the values #' of the four nearest raster cells. #'@param varnames a character string or vector, the unique names for each -#' explanatory variable in order of rasters in stack. +#' explanatory variable in order of layers in the SpatRaster. #'@param GEE.math.fun optional; a character string, the mathematical function to #' compute across the specified spatial matrix for each record. #'@param moving.window.matrix optional; a matrix of weights with an odd number @@ -27,14 +27,13 @@ #' #' #'Note: -#' * `varnames` must be in the order of raster layers within the provided stack. -#' * `extraction.method` must be of length one to use for all layers, or the -#' length of nlayers(static.rasters) and in the same order as the appropriate -#' layers within the provided stack. +#' * `varnames` must be in the order of raster layers within the SpatRaster. +#' * `extraction.method` must be of length one to apply to all layers, or +#' length equal to the number of layers in `static.rasters`. #' #' # Spatial buffering (optional) #' -#' Using the `focal` function from `raster` R package (Hijmans et al., 2015), +#' Using the `focal` function from `terra` R package (Hijmans et al., 2022), #' `GEE.math.fun` is calculated across the spatial buffer area from the record #' co-ordinate. The spatial buffer area used is specified by the argument #' `moving.window.matrix`, which dictates the neighbourhood of cells @@ -59,15 +58,20 @@ #' data. #' #'@export -#' +#'@references +#'Hijmans, R.J., Bivand, R., Forner, K., Ooms, J., Pebesma, E. and Sumner, M.D., +#'2022. Package ‘terra’. Maintainer: Vienna, Austria. #'@examples #'\donttest{ #'data("sample_explan_data") -#'data("sample_biome_data") +#'random_cat_layer <- terra::rast(sample_extent_data) +#'random_cat_layer <- terra::setValues(random_cat_layer, +#' sample(0:10, terra::ncell(random_cat_layer), +#' replace = TRUE)) #' #'extract_static_coords(occ.data = sample_explan_data, -#' varnames = "biome_type", -#' static.rasters = raster::stack(sample_biome_data)) +#' varnames = "random_cat_layer", +#' static.rasters = random_cat_layer) #' #'} diff --git a/R/extract_xy_min_max.R b/R/extract_xy_min_max.R index a778b02..3023c34 100644 --- a/R/extract_xy_min_max.R +++ b/R/extract_xy_min_max.R @@ -1,5 +1,5 @@ #' extract_xy_min_max Extracts xmin,xmax,ymin,ymax from spatial extent object -#' @param x spatial extent object. Object of class "Extent", "raster" or "polygon" or numeric vector +#' @param x spatial extent object. #' listing xmin, xmax, ymin and ymax in order. #' @noRd @@ -15,10 +15,11 @@ extract_xy_min_max <- function(x) { ### Extent object to co-ords if ("Extent" %in% class(x)) { - xmin <- sp::bbox(x)[1, 1] - xmax <- sp::bbox(x)[1, 2] - ymin <- sp::bbox(x)[2, 1] - ymax <- sp::bbox(x)[2, 2] + x <- terra::ext(x) + xmin <- x[1] + xmax <- x[2] + ymin <- x[3] + ymax <- x[4] } @@ -37,10 +38,14 @@ extract_xy_min_max <- function(x) { ### Polygon object to co-ords if ("Polygon" %in% class(x)) { - xmin <- sp::bbox(x)[1, 1] - xmax <- sp::bbox(x)[1, 2] - ymin <- sp::bbox(x)[2, 1] - ymax <- sp::bbox(x)[2, 2] + stop("Please provide sf polygon.") + } + + if ("POLYGON" %in% class(x)) { + xmin <- as.numeric(sf::st_bbox(x)[1]) + xmax <- as.numeric(sf::st_bbox(x)[3]) + ymin <- as.numeric(sf::st_bbox(x)[2]) + ymax <- as.numeric(sf::st_bbox(x)[4]) } if ("sf" %in% class(x)) { @@ -50,12 +55,9 @@ extract_xy_min_max <- function(x) { ymax <- as.numeric(sf::st_bbox(x)[4]) } - if ("SpatialPolygonsDataFrame" %in% class(x)) { - xmin <- sp::bbox(raster::extent(x))[1, 1] - xmax <- sp::bbox(raster::extent(x))[1, 2] - ymin <- sp::bbox(raster::extent(x))[2, 1] - ymax <- sp::bbox(raster::extent(x))[2, 2] + if ("SpatialPolygonsDataFrame" %in% class(x)) { + stop("Please provide spatial object as an sf polygon or terra extent/r") } @@ -84,6 +86,13 @@ extract_xy_min_max <- function(x) { } + if ("sfc_POLYGON" %in% class(x)) { + xmin <- as.numeric(sf::st_bbox(x)[1]) + xmax <- as.numeric(sf::st_bbox(x)[3]) + ymin <- as.numeric(sf::st_bbox(x)[2]) + ymax <- as.numeric(sf::st_bbox(x)[4]) + } + return(c(xmin, xmax, ymin, ymax)) } @@ -100,17 +109,23 @@ convert_to_sf <- function(x,prj) { if ("numeric" %in% class(x) && length(x) == 4) { - raster<-raster::raster(raster::extent(x[1],x[2],x[3],x[4]),crs=prj) - spatial.ext <- methods::as(raster, 'SpatialPolygons') + raster<-terra::rast(terra::ext(x[1],x[2],x[3],x[4]),crs=prj) + spatial.ext <- terra::as.polygons(raster) spatial.ext<-sf::st_as_sf(spatial.ext,CRS = sf::st_crs(prj)) - } ### Extent object to co-ords - if ("Extent" %in% class(x)) { - raster <- raster::raster(raster::extent(x), crs = prj) - spatial.ext <- methods::as(raster, 'SpatialPolygons') + raster <- terra::rast(terra::ext(x), crs = prj) + spatial.ext <- terra::as.polygons(raster) + spatial.ext <- sf::st_as_sf(spatial.ext, CRS = sf::st_crs(prj)) + } + + + + if ("SpatExtent" %in% class(x)) { + raster <- terra::rast(terra::ext(x), crs = prj) + spatial.ext <- terra::as.polygons(raster) spatial.ext <- sf::st_as_sf(spatial.ext, CRS = sf::st_crs(prj)) } @@ -119,45 +134,49 @@ convert_to_sf <- function(x,prj) { ### RasterLayer object to co-ords if ("RasterLayer" %in% class(x)) { - raster::crs(x) <- prj - spatial.ext <- methods::as(x, 'SpatialPolygons') + raster <- terra::rast(x, crs = prj) + terra::crs(raster) <- prj + spatial.ext <- terra::as.polygons(raster) spatial.ext <- sf::st_as_sf(spatial.ext) spatial.ext <- sf::st_transform(spatial.ext, 7801) spatial.ext <- sf::st_union(spatial.ext) spatial.ext <- sf::st_transform(spatial.ext, prj) - } - ### Polygon object to co-ords if ("Polygon" %in% class(x)) { - xmin <- sp::bbox(x)[1, 1] - xmax <- sp::bbox(x)[1, 2] - ymin <- sp::bbox(x)[2, 1] - ymax <- sp::bbox(x)[2, 2] + stop("Please provide sf polygon") + } - raster<-raster::raster(raster::extent(xmin,xmax,ymin,ymax),crs=prj) - spatial.ext <- methods::as(raster, 'SpatialPolygons') + if ("sf" %in% class(x)) { - message("Only using extent of sp Polygon. Provide sf polygon for specific shape") + x <- sf::st_set_crs(x, prj) - spatial.ext<-sf::st_as_sf(spatial.ext) + return(x) + } + if ("POLYGON" %in% class(x)) { + polygon <- polygon %>% + sf::st_sfc(crs = prj) + x <- sf::st_set_crs(polygon, prj) + return(x) } - if ("sf" %in% class(x)) { + if ("sfc_POLYGON" %in% class(x)) { x <- sf::st_set_crs(x, prj) - return(x) } + if ("SpatialPolygonsDataFrame" %in% class(x)) { spatial.ext <- sf::st_as_sf(x) } + + return(spatial.ext) } diff --git a/R/get_moving_window.R b/R/get_moving_window.R index 98080c8..4acd49c 100644 --- a/R/get_moving_window.R +++ b/R/get_moving_window.R @@ -8,9 +8,9 @@ #' variable data. #'@param spatial.res.metres a numeric value, the spatial resolution in metres of explanatory #' variable data. -#'@param spatial.ext the spatial extent of the study. Object from which extent can be extracted of -#' class `Extent`, `RasterLayer`, `sf` or `polygon` or numeric vector listing xmin, xmax, ymin and -#' ymax in order. +#'@param spatial.ext the spatial extent of the study. Object from which extent +#' can be extracted of class `SpatExtent`, `SpatRaster`, `sf` polygon or +#' numeric vector listing xmin, xmax, ymin and ymax in order. #'@details #' #'# Importance for other functions in `dynamicSDM` To extract spatially buffered explanatory @@ -22,10 +22,13 @@ #'variable would be calculated across the nine grid cells neighbouring the cell of interest and the #'cell of interest. #' -#'# Why use a moving window matrix instead of circular buffer? The benefit of using a “moving -#'window” over calculating explanatory variable values across a set radius from each record -#'co-ordinate, is that when generating projection rasters at high spatial and temporal resolution, -#'these can be generated much faster as the “moving windows” standardise the calculation. +#'# Why use a moving window matrix instead of circular buffer? +#' +#'The benefit of using a “moving window” over calculating explanatory +#'variable values across a set radius from each record co-ordinate, is that when +#'generating projection rasters at high spatial and temporal resolution, these +#'can be generated much faster as the “moving windows” standardise the +#'calculation. #' #'# Function calculation #' @@ -72,12 +75,7 @@ get_moving_window <- function(radial.distance, stop("spatial.ext is missing. Required when spatial.res given in degrees.") } - # Check spatial.ext is valid - if (!any(class(spatial.ext) %in% c("numeric", "Extent","sf", "RasterLayer", "Polygon","SpatRaster"))) { - stop("spatial.ext must be of class numeric, Extent, sf, RasterLayer, SpatRaster or Polygon") - } - - if (any(class(spatial.ext) == "numeric") && !length(spatial.ext) == 4) { + if (any(class(spatial.ext) == "numeric") && !length(spatial.ext) == 4) { stop("spatial.ext numeric vector should be of length four c(xmin, xmax, ymin and ymax)") } diff --git a/R/spatiotemp_bias.R b/R/spatiotemp_bias.R index 5e44e8d..cb54b0d 100644 --- a/R/spatiotemp_bias.R +++ b/R/spatiotemp_bias.R @@ -33,7 +33,7 @@ #' #'# Spatial bias #' -#' To assess spatial sampling bias, the function returns a scatterplot of the spatial +#' To assess spatial sampling bias, the function returns a scatter plot of the spatial #'distribution of occurrence records to illustrate any spatial clustering (if `plot = TRUE`). The #'average nearest neighbour distance of record co-ordinates is then compared to that of records #'randomly generated at same density using a t-test, following the nearest neighbour index diff --git a/R/spatiotemp_block.R b/R/spatiotemp_block.R index 9b7afd5..72f38e8 100644 --- a/R/spatiotemp_block.R +++ b/R/spatiotemp_block.R @@ -9,7 +9,7 @@ #' "month", and day as "day", and associated explanatory variable data. #'@param vars.to.block.by a character string or vector, the explanatory variable column names to #' group sampling units based upon. -#'@param spatial.layer optional; a `RasterLayer` object, a categorical spatial layer for sample +#'@param spatial.layer optional; a `SpatRaster` object, a categorical spatial layer for sample #' unit splitting. #'@param spatial.split.degrees a numeric value, the grid cell resolution in degrees to split #' `spatial.layer` by. Required if `spatial.layer` given. diff --git a/R/spatiotemp_extent.R b/R/spatiotemp_extent.R index e6ab79a..e9dcfff 100644 --- a/R/spatiotemp_extent.R +++ b/R/spatiotemp_extent.R @@ -9,9 +9,9 @@ #'@param temporal.ext optional; a character vector, two dates in format "YYYY-MM-DD". First date #' represents start of temporal extent and second date represents end of temporal extent for #' inclusion. -#'@param spatial.ext the spatial extent to filter by. Object from which extent can be extracted of -#' class `Extent`, `RasterLayer`, `SpatialPolygonsDataFrame`,`sf` or `polygon` or numeric vector -#' listing xmin, xmax, ymin and ymax in order. +#'@param spatial.ext the spatial extent to filter by. Object from which extent +#' can be extracted of class `SpatExtent`, `SpatRaster`, `sf` polygon or +#' numeric vector listing xmin, xmax, ymin and ymax in order. #'@param prj a character string, the coordinate reference system of input `occ.data` co-ordinates. #' Default is "+proj=longlat +datum=WGS84". #'@details @@ -23,10 +23,9 @@ #'outside of this extent. #' #' -#'If `spatial.ext` object can be used as a mask by `raster::mask()` then the mask is used to filter -#'records in a more targetted way. If not, then the rectangular extent of the `spatial.ext` object -#'is used. If an `sf` polygon object is provided, this is first transformed into a `Spatial` object -#'for use by `raster::mask()`. +#'If `spatial.ext` object can be used as a mask by `terra::mask()` then the mask is used to filter +#'records in a more targeted way. If not, then the rectangular extent of the `spatial.ext` object +#'is used. #' #'# Temporal extent #' @@ -113,31 +112,22 @@ spatiotemp_extent <- function(occ.data, # Convert sf object to Spatial object that can be tranformed into raster if("sf" %in% class(spatial.ext)){ - v <- terra::vect(spatial.ext) - r <- terra::rast(v,ncols=75, nrows=100) - spatial.ext <- terra::rasterize(v, r)} - + spatial.ext <- terra::vect(spatial.ext) + } # Convert polygon object to Extent object that can be transformed into raster if ("Polygon" %in% class(spatial.ext)) { - xmin <- sp::bbox(spatial.ext)[1, 1] - xmax <- sp::bbox(spatial.ext)[1, 2] - ymin <- sp::bbox(spatial.ext)[2, 1] - ymax <- sp::bbox(spatial.ext)[2, 2] - r<- terra::ext(xmin,xmax,ymin,ymax)} - + stop("Please provide sf polygon as spatial.ext object.") + } if("RasterLayer" %in% class(spatial.ext)){ spatial.ext <- terra::rast(spatial.ext) } - if("SpatRaster" %in% class(spatial.ext)){ - spatial.ext <- terra::as.polygons(spatial.ext) + if(inherits(spatial.ext, "sfc_POLYGON")){ + spatial.ext <- terra::vect(spatial.ext) } - if(inherits(spatial.ext,"SpatExtent")){ - spatial.ext <- terra::as.polygons(terra::ext(spatial.ext))} - # Convert spatial.ext to raster in same projection r <- terra::rast(r) terra::crs(r) <- prj diff --git a/R/spatiotemp_pseudoabs.R b/R/spatiotemp_pseudoabs.R index 1fe32a6..89d6bfa 100644 --- a/R/spatiotemp_pseudoabs.R +++ b/R/spatiotemp_pseudoabs.R @@ -22,10 +22,11 @@ #' represents the start of the temporal extent and the second represents the end of temporal extent #' to randomly generate pseudo-absences dates within. Required if `temporal.method` is `random`, #' and optionally used if `buffer`. See details. -#'@param spatial.ext the spatial extent to randomly generate pseudo-absences within. Object from -#' which extent can be extracted of class `Extent`, `RasterLayer`,`SpatialPolygonsDataFrame`, `sf` -#' or `polygon` or numeric vector listing xmin, xmax, ymin and ymax in order. Required if -#' `spatial.method` is `random`, and optionally used if `buffer`. See details. +#'@param spatial.ext the spatial extent to randomly generate pseudo-absences +#' within. Object from which extent can be extracted of class `SpatExtent`, +#' `SpatRaster`, an `sf` polygon or a numeric vector listing xmin, xmax, ymin +#' and ymax in order. Required if `spatial.method` is `random`, and optionally +#' used if `buffer`. See details. #'@param prj a character string, the coordinate reference system of input `occ.data` co-ordinates. #' Default is "+proj=longlat +datum=WGS84". #'@details @@ -61,12 +62,12 @@ #'If `spatial.method` is `random`, then the pseudo-absence record co-ordinates are randomly #'generated across `spatial.ext` object given. #' -#'If `spatial.ext` is a `sf` polygon or multipolygon object, `RasterLayer` (mask if possible before -#'input) or `SpatialPolygonsDataFrame`, then these shapes are used, instead of a simple rectangular -#'extent. Therefore, inputting one of these objects will allow for more specific pseudo-absence +#'If `spatial.ext` is a `sf` polygon or `SpatRaster` (mask if possible before +#'input) then these shapes are used, instead of a simple rectangular +#'extent (`SpatExtent`). Therefore, inputting one of these objects will allow for more specific pseudo-absence #'generation. #' -#'For example, inputting a `SpatialPolygonsDataFrame` of specific countries will ensure co-ordinates +#'For example, inputting an `sf` polygon of a specific countries will ensure co-ordinates #'are terrestrial, whereas an extent (xmin, xmax, ymin, ymax) that encompasses these countries may #'result in the generation of pseudo-absence records in inappropriate areas, such as oceans or #'non-study-area countries. diff --git a/README.Rmd b/README.Rmd index 31c2656..01ae78d 100644 --- a/README.Rmd +++ b/README.Rmd @@ -20,7 +20,7 @@ knitr::opts_chunk$set( [![Codecov test coverage](https://codecov.io/gh/r-a-dobson/dynamicSDM/branch/main/graph/badge.svg)](https://app.codecov.io/gh/r-a-dobson/dynamicSDM?branch=main) [![R-CMD-check](https://github.com/r-a-dobson/dynamicSDM/workflows/R-CMD-check/badge.svg)](https://github.com/r-a-dobson/dynamicSDM/actions) [![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.7405906.svg)](https://doi.org/10.5281/zenodo.7405906) -[![Journal article](https://img.shields.io/badge/Published in-Methods in Ecology and Evolution-purple.svg)](https://doi.org/10.1111/2041-210X.14101) +[![Journal article](https://img.shields.io/badge/Published_in-Methods_in_Ecology_and_Evolution-purple.svg)](\doi{10.1111/2041-210X.14101}) [![CRAN status](https://www.r-pkg.org/badges/version/dynamicSDM)](https://CRAN.R-project.org/package=dynamicSDM) @@ -36,7 +36,7 @@ knitr::opts_chunk$set( * The package has since been published in the **Open Access journal "Methods in Ecology and Evolution"** -[*Dobson, R., Challinor, A.J., Cheke, R.A., Jennings, S., Willis, S.G. and Dallimer, M., 2023. dynamicSDM: An R package for species geographical distribution and abundance modelling at high spatiotemporal resolution. Methods in Ecology and Evolution.*](https://doi.org/10.1111/2041-210X.14101) +[*Dobson, R., Challinor, A.J., Cheke, R.A., Jennings, S., Willis, S.G. and Dallimer, M., 2023. dynamicSDM: An R package for species geographical distribution and abundance modelling at high spatiotemporal resolution. Methods in Ecology and Evolution.*](\doi{10.1111/2041-210X.14101}) diff --git a/README.md b/README.md index 8242b65..898538d 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ coverage](https://codecov.io/gh/r-a-dobson/dynamicSDM/branch/main/graph/badge.sv [![R-CMD-check](https://github.com/r-a-dobson/dynamicSDM/workflows/R-CMD-check/badge.svg)](https://github.com/r-a-dobson/dynamicSDM/actions) [![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.7405906.svg)](https://doi.org/10.5281/zenodo.7405906) [![Journal -article](https://img.shields.io/badge/Published%20in-Methods%20in%20Ecology%20and%20Evolution-purple.svg)](https://doi.org/10.1111/2041-210X.14101) +article](https://img.shields.io/badge/Published_in-Methods_in_Ecology_and_Evolution-purple.svg)](\doi%7B10.1111/2041-210X.14101%7D) [![CRAN status](https://www.r-pkg.org/badges/version/dynamicSDM)](https://CRAN.R-project.org/package=dynamicSDM) @@ -36,7 +36,7 @@ status](https://www.r-pkg.org/badges/version/dynamicSDM)](https://CRAN.R-project and Dallimer, M., 2023. dynamicSDM: An R package for species geographical distribution and abundance modelling at high spatiotemporal resolution. Methods in Ecology and -Evolution.*](https://doi.org/10.1111/2041-210X.14101) +Evolution.*](\doi%7B10.1111/2041-210X.14101%7D) diff --git a/data/sample_biome_data.rda b/data/sample_biome_data.rda deleted file mode 100644 index 0b88476..0000000 Binary files a/data/sample_biome_data.rda and /dev/null differ diff --git a/data/sample_proj_rast.rda b/data/sample_proj_rast.rda deleted file mode 100644 index 48d36cb..0000000 Binary files a/data/sample_proj_rast.rda and /dev/null differ diff --git a/man/dynamic_proj.Rd b/man/dynamic_proj.Rd index 229521b..5ae0d9d 100644 --- a/man/dynamic_proj.Rd +++ b/man/dynamic_proj.Rd @@ -70,7 +70,7 @@ Default is "+proj=longlat +datum=WGS84".} \item{proj.prj}{a character string, the coordinate reference system desired for output projection rasters. Default is assumed to be the same as prj.} -\item{spatial.mask}{an object of class \code{Raster}, \code{sf} or \code{Spatial}, representing a mask in which +\item{spatial.mask}{an object of class \code{SpatRaster} or\code{sf} polygon, representing a mask in which NA cells in the mask layer are removed from the projection covariates.} } \value{ diff --git a/man/dynamic_proj_covariates.Rd b/man/dynamic_proj_covariates.Rd index dd2daf0..1f9eebf 100644 --- a/man/dynamic_proj_covariates.Rd +++ b/man/dynamic_proj_covariates.Rd @@ -41,9 +41,9 @@ if \code{drive.folder} or \code{save.drive.folder} used.} \item{local.directory}{optional; a character string or vector, path to local directory or directories to read projection covariate rasters from.} -\item{spatial.ext}{optional; the spatial extent to crop explanatory variable rasters to. Object of -class \code{Extent}, \code{RasterLayer}, \code{sf}, \code{SpatialPolygonsDataFrame}, \code{polygon} or numeric vector -listing xmin, xmax, ymin and ymax in order.} +\item{spatial.ext}{optional; the spatial extent to crop explanatory variable +rasters to. Object of class \code{SpatExtent}, \code{SpatRaster}, an \code{sf} polygon or +numeric vector listing xmin, xmax, ymin and ymax in order.} \item{spatial.mask}{an object of class \code{Raster}, \code{sf} or \code{Spatial}, representing a mask in which NA cells in the mask layer are removed from the projection covariates.} @@ -55,7 +55,7 @@ projection rasters to be resampled to. Required if \code{spatial.ext} given.} method to use. One of \code{ngb} and \code{bilinear}. See details for more information.} \item{cov.file.type}{a character string, the type of file to export projection covariates as. One -of: \code{tif} (raster stack) or \code{csv}(data frame).} +of: \code{tif} (SpatRaster with multiple layers) or \code{csv}(data frame).} \item{prj}{a character string, the coordinate reference system desired for projection covariates. Default is "+proj=longlat +datum=WGS84".} @@ -104,9 +104,10 @@ date and explanatory variable name, then the function will error. } \section{Processing rasters}{ -If required, rasters are cropped and resampled to the same spatial extent and resolution. If -\code{spatial.mask} is given, then cells with NA in this mask layer are removed from the returned -projection covariates. See \code{raster::mask()} in R package \code{raster} for details. +If required, rasters are cropped and resampled to the same spatial extent and +resolution. If \code{spatial.mask} is given, then cells with NA in this mask layer +are removed from the returned projection covariates. See \code{terra::mask()} in R +package \code{terra} for details (Hijmans et al., 2022). Rasters are then stacked and reprojected if \code{cov.prj} is different to \code{prj}. @@ -154,7 +155,7 @@ to be specified too using \code{static.resample.method}. Please also provide #' # Spatial buffering of static rasters (optional) -Using the \code{focal} function from \code{raster} R package (Hijmans et al., 2015), +Using the \code{focal} function from \code{terra} R package (Hijmans et al., 2022), \code{GEE.math.fun} is calculated across the spatial buffer area from the record co-ordinate. The spatial buffer area used is specified by the argument \code{moving.window.matrix}, which dictates the neighbourhood of cells @@ -232,3 +233,7 @@ dynamic_proj_covariates(dates = projectiondates, save.directory = tempdir()) \dontshow{\}) # examplesIf} } +\references{ +Hijmans, R.J., Bivand, R., Forner, K., Ooms, J., Pebesma, E. and Sumner, M.D., +2022. Package 'terra'. Maintainer: Vienna, Austria. +} diff --git a/man/extract_buffered_coords.Rd b/man/extract_buffered_coords.Rd index c73f587..20940ed 100644 --- a/man/extract_buffered_coords.Rd +++ b/man/extract_buffered_coords.Rd @@ -99,7 +99,7 @@ occurrence record date. } \section{Spatial dimension}{ -Using the \code{focal} function from \code{raster} R package (Hijmans et al., 2015), \code{GEE.math.fun} is +Using the \code{focal} function from \code{terra} R package (Hijmans et al., 2022), \code{GEE.math.fun} is calculated across the spatial buffer area from the record co-ordinate. The spatial buffer area used is specified by the argument \code{moving.window.matrix}, which dictates the neighbourhood of cells surrounding the cell containing the occurrence record to include in this calculation. @@ -147,7 +147,7 @@ same raster. For the former, \code{temporal.level} argument should be \code{year \section{Aggregation factor}{ \code{agg.factor} given represents the factor to aggregate \code{RasterLayer} data with function -\code{aggregate} in \code{raster} R package (Hijmans et al., 2015). Aggregation uses the \code{GEE.math.fun} as +\code{aggregate} in \code{terra} R package (Hijmans et al., 2022). Aggregation uses the \code{GEE.math.fun} as the function. Following aggregation spatial buffering using the moving window matrix occurs. This is included to minimise computing time if data are of high spatial resolution and a large spatial buffer is needed. Ensure to calculate \code{get_moving_window()} with the spatial resolution @@ -229,7 +229,6 @@ interacting with Google Earth Engine. Journal of Open Source Software, 5(51), p. D'Agostino McGowan L., and Bryan J., 2022. googledrive: An Interface to Google Drive. \url{https://googledrive.tidyverse.org}, \url{https://github.com/tidyverse/googledrive}. -Hijmans, R. J., Van Etten, J., Cheng, J., Mattiuzzi, M., Sumner, M., Greenberg, J. A., -Lamigueiro, O. P., Bevan, A., Racine, E. B. & Shortridge, A. 2015. Package ‘raster’. R package, -734. +Hijmans, R.J., Bivand, R., Forner, K., Ooms, J., Pebesma, E. and Sumner, M.D., +2022. Package 'terra'. Maintainer: Vienna, Austria. } diff --git a/man/extract_buffered_raster.Rd b/man/extract_buffered_raster.Rd index 18c4234..ce4b87e 100644 --- a/man/extract_buffered_raster.Rd +++ b/man/extract_buffered_raster.Rd @@ -27,8 +27,8 @@ extract_buffered_raster( \arguments{ \item{dates}{a character string, vector of dates in format "YYYY-MM-DD".} -\item{spatial.ext}{the spatial extent for the extracted raster. Object from which extent can be -extracted of class \code{Extent}, \code{RasterLayer},\code{SpatialPolygonsDataFrame}, \code{sf} or \code{polygon} or +\item{spatial.ext}{the spatial extent for the extracted raster. Object from which extent +can be extracted of class \code{SpatExtent}, \code{SpatRaster}, \code{sf} polygon or numeric vector listing xmin, xmax, ymin and ymax in order.} \item{datasetname}{a character string, the Google Earth Engine dataset to extract data from.} @@ -109,7 +109,7 @@ more relevant that "sum" of land cover classification numbers. } \section{Spatial dimension}{ -Using the \code{focal} function in \code{raster} R package (Hijmans et al., 2015), \code{GEE.math.fun} is +Using the \code{focal} function in \code{terra} R package (Hijmans et al., 2022), \code{GEE.math.fun} is calculated across the spatial buffer area from each cell in \code{spatial.ext}. The spatial buffer area used is defined by \verb{moving.window matrix}, which dictates the neighbourhood of cells surrounding each cell in \code{spatial.ext} to include in the calculation. @@ -136,8 +136,8 @@ For example, this function could return the sum of suitable land cover classifie } \section{Aggregation factor}{ -\code{agg.factor} given represents the factor to aggregate \code{RasterLayer} data with function -\code{aggregate} in \code{raster} R package (Hijmans et al., 2015). Aggregation uses the \code{GEE.math.fun} as +\code{agg.factor} given represents the factor to aggregate \code{SpatRaster} data with function +\code{aggregate} in \code{terra} R package (Hijmans et al., 2022). Aggregation uses the \code{GEE.math.fun} as the function. Following aggregation spatial buffering using the moving window matrix occurs. This is included to minimise computing time if data are of high spatial resolution and a large spatial buffer is needed. Ensure to calculate \code{get_moving_window()} with the spatial resolution @@ -235,7 +235,6 @@ interacting with Google Earth Engine. Journal of Open Source Software, 5(51), p. D'Agostino McGowan L., and Bryan J., 2022. googledrive: An Interface to Google Drive. \url{https://googledrive.tidyverse.org}, \url{https://github.com/tidyverse/googledrive}. -Hijmans, R. J., Van Etten, J., Cheng, J., Mattiuzzi, M., Sumner, M., Greenberg, J. A., -Lamigueiro, O. P., Bevan, A., Racine, E. B. & Shortridge, A. 2015. Package ‘raster’. R package, -734. +Hijmans, R.J., Bivand, R., Forner, K., Ooms, J., Pebesma, E. and Sumner, M.D., +2022. Package 'terra'. Maintainer: Vienna, Austria. } diff --git a/man/extract_dynamic_raster.Rd b/man/extract_dynamic_raster.Rd index 57ed485..7ad29d4 100644 --- a/man/extract_dynamic_raster.Rd +++ b/man/extract_dynamic_raster.Rd @@ -24,7 +24,7 @@ extract_dynamic_raster( \item{dates}{a character string, vector of dates in format "YYYY-MM-DD".} \item{spatial.ext}{the spatial extent for the extracted raster. Object from which extent can be -extracted of class \code{Extent}, \code{RasterLayer}, \code{SpatialPolygonsDataFrame}, \code{sf} or \code{polygon} or +extracted of class \code{SpatExtent}, \code{SpatRaster}, an \code{sf} polygon or a numeric vector listing xmin, xmax, ymin and ymax in order.} \item{datasetname}{a character string, the Google Earth Engine dataset to extract data from.} diff --git a/man/extract_static_coords.Rd b/man/extract_static_coords.Rd index c1a71f5..1ec78e3 100644 --- a/man/extract_static_coords.Rd +++ b/man/extract_static_coords.Rd @@ -19,16 +19,16 @@ and dates with column names as follows; record longitude as "x", latitude as "y", and associated explanatory variable data.} \item{varnames}{a character string or vector, the unique names for each -explanatory variable in order of rasters in stack.} +explanatory variable in order of layers in the SpatRaster.} \item{extraction.method}{a character string or vector, the methods to extract -data from raster using \code{raster} package \code{extract} function. One of \code{simple} +data from SpatRaster using \code{terra} package \code{extract} function. One of \code{simple} or \code{bilinear}. If \code{simple} values for the cell a point falls in are returned. If \code{bilinear} the returned values are interpolated from the values of the four nearest raster cells.} -\item{static.rasters}{a RasterStack of one or more rasters to extracted data -from.} +\item{static.rasters}{a \code{SpatRaster} containing one or more SpatRaster layers +to extract data from.} \item{moving.window.matrix}{optional; a matrix of weights with an odd number of sides, representing the spatial neighbourhood of cells (“moving @@ -52,14 +52,13 @@ record co-ordinates or spatially buffered using a moving window matrix. Note: \itemize{ -\item \code{varnames} must be in the order of raster layers within the provided stack. -\item \code{extraction.method} must be of length one to use for all layers, or the -length of nlayers(static.rasters) and in the same order as the appropriate -layers within the provided stack. +\item \code{varnames} must be in the order of raster layers within the SpatRaster. +\item \code{extraction.method} must be of length one to apply to all layers, or +length equal to the number of layers in \code{static.rasters}. } } \section{Spatial buffering (optional)}{ -Using the \code{focal} function from \code{raster} R package (Hijmans et al., 2015), +Using the \code{focal} function from \code{terra} R package (Hijmans et al., 2022), \code{GEE.math.fun} is calculated across the spatial buffer area from the record co-ordinate. The spatial buffer area used is specified by the argument \code{moving.window.matrix}, which dictates the neighbourhood of cells @@ -84,11 +83,18 @@ analogous R function is available. This includes: "allNonZero","anyNonZero", \examples{ \donttest{ data("sample_explan_data") -data("sample_biome_data") +random_cat_layer <- terra::rast(sample_extent_data) +random_cat_layer <- terra::setValues(random_cat_layer, + sample(0:10, terra::ncell(random_cat_layer), + replace = TRUE)) extract_static_coords(occ.data = sample_explan_data, - varnames = "biome_type", - static.rasters = raster::stack(sample_biome_data)) + varnames = "random_cat_layer", + static.rasters = random_cat_layer) } } +\references{ +Hijmans, R.J., Bivand, R., Forner, K., Ooms, J., Pebesma, E. and Sumner, M.D., +2022. Package ‘terra’. Maintainer: Vienna, Austria. +} diff --git a/man/figures/dynamicSDM_1.3.pdf b/man/figures/dynamicSDM_1.3.pdf index e892a7f..c150d43 100644 Binary files a/man/figures/dynamicSDM_1.3.pdf and b/man/figures/dynamicSDM_1.3.pdf differ diff --git a/man/get_moving_window.Rd b/man/get_moving_window.Rd index 39b1a8d..dc1d4f1 100644 --- a/man/get_moving_window.Rd +++ b/man/get_moving_window.Rd @@ -20,9 +20,9 @@ variable data.} \item{spatial.res.metres}{a numeric value, the spatial resolution in metres of explanatory variable data.} -\item{spatial.ext}{the spatial extent of the study. Object from which extent can be extracted of -class \code{Extent}, \code{RasterLayer}, \code{sf} or \code{polygon} or numeric vector listing xmin, xmax, ymin and -ymax in order.} +\item{spatial.ext}{the spatial extent of the study. Object from which extent +can be extracted of class \code{SpatExtent}, \code{SpatRaster}, \code{sf} polygon or +numeric vector listing xmin, xmax, ymin and ymax in order.} } \value{ Returns "moving window" matrix with an odd number of sides and equal weights. @@ -42,10 +42,12 @@ variable would be calculated across the nine grid cells neighbouring the cell of cell of interest. } -\section{Why use a moving window matrix instead of circular buffer? The benefit of using a “moving}{ -window” over calculating explanatory variable values across a set radius from each record -co-ordinate, is that when generating projection rasters at high spatial and temporal resolution, -these can be generated much faster as the “moving windows” standardise the calculation. +\section{Why use a moving window matrix instead of circular buffer?}{ +The benefit of using a “moving window” over calculating explanatory +variable values across a set radius from each record co-ordinate, is that when +generating projection rasters at high spatial and temporal resolution, these +can be generated much faster as the “moving windows” standardise the +calculation. } \section{Function calculation}{ diff --git a/man/sample_biome_data.Rd b/man/sample_biome_data.Rd deleted file mode 100644 index ab911cd..0000000 --- a/man/sample_biome_data.Rd +++ /dev/null @@ -1,32 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/data.R -\docType{data} -\name{sample_biome_data} -\alias{sample_biome_data} -\title{Biome classification raster for southern Africa.} -\format{ -A RasterLayer -\describe{ -\item{class}{RasterLayer} -\item{dimensions}{4839, 3243, 15692877 (nrow, ncol, ncell)} -\item{resolution}{0.008983153, 0.008983153 (x, y)} -\item{extent}{11.71845, 40.85081, -47.89832, -4.428839 (xmin, xmax, ymin, ymax)} -\item{crs}{"+proj=longlat +datum=WGS84 +no_defs"} -\item{source}{biome_type_2001-01-01.tif } -\item{names}{biome_type_2001-01-01.tif } -\item{values}{Numerical categorical value ranging from 0, 255 (min, max).} -} -} -\usage{ -sample_biome_data -} -\description{ -Categorical RasterLayer cropped to southern Africa at 0.08 degree resolution from OpenLandMap -Potential Distribution of Biomes (Hengl et al., 2018). -} -\references{ -Hengl T, Walsh MG, Sanderman J, Wheeler I, Harrison SP, Prentice IC. (2018) Global Mapping of -Potential Natural Vegetation: An Assessment of Machine Learning Algorithms for Estimating Land -Potential. PeerJ Preprints. -} -\keyword{datasets} diff --git a/man/sample_proj_rast.Rd b/man/sample_proj_rast.Rd deleted file mode 100644 index f8126f5..0000000 --- a/man/sample_proj_rast.Rd +++ /dev/null @@ -1,29 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/data.R -\docType{data} -\name{sample_proj_rast} -\alias{sample_proj_rast} -\title{Distribution suitability projections for red-billed quelea in southern Africa} -\format{ -A RasterBrick -\describe{ -\item{class}{RasterBrick} -\item{dimensions}{31, 30, 930, 4 (nrow, ncol, ncell, nlayers)} -\item{resolution}{1, 1 (x, y)} -\item{extent}{11.6901, 41.6901, -35.43802, -4.438023 (xmin, xmax, ymin, ymax)} -\item{crs}{"+proj=longlat +datum=WGS84 +no_defs"} -\item{source}{memory} \item{names}{ X2018.01.01_proportional, X2018.04.01_proportional, -X2018.07.01_proportional, X2018.10.01_proportional } -\item{min values}{Numerical minimum distribution suitability projected in each layer.} -\item{max values}{Numerical maximum distribution suitability projected in each layer.} -} -} -\usage{ -sample_proj_rast -} -\description{ -RasterBrick of distribution suitability projections for red-billed quelea across southern at one -degree resolution for the dates: "2018-01-01", "2018-04-01", "2018-07-01" and "2018-10-01". A -value of 1 represents high suitability and a value of 0 low suitability. -} -\keyword{datasets} diff --git a/man/spatiotemp_bias.Rd b/man/spatiotemp_bias.Rd index 161d124..bea1767 100644 --- a/man/spatiotemp_bias.Rd +++ b/man/spatiotemp_bias.Rd @@ -56,7 +56,7 @@ and Nikulin, 1996) . } \section{Spatial bias}{ -To assess spatial sampling bias, the function returns a scatterplot of the spatial +To assess spatial sampling bias, the function returns a scatter plot of the spatial distribution of occurrence records to illustrate any spatial clustering (if \code{plot = TRUE}). The average nearest neighbour distance of record co-ordinates is then compared to that of records randomly generated at same density using a t-test, following the nearest neighbour index diff --git a/man/spatiotemp_block.Rd b/man/spatiotemp_block.Rd index e72c806..4bb308e 100644 --- a/man/spatiotemp_block.Rd +++ b/man/spatiotemp_block.Rd @@ -22,7 +22,7 @@ column names as follows; record longitude as "x", latitude as "y", year as "year \item{vars.to.block.by}{a character string or vector, the explanatory variable column names to group sampling units based upon.} -\item{spatial.layer}{optional; a \code{RasterLayer} object, a categorical spatial layer for sample +\item{spatial.layer}{optional; a \code{SpatRaster} object, a categorical spatial layer for sample unit splitting.} \item{spatial.split.degrees}{a numeric value, the grid cell resolution in degrees to split diff --git a/man/spatiotemp_extent.Rd b/man/spatiotemp_extent.Rd index b7c5313..beb30d8 100644 --- a/man/spatiotemp_extent.Rd +++ b/man/spatiotemp_extent.Rd @@ -20,9 +20,9 @@ column names as follows; record longitude as "x", latitude as "y", year as "year represents start of temporal extent and second date represents end of temporal extent for inclusion.} -\item{spatial.ext}{the spatial extent to filter by. Object from which extent can be extracted of -class \code{Extent}, \code{RasterLayer}, \code{SpatialPolygonsDataFrame},\code{sf} or \code{polygon} or numeric vector -listing xmin, xmax, ymin and ymax in order.} +\item{spatial.ext}{the spatial extent to filter by. Object from which extent +can be extracted of class \code{SpatExtent}, \code{SpatRaster}, \code{sf} polygon or +numeric vector listing xmin, xmax, ymin and ymax in order.} \item{prj}{a character string, the coordinate reference system of input \code{occ.data} co-ordinates. Default is "+proj=longlat +datum=WGS84".} @@ -40,10 +40,9 @@ If \code{spatial.ext} is provided, \code{spatiotemp_extent()} checks whether spe co-ordinates are within the given spatial extent of the study (\code{spatial.ext}) and excludes any outside of this extent. -If \code{spatial.ext} object can be used as a mask by \code{raster::mask()} then the mask is used to filter -records in a more targetted way. If not, then the rectangular extent of the \code{spatial.ext} object -is used. If an \code{sf} polygon object is provided, this is first transformed into a \code{Spatial} object -for use by \code{raster::mask()}. +If \code{spatial.ext} object can be used as a mask by \code{terra::mask()} then the mask is used to filter +records in a more targeted way. If not, then the rectangular extent of the \code{spatial.ext} object +is used. } \section{Temporal extent}{ diff --git a/man/spatiotemp_pseudoabs.Rd b/man/spatiotemp_pseudoabs.Rd index 21e96a6..f6401fa 100644 --- a/man/spatiotemp_pseudoabs.Rd +++ b/man/spatiotemp_pseudoabs.Rd @@ -27,10 +27,11 @@ of \code{buffer} or \code{random}: can be abbreviated.} with column names as follows; record longitude as "x", latitude as "y", year as "year", month as "month", and day as "day". Required if either \code{temporal.method} or \code{spatial.method} is \code{buffer}.} -\item{spatial.ext}{the spatial extent to randomly generate pseudo-absences within. Object from -which extent can be extracted of class \code{Extent}, \code{RasterLayer},\code{SpatialPolygonsDataFrame}, \code{sf} -or \code{polygon} or numeric vector listing xmin, xmax, ymin and ymax in order. Required if -\code{spatial.method} is \code{random}, and optionally used if \code{buffer}. See details.} +\item{spatial.ext}{the spatial extent to randomly generate pseudo-absences +within. Object from which extent can be extracted of class \code{SpatExtent}, +\code{SpatRaster}, an \code{sf} polygon or a numeric vector listing xmin, xmax, ymin +and ymax in order. Required if \code{spatial.method} is \code{random}, and optionally +used if \code{buffer}. See details.} \item{temporal.ext}{optional; a character vector, two dates in format "YYYY-MM-DD". The first represents the start of the temporal extent and the second represents the end of temporal extent @@ -89,12 +90,12 @@ want to clip buffers to only terrestrial regions using a country polygon given i If \code{spatial.method} is \code{random}, then the pseudo-absence record co-ordinates are randomly generated across \code{spatial.ext} object given. -If \code{spatial.ext} is a \code{sf} polygon or multipolygon object, \code{RasterLayer} (mask if possible before -input) or \code{SpatialPolygonsDataFrame}, then these shapes are used, instead of a simple rectangular -extent. Therefore, inputting one of these objects will allow for more specific pseudo-absence +If \code{spatial.ext} is a \code{sf} polygon or \code{SpatRaster} (mask if possible before +input) then these shapes are used, instead of a simple rectangular +extent (\code{SpatExtent}). Therefore, inputting one of these objects will allow for more specific pseudo-absence generation. -For example, inputting a \code{SpatialPolygonsDataFrame} of specific countries will ensure co-ordinates +For example, inputting an \code{sf} polygon of a specific countries will ensure co-ordinates are terrestrial, whereas an extent (xmin, xmax, ymin, ymax) that encompasses these countries may result in the generation of pseudo-absence records in inappropriate areas, such as oceans or non-study-area countries. diff --git a/tests/testthat/test-dynamic_proj_covariates.R b/tests/testthat/test-dynamic_proj_covariates.R index 3a966f4..45c8f4d 100644 --- a/tests/testthat/test-dynamic_proj_covariates.R +++ b/tests/testthat/test-dynamic_proj_covariates.R @@ -138,7 +138,7 @@ test_that("Works if spatial.ext = RasterLayer", { test_that("Works if spatial.ext = polygon", { dates <- c("2010-01-01") - polygon <- sp::Polygon(cbind(c(12, 12, 36, 36), c(-35, -12, -35, -12))) + polygon <- sf::st_polygon(list(cbind(c(20, 12, 36, 36,20), c(-35, -12, -35, -12,-35)))) results <- dynamic_proj_covariates( dates = dates, varnames = c("precipitation_10_prior_sum", "NDVI_5_post_max"), diff --git a/tests/testthat/test-get_moving_window.R b/tests/testthat/test-get_moving_window.R index 80f016c..753ae09 100644 --- a/tests/testthat/test-get_moving_window.R +++ b/tests/testthat/test-get_moving_window.R @@ -35,16 +35,6 @@ test_that("stops if spatial.res.degrees given but spatial.ext not given", { )) }) -test_that("stops if spatial.res.degrees and spatial.ext class invalid", { - expect_error( - get_moving_window( - radial.distance = 100, - spatial.res.degrees = 0.5, - spatial.ext = "southernafrica" - ) - ) -}) - test_that( "stops if spatial.res.degrees and spatial.ext class numeric and incorrect length invalid", { @@ -82,7 +72,7 @@ test_that("works with spatial.ext as numeric", { }) test_that("works with spatial.ext as Extent", { - Extent <- raster::extent(c(12, 36, -35, -12)) + Extent <- terra::ext(c(12, 36, -35, -12)) results <- get_moving_window( radial.distance = 100, spatial.res.degrees = 0.5, @@ -93,7 +83,7 @@ test_that("works with spatial.ext as Extent", { test_that("works with spatial.ext as raster", { numeric <- c(12, 36, -35, -12) - raster <- raster::raster(raster::extent(numeric)) + raster <- terra::rast(terra::ext(numeric)) results <- get_moving_window( radial.distance = 100000, spatial.res.degrees = 0.5, @@ -103,7 +93,7 @@ test_that("works with spatial.ext as raster", { }) test_that("works with spatial.ext as polygon", { - polygon <- sp::Polygon(cbind(c(12, 12, 36, 36), c(-35, -12, -35, -12))) + polygon <- sf::st_polygon(list(cbind(c(20, 12, 36, 36,20), c(-35, -12, -35, -12,-35)))) results <- get_moving_window( radial.distance = 100000, spatial.res.degrees = 0.5, @@ -123,15 +113,6 @@ test_that("works with spatial.ext as sf", { expect_equal(class(results)[1], "matrix") }) -test_that("stops if spatial.res.degrees and spatial.ext class invalid", { - expect_error( - get_moving_window( - radial.distance = 100000, - spatial.res.degrees = 0.5, - spatial.ext = "southernafrica" - ) - ) -}) test_that("Error if wrong class spatial.res.metres", { expect_error(get_moving_window(radial.distance = 100000, spatial.res.metres = diff --git a/tests/testthat/test-spatiotemp_block.R b/tests/testthat/test-spatiotemp_block.R index 7dfac30..3d230a9 100644 --- a/tests/testthat/test-spatiotemp_block.R +++ b/tests/testthat/test-spatiotemp_block.R @@ -1,9 +1,9 @@ data("sample_explan_data") sample_model_data2 <- dplyr::sample_n(sample_explan_data, 50) -biome_layer <- raster::raster() -raster::extent(biome_layer) <- c(11.71845, 40.85081,-47.89832,-4.428839) -raster::res(biome_layer) <- 10 -raster::values(biome_layer) <- 1:raster::ncell(biome_layer) +biome_layer <- terra::rast(sample_extent_data) +terra::res(biome_layer) <- 10 +biome_layer <- terra::setValues(biome_layer, + 1:terra::ncell(biome_layer)) test_that("stops if no occ.data provided", { expect_error( diff --git a/tests/testthat/test-spatiotemp_extent.R b/tests/testthat/test-spatiotemp_extent.R index 33ffc1e..9bc77da 100644 --- a/tests/testthat/test-spatiotemp_extent.R +++ b/tests/testthat/test-spatiotemp_extent.R @@ -95,7 +95,7 @@ test_that("Filters by spatial.ext but all within extent, raster ", { }) test_that("Filters by spatial.ext polygon ", { - polygon <- sp::Polygon(cbind(c(12, 12, 36, 36), c(-35, -12, -35, -12))) + polygon <- sf::st_polygon(list(cbind(c(20, 12, 36, 36,20), c(-35, -12, -35, -12,-35)))) results <- spatiotemp_extent(occ.data = sample_explan_data, spatial.ext = polygon) expect_equal(nrow(results), 327) }) diff --git a/tests/testthat/test-spatiotemp_pseudoabs.R b/tests/testthat/test-spatiotemp_pseudoabs.R index c4fc542..8fcbc63 100644 --- a/tests/testthat/test-spatiotemp_pseudoabs.R +++ b/tests/testthat/test-spatiotemp_pseudoabs.R @@ -323,7 +323,7 @@ test_that("Success if spatial extent numeric", { }) test_that("Success if spatial extent extent", { - Extent <- raster::extent(c(20, 36, -35, -12)) + Extent <- terra::ext(c(20, 36, -35, -12)) results <- spatiotemp_pseudoabs( occ.data = sample_explan_data, n.pseudoabs = 10, @@ -336,7 +336,7 @@ test_that("Success if spatial extent extent", { }) test_that("Success if spatial extent raster", { - raster <- raster::raster(raster::extent(c(20, 36, -35, -12))) + raster <- terra::rast(terra::ext(c(20, 36, -35, -12))) results <- spatiotemp_pseudoabs( occ.data = sample_explan_data, n.pseudoabs = 10, @@ -349,7 +349,7 @@ test_that("Success if spatial extent raster", { }) test_that("Success if spatial extent polygon", { - polygon <- sp::Polygon(cbind(c(20, 12, 36, 36), c(-35, -12, -35, -12))) + polygon <- sf::st_polygon(list(cbind(c(20, 12, 36, 36,20), c(-35, -12, -35, -12,-35)))) results <-spatiotemp_pseudoabs( occ.data = sample_explan_data, n.pseudoabs = 10, diff --git a/vignettes/vignette4_projecting.Rmd b/vignettes/vignette4_projecting.Rmd index 08c7f49..3803fb5 100644 --- a/vignettes/vignette4_projecting.Rmd +++ b/vignettes/vignette4_projecting.Rmd @@ -209,10 +209,10 @@ dynamic_proj(dates = projectiondates, Let’s read in and plot our projections! ```{r plot projections, eval = FALSE} -sp::plot(terra::rast(list.files(projection_directories)[1])) -sp::plot(terra::rast(list.files(projection_directories)[2])) -sp::plot(terra::rast(list.files(projection_directories)[3])) -sp::plot(terra::rast(list.files(projection_directories)[4])) +terra::plot(terra::rast(list.files(projection_directories)[1])) +terra::plot(terra::rast(list.files(projection_directories)[2])) +terra::plot(terra::rast(list.files(projection_directories)[3])) +terra::plot(terra::rast(list.files(projection_directories)[4])) ```