#' Focal (moving window) mean
#'
#' @param s Input RasterStack
#' @param d Size of focalWeight matrix. See ?focalWeight
#' @param mem_share Share of memory to be used
#' @param n_cores Number of cores used for parallel processing. Default is NULL, indicating no parallelization.
#' @param window_type Type of moving window. See ?focalWeight
#' @param d_in_cells Is 'd' specified in number of cells?
#' @param mem_of_total Is 'mem_share' specified as share of total memory (instead of currently available)?
#'
#' @return RasterStack
#' @export
vx_mean_focal <- function(s, d, mem_share = .5, n_cores = NULL, window_type = "circle", d_in_cells = FALSE, mem_of_total = FALSE) {
# split into memory-safe chunks
raster_chunk_list <- split_layers(s, mem_share, mem_of_total)
# is the d parameter specified in number of cells? -> convert
if(d_in_cells) {
d <- raster::res(s)[1]*d
}
# create weights matrix
m <- raster::focalWeight(s, d, window_type)
# process one chunk after the other
# use parallel processing if specified
out_list <- lapply(raster_chunk_list, function(r_chunk){
if(!is.null(n_cores)) {
cl <- parallel::makeCluster(n_cores)
r_list <- parallel::parLapply(cl,
raster::unstack(r_chunk),
varlist = c("m"),
fun = function(ri) {
vx <- velox::velox(ri)
vx$meanFocal(m)
vx$as.RasterStack()
})
out_chunk <- raster::stack(r_list)
parallel::stopCluster(cl)
} else {
vx <- velox::velox(r_chunk)
vx$meanFocal(m, bands = 1:raster::nlayers(s))
out_chunk <- vx$as.RasterStack()
}
out_chunk
})
out <- raster::stack(out_list)
out
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.