Commit a06e5067 authored by Nicolau Manubens Gil's avatar Nicolau Manubens Gil
Browse files

Merge branch 'master' into 'production'

Master

See merge request !9
parents 4a55da1d cb0a5956
Pipeline #766 passed with stage
in 1 minute
.git
.gitignore
.gitlab-ci.yml
.tar.gz
.pdf
./.nc
stages:
- build
build:
stage: build
script:
- module load R
- R CMD build --resave-data .
- R CMD check --as-cran multiApply_*.tar.gz
- R -e 'covr::package_coverage()'
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("Alasdair", "Hunter", , "alasdair.hunter@bsc.es", role = c("aut", "cre")),
person("Nicolau", "Manubens", , "nicolau.manubens@bsc.es", role = "aut"))
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 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.
person("Nicolau", "Manubens", , "nicolau.manubens@bsc.es", role = "aut"),
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 with its only function, Apply, which efficiently applies functions taking one or a list of multiple unidimensional or multidimensional numeric arrays (or combinations thereof) as input. The input arrays can have different numbers of dimensions as well as different dimension lengths, and the applied function can return one or a list of unidimensional or multidimensional arrays as output. This saves development time by preventing the R user from writing often error-prone and memory-unefficient loops dealing with multiple complex arrays. Also, a remarkable feature of Apply is the transparent use of multi-core through its parameter 'ncores'. In contrast to the base apply function, this package suggests the use of 'target dimensions' as opposite to the 'margins' for specifying the dimensions relevant to the function to be applied.
Depends:
R (>= 3.2.0)
Imports:
abind,
doParallel,
foreach,
plyr
Suggests:
testthat
License: LGPL-3
URL: https://earth.bsc.es/gitlab/ces/multiApply
BugReports: https://earth.bsc.es/gitlab/ces/multiApply/issues
......
# Generated by roxygen2: do not edit by hand
importFrom(abind, abind)
importFrom(foreach, registerDoSEQ)
importFrom(doParallel, registerDoParallel)
importFrom(plyr, splat)
importFrom(plyr, llply)
importFrom(stats, setNames)
export(Apply)
importFrom(doParallel,registerDoParallel)
importFrom(foreach,registerDoSEQ)
importFrom(plyr,llply)
importFrom(plyr,splat)
This diff is collapsed.
# Function to permute arrays of non-atomic elements (e.g. POSIXct)
.aperm2 <- function(x, new_order) {
y <- array(1:length(x), dim = dim(x))
y <- aperm(y, new_order)
old_dims <- dim(x)
x <- x[as.vector(y)]
if (is.numeric(x)) {
x <- aperm(x, new_order)
} else {
y <- array(1:length(x), dim = dim(x))
y <- aperm(y, new_order)
x <- x[as.vector(y)]
}
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]]
}
---
title: "Apply a Function Taking Multiple Numeric Objects as Input Across Multiple Arrays"
author: "Alasdair"
date: "14 July 2017"
output: html_document
---
## 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)
This package extends the apply and plyr families of functions to applications which involve the use of multiple arrays as input.
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, it can often be a challenging task which can easily result in error-prone or memory-unefficient code.
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 write loops for every application.
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 (plus some helper libraries):
```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])
```
Since the choosen use case is very simple, this solution is not excessively complex, but 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 along the third dimension by the second along the third dimension).
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 (as measured with `microbenchmark` with inputs of different sizes), 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.
Additionally, multi-code computation can be enabled via the `ncores` parameter, as shown next. Although in this minimalist example using multi-core would make the execution slower, in applications where the inputs are larger the wall-clock time is reduced dramatically.
```r
D <- Apply(data = list(A, B),
target_dims = c(2, 3),
fun = "%*%",
ncores = 4)$output1
```
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
In order to install and load the latest published version of the package on CRAN, you can run the following lines in your R session:
```r
install.packages('multiApply')
library(multiApply)
```
Also, you can install the latest stable version from the GitHub repository as follows:
```r
devtools::install_git('https://earth.bsc.es/gitlab/ces/multiApply')
```
### How to use
This package consistis in a single function, `Apply`, which is used in a similar fashion as the base `apply`. Full documentation can be found in `?Apply`.
A simple example is provided next. In this example, we have two data arrays. The first, with information on the number of items sold in 5 different stores (located in different countries) during the past 1000 days, for 200 different items. The second, with information on the price point for each item in each store.
The example shows how to compute the total income for each of the stores, straightforwardly combining the input data arrays, by automatically applying repeatedly the 'atomic' function that performs only the essential calculations for a single case.
```r
dims <- c(store = 5, item = 200, day = 1000)
sales_amount <- array(rnorm(prod(dims)), dims)
dims <- c(store = 5, item = 200)
sales_price <- array(rnorm(prod(dims)), dims)
income_function <- function(x, y) {
# Expected inputs:
# x: array with dimensions (item, day)
# y: price point vector with dimension (item)
sum(rowSums(x) * y)
}
income <- Apply(data = list(sales_amount, sales_price),
target_dims = list(c('item', 'day'), 'item'),
income_function)
dim(income$output1)
# store
# 5
```
......@@ -2,44 +2,51 @@
% 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, AtomicFun, ..., output_dims = NULL,
margins = NULL, ncores = NULL)
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 AtomicFun.}
\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 AtomicFun 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{AtomicFun}{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 AtomicFun.}
\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 AtomicFun for each of the objects it returns (or a single vector if the function has only one output).}
\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{ncores}{The number of multicore threads to use for parallel computation.}
\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 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 AtomicFun 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
#dimensions, for some matrix of exceedances.
data = list(array(rnorm(2000), c(10,10,20)), array(rnorm(1000), c(10,10,10)),
array(rnorm(100), c(10, 10)))
test_fun <- function(x, y, z) {((sum(x > z) / (length(x))) /
(sum(y > z) / (length(y)))) * 100}
margins = list(c(1, 2), c(1, 2), c(1,2))
test <- Apply(data, margins = margins, AtomicFun = "test_fun")
data <- list(array(rnorm(1000), c(5, 10, 20)),
array(rnorm(500), c(5, 10, 10)),
array(rnorm(50), c(5, 10)))
test_fun <- function(x, y, z) {
((sum(x > z) / (length(x))) /
(sum(y > z) / (length(y)))) * 100
}
test <- Apply(data, target = list(3, 3, NULL), test_fun)
}
\references{
Wickham, H (2011), The Split-Apply-Combine Strategy for Data Analysis, Journal of Statistical Software.
......
No preview for this file type
library(testthat)
library(multiApply)
test_check("multiApply")
context("Sanity checks")
test_that("required arguments are provided", {
expect_error(
Apply(),
"missing, with no default"
)
expect_error(
Apply(1:10),
"missing, with no default"
)
expect_error(
Apply(1:10, fun = mean),
"must be specified"
)
})
test_that("arguments have the right type", {
expect_equal(
Apply(1:10, NULL, mean),
list(output1 = array(1:10, dim = 10))
)
expect_error(
Apply(numeric(0), NULL, mean),
"must be of length > 0"
)
#expect_error(
#)
})
#context("Parameter order")
#
#test_that("", {
# expect_that(
# Apply(),
# throws_error("")
# )
#})
This diff is collapsed.
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment