diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 398a915fa2cba6f605378d497f0b6ab8ac275d84..a7d3f8954fc859541b2ce5e564804bf6b7624848 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -5,6 +5,6 @@ build: stage: build script: - module load R - - R -e 'devtools::build()' - - R -e 'devtools::check()' + - R CMD build --resave-data . + - R CMD check --as-cran multiApply_*.tar.gz - R -e 'covr::package_coverage()' diff --git a/DESCRIPTION b/DESCRIPTION index 1f13960443cd0342df543061a807dbba68d85924..d514a064fa31a9d388854a4f08d88379b355c95c 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,15 +1,15 @@ Package: multiApply -Title: Apply Functions to Multiple Multidimensional Arguments -Version: 1.0.0 +Title: Apply Functions to Multiple Multidimensional Arrays or Vectors +Version: 2.0.0 Authors@R: c( person("BSC-CNS", role = c("aut", "cph")), person("Nicolau", "Manubens", , "nicolau.manubens@bsc.es", role = "aut"), - person("Alasdair", "Hunter", , "alasdair.hunter@bsc.es", role = c("aut", "cre"))) -Description: The base apply function and its variants, as well as the related functions in the 'plyr' package, typically apply user-defined functions to a single argument (or a list of vectorized arguments in the case of mapply). The 'multiApply' package extends this paradigm to functions taking one or a list of multiple unidimensional or multidimensional arguments (or combinations thereof) as input, which can have different numbers of dimensions as well as different dimension lengths, and returning one or a list of unidimensional or multidimensional arrays as output. In contrast to apply and variants, this package suggests the use of 'target dimensions' as opposite to the 'margins' for specifying the dimensions relevant to the function to be applied. Also, two remarkable differences are the support for functions returning multiple array outputs and the transparent use of multi-core. + person("Alasdair", "Hunter", , "alasdair.hunter@bsc.es", role = "aut"), + person("Nuria", "Perez", , "nuria.perez@bsc.es", role = "cre")) +Description: The base apply function and its variants, as well as the related functions in the 'plyr' package, typically apply user-defined functions to a single argument (or a list of vectorized arguments in the case of mapply). The 'multiApply' package extends this paradigm to efficiently apply functions taking one or a list of multiple unidimensional or multidimensional arguments (or combinations thereof) as input, which can have different numbers of dimensions as well as different dimension lengths, and returning one or a list of unidimensional or multidimensional arrays as output. This saves development time by preventing the R user from writing error-prone and memory-unefficient loops dealing with multiple complex arrays. In contrast to apply and variants, this package suggests the use of 'target dimensions' as opposite to the 'margins' for specifying the dimensions relevant to the function to be applied. Also, two remarkable features of multiApply are the support for functions returning multiple array outputs and the transparent use of multi-core. Depends: R (>= 3.2.0) Imports: - abind, doParallel, foreach, plyr diff --git a/NAMESPACE b/NAMESPACE index aaad7ddbf11c74b330f0f98b7f932b9cff6fffab..12eb9c50b1bb579c77ba3a41b70b37c9c3e783d5 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -1,7 +1,6 @@ # Generated by roxygen2: do not edit by hand export(Apply) -importFrom(abind,abind) importFrom(doParallel,registerDoParallel) importFrom(foreach,registerDoSEQ) importFrom(plyr,llply) diff --git a/R/Apply.R b/R/Apply.R index b126918fdb1cff83d168cb51c9fd3dc298fd9f75..335d437dc39d6b472ee9fe128ebb4b3807d50849 100644 --- a/R/Apply.R +++ b/R/Apply.R @@ -1,17 +1,18 @@ -#' Wrapper for Applying Atomic Functions to Arrays. +#' Apply Functions to Multiple Multidimensional Arrays or Vectors #' -#' This wrapper applies a given function, which takes N [multi-dimensional] arrays as inputs (which may have different numbers of dimensions and dimension lengths), and applies it to a list of N [multi-dimensional] arrays with at least as many dimensions as expected by the given function. The user can specify which dimensions of each array (or matrix) the function is to be applied over with the \code{margins} or \code{target_dims} option. A user can apply a function that receives (in addition to other helper parameters) 1 or more arrays as input, each with a different number of dimensions, and returns any number of multidimensional arrays. The target dimensions can be specified by their names. It is recommended to use this wrapper with multidimensional arrays with named dimensions. -#' @param data A single object (vector, matrix or array) or a list of objects. They must be in the same order as expected by fun. -#' @param target_dims List of vectors containing the dimensions to be input into fun for each of the objects in the data. These vectors can contain either integers specifying the dimension position, or characters corresponding to the dimension names. This parameter is mandatory if margins is not specified. If both margins and target_dims are specified, margins takes priority over target_dims. -#' @param fun Function to be applied to the arrays. -#' @param ... Additional arguments to be used in the fun. +#' This function efficiently applies a given function, which takes N vectors or multi-dimensional arrays as inputs (which may have different numbers of dimensions and dimension lengths), and applies it to a list of N vectors or multi-dimensional arrays with at least as many dimensions as expected by the given function. The user can specify which dimensions of each array the function is to be applied over with the \code{margins} or \code{target_dims} parameters. The function to be applied can receive other helper parameters and return any number of numeric vectors or multidimensional arrays. The target dimensions or margins can be specified by their names, as long as the inputs are provided with dimension names (recommended). This function can also use multi-core in a transparent way if requested via the \code{ncores} parameter.\cr\cr The following steps help to understand how \code{Apply} works:\cr\cr - The function receives N arrays with Dn dimensions each.\cr - The user specifies, for each of the arrays, which of its dimensions are 'target' dimensions (dimensions which the function provided in 'fun' operates with) and which are 'margins' (dimensions to be looped over).\cr - \code{Apply} will generate an array with as many dimensions as margins in all of the input arrays. If a margin is repeated across different inputs, it will appear only once in the resulting array.\cr - For each element of this resulting array, the function provided in the parameter'fun' is applied to the corresponding sub-arrays in 'data'.\cr - If the function returns a vector or a multidimensional array, the additional dimensions will be prepended to the resulting array (in left-most positions).\cr - If the provided function returns more than one vector or array, the process above is carried out for each of the outputs, resulting in a list with multiple arrays, each with the combination of all target dimensions (at the right-most positions) and resulting dimensions (at the left-most positions). +#' +#' @param data One or a list of numeric object (vector, matrix or array). They must be in the same order as expected by the function provided in the parameter 'fun'. The dimensions do not necessarily have to be ordered. If the 'target_dims' require a different order than the provided, \code{Apply} will automatically reorder the dimensions as needed. +#' @param target_dims One or a list of vectors (or NULLs) containing the dimensions to be input into fun for each of the objects in the data. If a single vector of target dimensions is specified and multiple inputs are provided in 'data, then the single set of target dimensions is re-used for all of the inputs. These vectors can contain either integers specifying the position of the dimensions, or character strings corresponding to the dimension names. This parameter is mandatory if 'margins' are not specified. If both 'margins' and 'target_dims' are specified, 'margins' takes priority. +#' @param fun Function to be applied to the arrays. Must receive as many inputs as provided in 'data', each with as many dimensions as specified in 'target_dims' or as the total number of dimensions in 'data' minus the ones specified in 'margins'. The function can receive other additional fixed parameters (see parameter '...' of \code{Apply}). The function can return one or a list of numeric vectors or multidimensional arrays, optionally with dimension names which will be propagated to the final result. The returned list can optionally be named, with a name for each output, which will be propagated to the resulting array. The function can optionally be provided with the attributes 'target_dims' and 'output_dims'. In that case, the corresponding parameters of \code{Apply} do not need to be provided. The function can expect named dimensions for each of its inputs, in the same order as specified in 'target_dims' or, if no 'target_dims' have been provided, in the same order as provided in 'data'. +#' @param ... Additional fixed arguments expected by the function provided in the parameter 'fun'. #' @param output_dims Optional list of vectors containing the names of the dimensions to be output from the fun for each of the objects it returns (or a single vector if the function has only one output). -#' @param margins List of vectors containing the margins for the input objects to be split by. Or, if there is a single vector of margins specified and a list of objects in data, then the single set of margins is applied over all objects. These vectors can contain either integers specifying the dimension position, or characters corresponding to the dimension names. If both margins and target_dims are specified, margins takes priority over target_dims. +#' @param margins One or a list of vectors (or NULLs) containing the 'margin' dimensions to be looped over for each input in 'data'. If a single vector of margins is specified and multiple inputs are provided in 'data', then the single set of margins is re-used for all of the inputs. These vectors can contain either integers specifying the position of the margins, or character strings corresponding to the dimension names. If both 'margins' and 'target_dims' are specified, 'margins' takes priority. #' @param guess_dim_names Whether to automatically guess missing dimension names for dimensions of equal length across different inputs in 'data' with a warning (TRUE; default), or to crash whenever unnamed dimensions of equa length are identified across different inputs (FALSE). -#' @param ncores The number of multicore threads to use for parallel computation. +#' @param ncores The number of parallel processes to spawn for the use for parallel computation in multiple cores. #' @param split_factor Factor telling to which degree the input data should be split into smaller pieces to be processed by the available cores. By default (split_factor = 1) the data is split into 4 pieces for each of the cores (as specified in ncores). A split_factor of 2 will result in 8 pieces for each of the cores, and so on. The special value 'greatest' will split the input data into as many pieces as possible. -#' @details When using a single object as input, Apply is almost identical to the apply function. For multiple input objects, the output array will have dimensions equal to the dimensions specified in 'margins'. -#' @return List of arrays or matrices or vectors resulting from applying fun to data. +#' @details When using a single object as input, Apply is almost identical to the apply function (as fast or slightly slower in some cases; with equal or improved -smaller- memory footprint). +#' @return List of arrays or matrices or vectors resulting from applying 'fun' to 'data'. #' @references Wickham, H (2011), The Split-Apply-Combine Strategy for Data Analysis, Journal of Statistical Software. #' @export #' @examples @@ -25,7 +26,6 @@ #' (sum(y > z) / (length(y)))) * 100 #' } #' test <- Apply(data, target = list(3, 3, NULL), test_fun) -#' @importFrom abind abind #' @importFrom foreach registerDoSEQ #' @importFrom doParallel registerDoParallel #' @importFrom plyr splat llply @@ -402,29 +402,15 @@ Apply <- function(data, target_dims = NULL, fun, ..., chunk_sizes <- c(chunk_sizes, total_size %% chunk_size) } - input_margin_weights <- lapply(1:length(data), - function(i) { - marg_sizes <- dim(data[[i]])[margins[[i]]] - sapply(1:length(marg_sizes), - function(k) prod(c(1, marg_sizes)[1:k])) - }) - - # Flattening margin dimensions so that the iteration function can access - # them easily. + input_margin_weights <- vector('list', length(data)) for (i in 1:length(data)) { - if (length(margins[[i]]) > 0) { - dims <- dim(data[[i]]) - margins_inds <- 1:length(margins[[i]]) + length(target_dims[[i]]) - dim(data[[i]]) <- c(dims[-margins_inds], - '_margins_dim_' = prod(dims[margins_inds])) - } else { - dim(data[[i]]) <- c(dim(data[[i]]), '_margins_dim_' = 1) - } + marg_sizes <- dim(data[[i]])[margins[[i]]] + input_margin_weights[[i]] <- sapply(1:length(marg_sizes), + function(k) prod(c(1, marg_sizes)[1:k])) } + # TODO: need to add progress bar - # TODO: IF ONLY ONE INPUT ARRAY, MAKE USE OF apply. splatted_f <- splat(fun) - # For a selected use case, these are the timings: # - total: 17 s # - preparation + post: 1 s @@ -447,6 +433,7 @@ Apply <- function(data, target_dims = NULL, fun, ..., iteration_indices_to_take <- list() for (i in 1:length(data)) { iteration_indices_to_take[[i]] <- as.list(rep(TRUE, length(dim(data[[i]])))) + names(iteration_indices_to_take[[i]]) <- names(dim(data[[i]])) } add_one_multidim <- function(index, dims) { @@ -475,17 +462,19 @@ Apply <- function(data, target_dims = NULL, fun, ..., iteration_input <- list() for (i in 1:length(data)) { input_margin_dim_index <- first_marg_indices[margins_names[[i]]] - input_margin_dim_index <- 1 + sum((input_margin_dim_index - 1) * - input_margin_weights[[i]]) - iteration_indices_to_take[[i]][[length(dim(data[[i]]))]] <- input_margin_dim_index + iteration_indices_to_take[[i]][margins_names[[i]]] <- input_margin_dim_index iteration_input[[i]] <- do.call('[', c(list(x = data[[i]]), iteration_indices_to_take[[i]], list(drop = FALSE))) - num_dims <- length(dim(iteration_input[[i]])) - if (num_dims > 1) { - dim(iteration_input[[i]]) <- dim(iteration_input[[i]])[-length(dim(iteration_input[[i]]))] - } else { - dim(iteration_input[[i]]) <- NULL + num_margins <- length(margins_names[[i]]) + if (num_margins > 0) { + if (num_margins == length(dim(iteration_input[[i]]))) { + dim(iteration_input[[i]]) <- NULL + } else { + dims_to_remove <- 1:num_margins + length(target_dims[[i]]) + dim(iteration_input[[i]]) <- dim(iteration_input[[i]])[-dims_to_remove] + #if only one dim remains, make as.vector + } } } if (!is.null(mad)) { diff --git a/R/zzz.R b/R/zzz.R index 4df33e9e19c911fbd46dff48edae0bc35a3a6ef4..2bf747e7d38039995b33abe6636e771e6f2f30f5 100644 --- a/R/zzz.R +++ b/R/zzz.R @@ -11,137 +11,3 @@ dim(x) <- old_dims[new_order] x } - -# This function is a helper for the function .MergeArrays. -# It expects as inputs two named numeric vectors, and it extends them -# with dimensions of length 1 until an ordered common dimension -# format is reached. -.MergeArrayDims <- function(dims1, dims2) { - new_dims1 <- c() - new_dims2 <- c() - while (length(dims1) > 0) { - if (names(dims1)[1] %in% names(dims2)) { - pos <- which(names(dims2) == names(dims1)[1]) - dims_to_add <- rep(1, pos - 1) - if (length(dims_to_add) > 0) { - names(dims_to_add) <- names(dims2[1:(pos - 1)]) - } - new_dims1 <- c(new_dims1, dims_to_add, dims1[1]) - new_dims2 <- c(new_dims2, dims2[1:pos]) - dims1 <- dims1[-1] - dims2 <- dims2[-c(1:pos)] - } else { - new_dims1 <- c(new_dims1, dims1[1]) - new_dims2 <- c(new_dims2, 1) - names(new_dims2)[length(new_dims2)] <- names(dims1)[1] - dims1 <- dims1[-1] - } - } - if (length(dims2) > 0) { - dims_to_add <- rep(1, length(dims2)) - names(dims_to_add) <- names(dims2) - new_dims1 <- c(new_dims1, dims_to_add) - new_dims2 <- c(new_dims2, dims2) - } - list(new_dims1, new_dims2) -} - -# This function takes two named arrays and merges them, filling with -# NA where needed. -# dim(array1) -# 'b' 'c' 'e' 'f' -# 1 3 7 9 -# dim(array2) -# 'a' 'b' 'd' 'f' 'g' -# 2 3 5 9 11 -# dim(.MergeArrays(array1, array2, 'b')) -# 'a' 'b' 'c' 'e' 'd' 'f' 'g' -# 2 4 3 7 5 9 11 -.MergeArrays <- function(array1, array2, along) { - if (!(is.null(array1) || is.null(array2))) { - if (!(identical(names(dim(array1)), names(dim(array2))) && - identical(dim(array1)[-which(names(dim(array1)) == along)], - dim(array2)[-which(names(dim(array2)) == along)]))) { - new_dims <- .MergeArrayDims(dim(array1), dim(array2)) - dim(array1) <- new_dims[[1]] - dim(array2) <- new_dims[[2]] - for (j in 1:length(dim(array1))) { - if (names(dim(array1))[j] != along) { - if (dim(array1)[j] != dim(array2)[j]) { - if (which.max(c(dim(array1)[j], dim(array2)[j])) == 1) { - na_array_dims <- dim(array2) - na_array_dims[j] <- dim(array1)[j] - dim(array2)[j] - na_array <- array(dim = na_array_dims) - array2 <- abind(array2, na_array, along = j) - names(dim(array2)) <- names(na_array_dims) - } else { - na_array_dims <- dim(array1) - na_array_dims[j] <- dim(array2)[j] - dim(array1)[j] - na_array <- array(dim = na_array_dims) - array1 <- abind(array1, na_array, along = j) - names(dim(array1)) <- names(na_array_dims) - } - } - } - } - } - if (!(along %in% names(dim(array2)))) { - stop("The dimension specified in 'along' is not present in the ", - "provided arrays.") - } - array1 <- abind(array1, array2, along = which(names(dim(array1)) == along)) - names(dim(array1)) <- names(dim(array2)) - } else if (is.null(array1)) { - array1 <- array2 - } - array1 -} - -# Takes as input a list of arrays. The list must have named dimensions. -.MergeArrayOfArrays <- function(array_of_arrays) { - MergeArrays <- .MergeArrays - array_dims <- (dim(array_of_arrays)) - dim_names <- names(array_dims) - - # Merge the chunks. - for (dim_index in 1:length(dim_names)) { - dim_sub_array_of_chunks <- dim_sub_array_of_chunk_indices <- NULL - if (dim_index < length(dim_names)) { - dim_sub_array_of_chunks <- array_dims[(dim_index + 1):length(dim_names)] - names(dim_sub_array_of_chunks) <- dim_names[(dim_index + 1):length(dim_names)] - dim_sub_array_of_chunk_indices <- dim_sub_array_of_chunks - sub_array_of_chunk_indices <- array(1:prod(dim_sub_array_of_chunk_indices), - dim_sub_array_of_chunk_indices) - } else { - sub_array_of_chunk_indices <- NULL - } - sub_array_of_chunks <- vector('list', prod(dim_sub_array_of_chunks)) - dim(sub_array_of_chunks) <- dim_sub_array_of_chunks - for (i in 1:prod(dim_sub_array_of_chunks)) { - if (!is.null(sub_array_of_chunk_indices)) { - chunk_sub_indices <- which(sub_array_of_chunk_indices == i, arr.ind = TRUE)[1, ] - } else { - chunk_sub_indices <- NULL - } - for (j in 1:(array_dims[dim_index])) { - new_chunk <- do.call('[[', c(list(x = array_of_arrays), - as.list(c(j, chunk_sub_indices)))) - if (is.null(new_chunk)) { - stop("Chunks missing.") - } - if (is.null(sub_array_of_chunks[[i]])) { - sub_array_of_chunks[[i]] <- new_chunk - } else { - sub_array_of_chunks[[i]] <- MergeArrays(sub_array_of_chunks[[i]], - new_chunk, - dim_names[dim_index]) - } - } - } - array_of_arrays <- sub_array_of_chunks - rm(sub_array_of_chunks) - gc() - } - - array_of_arrays[[1]] -} diff --git a/README.md b/README.md index 3bdb2c32e0935055b565bce470503e0bc12ec67f..df71716eaf3f4867dd0beeec8d3ff30bb4ad9ae5 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,39 @@ -## multiApply +## multiApply [![build status](https://earth.bsc.es/gitlab/ces/multiApply/badges/master/build.svg)](https://earth.bsc.es/gitlab/ces/multiApply/commits/master) [![CRAN version](http://www.r-pkg.org/badges/version/multiApply)](https://cran.r-project.org/package=multiApply) [![coverage report](https://earth.bsc.es/gitlab/ces/multiApply/badges/master/coverage.svg)](https://earth.bsc.es/gitlab/ces/multiApply/commits/master) [![License: LGPL v3](https://img.shields.io/badge/License-LGPL%20v3-blue.svg)](https://www.gnu.org/licenses/lgpl-3.0) [![CRAN RStudio Downloads](https://cranlogs.r-pkg.org/badges/multiApply)](https://cran.rstudio.com/web/packages/multiApply/index.html) -[![build status](https://earth.bsc.es/gitlab/ces/multiApply/badges/master/build.svg)](https://earth.bsc.es/gitlab/ces/multiApply/commits/master) -[![coverage report](https://earth.bsc.es/gitlab/ces/multiApply/badges/master/coverage.svg)](https://earth.bsc.es/gitlab/ces/multiApply/commits/master) -[![CRAN version](http://www.r-pkg.org/badges/version/multiApply)](https://cran.r-project.org/package=multiApply) -[![CRAN RStudio Downloads](https://cranlogs.r-pkg.org/badges/multiApply)](https://cran.rstudio.com/web/packages/multiApply/index.html) +This package includes the function `Apply` as its only function. It extends the `apply` function to applications in which a function needs to be applied simultaneously over multiple input arrays. Although this can be done manually with for loops and calls to the base apply function, in many cases it can be a challenging task which can very easily result in error-prone or memory-unefficient code. -This package extends the apply and plyr families of functions to applications which involve the use of multiple arrays as input, and is useful to apply a function taking multiple numeric objects as input across multiple multi-dimensional arrays. +A very simple example follows showing the kind of situation where `Apply` can be useful: imagine you have two arrays, each containing five 2x2 matrices, and you want to perform the multiplication of each of the five pairs of matrices. Next, one of the best ways to do this with base R: -This is especially useful for climate data related applications, where data is often distributed across multiple arrays with different dimensions (e.g experimental array 1, experimental array 2 and the observations). The `multiApply::Apply` function reduces the need to write loops for every application. +```r +library(plyr) +library(abind) + +A <- array(1:20, c(5, 2, 2)) +B <- array(1:20, c(5, 2, 2)) + +D <- aaply(X = abind(A, B, along = 4), + MARGINS = 1, + FUN = function(x) x[,,1] %*% x[,,2]) +``` + +Although it is not excessively complex, the choosen example is very simple and the complexity would increase as the function to apply required additional dimensions or inputs, and would be unapplicable if multiple outputs were to be returned. In addition, the function to apply (matrix multiplication) had to be redefined for this particular case (multiplication of the first matrix by the second). + +Next, an example of how to reach the same results using `Apply`: + +```r +library(multiApply) + +A <- array(1:20, c(5, 2, 2)) +B <- array(1:20, c(5, 2, 2)) + +D <- Apply(data = list(A, B), + target_dims = c(2, 3), + fun = "%*%")$output1 +``` + +This solution takes half the time to complete, and is cleaner and extensible to functions receiving any number of inputs with any number of dimensions, or returning any number of outputs. Although the peak RAM usage (as measured with `peakRAM`) of both solutions in this example is about the same, it is challenging to avoid memory duplications when using custom code in more complex applications, and can usually require hours of dedication. `Apply` scales well to large inputs and has been designed to be fast and avoid memory duplications. + +In contrast to `apply` and variants, this package suggests the use of 'target dimensions' as opposite to the 'margins' for specifying the dimensions relevant to the function to be applied. Additionally, it supports functions returning multiple vector or arrays, and can transparently uses multi-core. ### Installation @@ -50,7 +76,7 @@ income <- Apply(data = list(sales_amount, sales_price), target_dims = list(c('item', 'day'), 'item'), income_function) -dim(income[[1]]) +dim(income$output1) # store # 5 ``` diff --git a/man/Apply.Rd b/man/Apply.Rd index 592c6af89374312ba94fed78329d1837656bb3b7..4fe37e951ce203ef6ca4b605a45d0b86cd41c5c7 100644 --- a/man/Apply.Rd +++ b/man/Apply.Rd @@ -2,39 +2,39 @@ % Please edit documentation in R/Apply.R \name{Apply} \alias{Apply} -\title{Wrapper for Applying Atomic Functions to Arrays.} +\title{Apply Functions to Multiple Multidimensional Arrays or Vectors} \usage{ Apply(data, target_dims = NULL, fun, ..., output_dims = NULL, margins = NULL, guess_dim_names = TRUE, ncores = NULL, split_factor = 1) } \arguments{ -\item{data}{A single object (vector, matrix or array) or a list of objects. They must be in the same order as expected by fun.} +\item{data}{One or a list of numeric object (vector, matrix or array). They must be in the same order as expected by the function provided in the parameter 'fun'. The dimensions do not necessarily have to be ordered. If the 'target_dims' require a different order than the provided, \code{Apply} will automatically reorder the dimensions as needed.} -\item{target_dims}{List of vectors containing the dimensions to be input into fun for each of the objects in the data. These vectors can contain either integers specifying the dimension position, or characters corresponding to the dimension names. This parameter is mandatory if margins is not specified. If both margins and target_dims are specified, margins takes priority over target_dims.} +\item{target_dims}{One or a list of vectors (or NULLs) containing the dimensions to be input into fun for each of the objects in the data. If a single vector of target dimensions is specified and multiple inputs are provided in 'data, then the single set of target dimensions is re-used for all of the inputs. These vectors can contain either integers specifying the position of the dimensions, or character strings corresponding to the dimension names. This parameter is mandatory if 'margins' are not specified. If both 'margins' and 'target_dims' are specified, 'margins' takes priority.} -\item{fun}{Function to be applied to the arrays.} +\item{fun}{Function to be applied to the arrays. Must receive as many inputs as provided in 'data', each with as many dimensions as specified in 'target_dims' or as the total number of dimensions in 'data' minus the ones specified in 'margins'. The function can receive other additional fixed parameters (see parameter '...' of \code{Apply}). The function can return one or a list of numeric vectors or multidimensional arrays, optionally with dimension names which will be propagated to the final result. The returned list can optionally be named, with a name for each output, which will be propagated to the resulting array. The function can optionally be provided with the attributes 'target_dims' and 'output_dims'. In that case, the corresponding parameters of \code{Apply} do not need to be provided. The function can expect named dimensions for each of its inputs, in the same order as specified in 'target_dims' or, if no 'target_dims' have been provided, in the same order as provided in 'data'.} -\item{...}{Additional arguments to be used in the fun.} +\item{...}{Additional fixed arguments expected by the function provided in the parameter 'fun'.} \item{output_dims}{Optional list of vectors containing the names of the dimensions to be output from the fun for each of the objects it returns (or a single vector if the function has only one output).} -\item{margins}{List of vectors containing the margins for the input objects to be split by. Or, if there is a single vector of margins specified and a list of objects in data, then the single set of margins is applied over all objects. These vectors can contain either integers specifying the dimension position, or characters corresponding to the dimension names. If both margins and target_dims are specified, margins takes priority over target_dims.} +\item{margins}{One or a list of vectors (or NULLs) containing the 'margin' dimensions to be looped over for each input in 'data'. If a single vector of margins is specified and multiple inputs are provided in 'data', then the single set of margins is re-used for all of the inputs. These vectors can contain either integers specifying the position of the margins, or character strings corresponding to the dimension names. If both 'margins' and 'target_dims' are specified, 'margins' takes priority.} \item{guess_dim_names}{Whether to automatically guess missing dimension names for dimensions of equal length across different inputs in 'data' with a warning (TRUE; default), or to crash whenever unnamed dimensions of equa length are identified across different inputs (FALSE).} -\item{ncores}{The number of multicore threads to use for parallel computation.} +\item{ncores}{The number of parallel processes to spawn for the use for parallel computation in multiple cores.} \item{split_factor}{Factor telling to which degree the input data should be split into smaller pieces to be processed by the available cores. By default (split_factor = 1) the data is split into 4 pieces for each of the cores (as specified in ncores). A split_factor of 2 will result in 8 pieces for each of the cores, and so on. The special value 'greatest' will split the input data into as many pieces as possible.} } \value{ -List of arrays or matrices or vectors resulting from applying fun to data. +List of arrays or matrices or vectors resulting from applying 'fun' to 'data'. } \description{ -This wrapper applies a given function, which takes N [multi-dimensional] arrays as inputs (which may have different numbers of dimensions and dimension lengths), and applies it to a list of N [multi-dimensional] arrays with at least as many dimensions as expected by the given function. The user can specify which dimensions of each array (or matrix) the function is to be applied over with the \code{margins} or \code{target_dims} option. A user can apply a function that receives (in addition to other helper parameters) 1 or more arrays as input, each with a different number of dimensions, and returns any number of multidimensional arrays. The target dimensions can be specified by their names. It is recommended to use this wrapper with multidimensional arrays with named dimensions. +This function efficiently applies a given function, which takes N vectors or multi-dimensional arrays as inputs (which may have different numbers of dimensions and dimension lengths), and applies it to a list of N vectors or multi-dimensional arrays with at least as many dimensions as expected by the given function. The user can specify which dimensions of each array the function is to be applied over with the \code{margins} or \code{target_dims} parameters. The function to be applied can receive other helper parameters and return any number of numeric vectors or multidimensional arrays. The target dimensions or margins can be specified by their names, as long as the inputs are provided with dimension names (recommended). This function can also use multi-core in a transparent way if requested via the \code{ncores} parameter.\cr\cr The following steps help to understand how \code{Apply} works:\cr\cr - The function receives N arrays with Dn dimensions each.\cr - The user specifies, for each of the arrays, which of its dimensions are 'target' dimensions (dimensions which the function provided in 'fun' operates with) and which are 'margins' (dimensions to be looped over).\cr - \code{Apply} will generate an array with as many dimensions as margins in all of the input arrays. If a margin is repeated across different inputs, it will appear only once in the resulting array.\cr - For each element of this resulting array, the function provided in the parameter'fun' is applied to the corresponding sub-arrays in 'data'.\cr - If the function returns a vector or a multidimensional array, the additional dimensions will be prepended to the resulting array (in left-most positions).\cr - If the provided function returns more than one vector or array, the process above is carried out for each of the outputs, resulting in a list with multiple arrays, each with the combination of all target dimensions (at the right-most positions) and resulting dimensions (at the left-most positions). } \details{ -When using a single object as input, Apply is almost identical to the apply function. For multiple input objects, the output array will have dimensions equal to the dimensions specified in 'margins'. +When using a single object as input, Apply is almost identical to the apply function (as fast or slightly slower in some cases; with equal or improved -smaller- memory footprint). } \examples{ #Change in the rate of exceedance for two arrays, with different diff --git a/multiApply-manual.pdf b/multiApply-manual.pdf index bf1c86e977e001ee0b102d7b749e031b158ac0d0..a1f26396885bcaa03cdf279c9f38176bab2d08b2 100644 Binary files a/multiApply-manual.pdf and b/multiApply-manual.pdf differ