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)
#' 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 AtomicFun.
#' @param 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.
#' @param AtomicFun Function to be applied to the arrays.
#' @param ... Additional arguments to be used in the AtomicFun.
#' @param 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).
#' @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 ncores The number of multicore threads to use for parallel computation.
#' @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 AtomicFun to data.
#' 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 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 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 (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
#' #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")
Apply <- function(data, target_dims = NULL, AtomicFun, ..., output_dims = NULL,
margins = NULL, ncores = NULL) {
#' 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)
#' @importFrom foreach registerDoSEQ
#' @importFrom doParallel registerDoParallel
#' @importFrom plyr splat llply
Apply <- function(data, target_dims = NULL, fun, ...,
output_dims = NULL, margins = NULL, guess_dim_names = TRUE,
ncores = NULL, split_factor = 1) {
# Check data
if (!is.list(data)) {
data <- list(data)
......@@ -32,7 +41,12 @@ Apply <- function(data, target_dims = NULL, AtomicFun, ..., output_dims = NULL,
}
is_vector <- rep(FALSE, length(data))
is_unnamed <- rep(FALSE, length(data))
unnamed_dims <- c()
guessed_any_dimnames <- FALSE
for (i in 1 : length(data)) {
if (length(data[[i]]) < 1) {
stop("Arrays in 'data' must be of length > 0.")
}
if (is.null(dim(data[[i]]))) {
is_vector[i] <- TRUE
is_unnamed[i] <- TRUE
......@@ -43,41 +57,89 @@ Apply <- function(data, target_dims = NULL, AtomicFun, ..., output_dims = NULL,
stop("Dimension names of arrays in 'data' must be at least ",
"one character long.")
}
if (length(unique(names(dim(data[[i]])))) != length(names(dim(data[[i]])))) {
stop("Arrays in 'data' must not have repeated dimension names.")
}
if (any(is.na(names(dim(data[[i]]))))) {
stop("Arrays in 'data' must not have NA as dimension names.")
}
} else {
is_unnamed[i] <- TRUE
new_unnamed_dims <- c()
unnamed_dims_copy <- unnamed_dims
for (j in 1 : length(dim(data[[i]]))) {
len_of_dim_j <- dim(data[[i]])[j]
found_match <- which(unnamed_dims_copy == len_of_dim_j)
if (!guess_dim_names && (length(found_match) > 0)) {
stop("Arrays in 'data' have multiple unnamed dimensions of the ",
"same length. Please provide dimension names.")
}
if (length(found_match) > 0) {
found_match <- found_match[1]
names(dim(data[[i]]))[j] <- names(unnamed_dims_copy[found_match])
unnamed_dims_copy <- unnamed_dims_copy[-found_match]
guessed_any_dimnames <- TRUE
} else {
new_dim <- len_of_dim_j
names(new_dim) <- paste0('_unnamed_dim_', length(unnamed_dims) +
length(new_unnamed_dims) + 1, '_')
new_unnamed_dims <- c(new_unnamed_dims, new_dim)
names(dim(data[[i]]))[j] <- names(new_dim)
}
}
unnamed_dims <- c(unnamed_dims, new_unnamed_dims)
}
}
if (guessed_any_dimnames) {
dim_names_string <- ""
for (i in 1:length(data)) {
dim_names_string <- c(dim_names_string, "\n\tInput ", i, ":",
sapply(capture.output(print(dim(data[[i]]))),
function(x) paste0('\n\t\t', x)))
}
warning("Guessed names for some unnamed dimensions of equal length ",
"found across different inputs in 'data'. Please check ",
"carefully the assumed names below are correct, or provide ",
"dimension names for safety, or disable the parameter ",
"'guess_dim_names'.", dim_names_string)
}
# Check AtomicFun
if (is.character(AtomicFun)) {
try({AtomicFun <- get(AtomicFun)}, silent = TRUE)
if (!is.function(AtomicFun)) {
stop("Could not find the function '", AtomicFun, "'.")
# Check fun
if (is.character(fun)) {
fun_name <- fun
err <- try({
fun <- get(fun)
}, silent = TRUE)
if (!is.function(fun)) {
stop("Could not find the function '", fun_name, "'.")
}
}
if (!is.function(AtomicFun)) {
stop("Parameter 'AtomicFun' must be a function or a character string ",
if (!is.function(fun)) {
stop("Parameter 'fun' must be a function or a character string ",
"with the name of a function.")
}
if ('startR_step' %in% class(AtomicFun)) {
if (!is.null(attributes(fun))) {
if (is.null(target_dims)) {
target_dims <- attr(AtomicFun, 'target_dims')
if ('target_dims' %in% names(attributes(fun))) {
target_dims <- attr(fun, 'target_dims')
}
}
if (is.null(output_dims)) {
output_dims <- attr(AtomicFun, 'output_dims')
if ('output_dims' %in% names(attributes(fun))) {
output_dims <- attr(fun, 'output_dims')
}
}
}
# Check target_dims and margins
if (is.null(margins) && is.null(target_dims)) {
arglist <- as.list(match.call())
if (!any(c('margins', 'target_dims') %in% names(arglist)) &&
is.null(target_dims)) {
stop("One of 'margins' or 'target_dims' must be specified.")
}
if (!is.null(margins)) {
target_dims <- NULL
}
margins_names <- vector('list', length(data))
target_dims_names <- vector('list', length(data))
if (!is.null(margins)) {
if ('margins' %in% names(arglist)) {
# Check margins and build target_dims accordingly
if (!is.list(margins)) {
margins <- rep(list(margins), length(data))
......@@ -87,6 +149,9 @@ Apply <- function(data, target_dims = NULL, AtomicFun, ..., output_dims = NULL,
stop("Parameter 'margins' must be one or a list of numeric or ",
"character vectors.")
}
if (any(sapply(margins, function(x) is.character(x) && (length(x) == 0)))) {
stop("Parameter 'margins' must not contain length-0 character vectors.")
}
duplicate_dim_specs <- sapply(margins,
function(x) {
length(unique(x)) != length(x)
......@@ -117,10 +182,15 @@ Apply <- function(data, target_dims = NULL, AtomicFun, ..., output_dims = NULL,
margins_names[[i]] <- margins[[i]]
margins[[i]] <- margins2_new_num
}
if (!is.null(names(dim(data[[i]])))) {
if (length(margins[[i]]) == length(dim(data[[i]]))) {
target_dims_names[i] <- list(NULL)
target_dims[i] <- list(NULL)
margins_names[[i]] <- names(dim(data[[i]]))
} else {
margins_names[[i]] <- names(dim(data[[i]]))[margins[[i]]]
target_dims_names[[i]] <- names(dim(data[[i]]))[- margins[[i]]]
target_dims[[i]] <- (1 : length(dim(data[[i]])))[- margins[[i]]]
}
target_dims[[i]] <- (1 : length(dim(data[[i]])))[- margins[[i]]]
} else {
target_dims[[i]] <- 1 : length(dim(data[[i]]))
if (!is.null(names(dim(data[[i]])))) {
......@@ -134,12 +204,12 @@ Apply <- function(data, target_dims = NULL, AtomicFun, ..., output_dims = NULL,
target_dims <- rep(list(target_dims), length(data))
}
if (any(!sapply(target_dims,
function(x) is.character(x) || is.numeric(x)))) {
function(x) is.character(x) || is.numeric(x) || is.null(x)))) {
stop("Parameter 'target_dims' must be one or a list of numeric or ",
"character vectors.")
}
if (any(sapply(target_dims, length) == 0)) {
stop("Parameter 'target_dims' must not contain length-0 vectors.")
if (any(sapply(target_dims, function(x) is.character(x) && (length(x) == 0)))) {
stop("Parameter 'target_dims' must not contain length-0 character vectors.")
}
duplicate_dim_specs <- sapply(target_dims,
function(x) {
......@@ -151,29 +221,41 @@ Apply <- function(data, target_dims = NULL, AtomicFun, ..., output_dims = NULL,
}
margins <- vector('list', length(data))
for (i in 1 : length(data)) {
if (is.character(unlist(target_dims[i]))) {
if (is.null(names(dim(data[[i]])))) {
stop("Parameter 'target_dims' contains dimension names, but ",
"some of the corresponding objects in 'data' do not have ",
"dimension names.")
}
targs2 <- target_dims[[i]]
targs2_new_num <- c()
for (j in 1 : length(targs2)) {
matches <- which(names(dim(data[[i]])) == targs2[j])
if (length(matches) < 1) {
stop("Could not find dimension '", targs2[j], "' in ", i,
"th object provided in 'data'.")
if (length(target_dims[[i]]) > 0) {
if (is.character(unlist(target_dims[i]))) {
if (is.null(names(dim(data[[i]])))) {
stop("Parameter 'target_dims' contains dimension names, but ",
"some of the corresponding objects in 'data' do not have ",
"dimension names.")
}
targs2 <- target_dims[[i]]
targs2_new_num <- c()
for (j in 1 : length(targs2)) {
matches <- which(names(dim(data[[i]])) == targs2[j])
if (length(matches) < 1) {
stop("Could not find dimension '", targs2[j], "' in ", i,
"th object provided in 'data'.")
}
targs2_new_num[j] <- matches[1]
}
targs2_new_num[j] <- matches[1]
target_dims_names[[i]] <- target_dims[[i]]
target_dims[[i]] <- targs2_new_num
}
if (length(target_dims[[i]]) == length(dim(data[[i]]))) {
margins_names[i] <- list(NULL)
margins[i] <- list(NULL)
target_dims_names[[i]] <- names(dim(data[[i]]))
} else {
target_dims_names[[i]] <- names(dim(data[[i]]))[target_dims[[i]]]
margins_names[[i]] <- names(dim(data[[i]]))[- target_dims[[i]]]
margins[[i]] <- (1 : length(dim(data[[i]])))[- target_dims[[i]]]
}
} else {
margins[[i]] <- 1 : length(dim(data[[i]]))
if (!is.null(names(dim(data[[i]])))) {
margins_names[[i]] <- names(dim(data[[i]]))
}
target_dims_names[[i]] <- target_dims[[i]]
target_dims[[i]] <- targs2_new_num
}
if (!is.null(names(dim(data[[i]])))) {
margins_names[[i]] <- names(dim(data[[i]]))[- target_dims[[i]]]
}
margins[[i]] <- (1 : length(dim(data[[i]])))[- target_dims[[i]]]
}
}
# Reorder dimensions of input data for target dims to be left-most
......@@ -185,7 +267,11 @@ Apply <- function(data, target_dims = NULL, AtomicFun, ..., output_dims = NULL,
marg_dims <- (1 : length(dim(data[[i]])))[- target_dims[[i]]]
data[[i]] <- .aperm2(data[[i]], c(target_dims[[i]], marg_dims))
target_dims[[i]] <- 1 : length(target_dims[[i]])
margins[[i]] <- (length(target_dims[[i]]) + 1) : length(dim(data[[i]]))
target_dims_names[[i]] <- names(dim(data[[i]]))[target_dims[[i]]]
if (length(target_dims[[i]]) < length(dim(data[[i]]))) {
margins[[i]] <- (length(target_dims[[i]]) + 1) : length(dim(data[[i]]))
margins_names[[i]] <- names(dim(data[[i]]))[margins[[i]]]
}
}
}
}
......@@ -218,16 +304,11 @@ Apply <- function(data, target_dims = NULL, AtomicFun, ..., output_dims = NULL,
# Consistency checks of margins of all input objects
# for each data array, add its margins to the list if not present.
# if there are unnamed margins in the list, check their size matches the margins being added
# and simply assing them a name
# those margins present, check that they match
# if unnamed margins, check consistency with found margins
# if more mrgins than found, add numbers to the list, without names
# with this we end up with a named list of margin sizes
# for data arrays with unnamed margins, we can assume their margins names are those of the first entries in the resulting list
all_found_margins_lengths <- afml <- list()
for (i in 1:length(data)) {
if (!is.null(margins_names[[i]])) {
#if (!is.null(margins_names[[i]])) {
if (length(afml) > 0) {
matches <- which(margins_names[[i]] %in% names(afml))
if (length(matches) > 0) {
......@@ -239,72 +320,11 @@ Apply <- function(data, target_dims = NULL, AtomicFun, ..., output_dims = NULL,
} else {
margs_to_add <- as.list(dim(data[[i]])[margins[[i]]])
}
unnamed_margins <- which(sapply(names(afml), nchar) == 0)
if (length(unnamed_margins) > 0) {
stop_with_error <- FALSE
if (length(unnamed_margins) <= length(margs_to_add)) {
if (any(unlist(afml[unnamed_margins]) != unlist(margs_to_add[1:length(unnamed_margins)]))) {
stop_with_error <- TRUE
}
names(afml)[unnamed_margins] <- names(margs_to_add)[1:length(unnamed_margins)]
margs_to_add <- margs_to_add[- (1:length(margs_to_add))]
} else {
if (any(unlist(afml[unnamed_margins[1:length(margs_to_add)]]) != unlist(margs_to_add))) {
stop_with_error <- TRUE
}
names(afml)[unnamed_margins[1:length(margs_to_add)]] <- names(margs_to_add)
margs_to_add <- list()
}
if (stop_with_error) {
stop("Found unnamed margins (for some objects in parameter ",
"'data') that have been associated by their position to ",
"named margins in other objects in 'data' and do not have ",
"matching length. It could also be that the unnamed ",
"margins don not follow the same order as the named ",
"margins. In that case, either put the corresponding names ",
"to the dimensions of the objects in 'data', or put them ",
"in a consistent order.")
}
}
afml <- c(afml, margs_to_add)
} else {
afml <- as.list(dim(data[[i]])[margins[[i]]])
}
} else {
margs_to_add <- as.list(dim(data[[i]])[margins[[i]]])
names(margs_to_add) <- rep('', length(margs_to_add))
if (length(afml) > 0) {
stop_with_error <- FALSE
if (length(afml) >= length(margs_to_add)) {
if (any(unlist(margs_to_add) != unlist(afml[1:length(margs_to_add)]))) {
stop_with_error <- TRUE
}
} else {
if (any(unlist(margs_to_add)[1:length(afml)] != unlist(afml))) {
stop_with_error <- TRUE
}
margs_to_add <- margs_to_add[- (1:length(afml))]
afml <- c(afml, margs_to_add)
}
if (stop_with_error) {
stop("Found unnamed margins (for some objects in parameter ",
"'data') that have been associated by their position to ",
"named margins in other objects in 'data' and do not have ",
"matching length. It could also be that the unnamed ",
"margins don not follow the same order as in other ",
"objects. In that case, either put the corresponding names ",
"to the dimensions of the objects in 'data', or put them ",
"in a consistent order.")
}
} else {
afml <- margs_to_add
}
}
}
missing_margin_names <- which(names(afml) == '')
if (length(missing_margin_names) > 0) {
names(afml)[missing_margin_names] <- paste0('_unnamed_margin_',
1:length(missing_margin_names), '_')
#}
}
# afml is now a named list with the lenghts of all margins. Each margin
# appears once only. If some names are not provided, they are set automatically
......@@ -316,8 +336,7 @@ Apply <- function(data, target_dims = NULL, AtomicFun, ..., output_dims = NULL,
# across them, and use data arrays repeatedly as needed.
margins_afml <- margins
for (i in 1:length(data)) {
if (!is.null(margins_names[[i]])) {
if (length(margins[[i]]) > 0) {
margins_afml[[i]] <- sapply(margins_names[[i]],
function(x) {
sapply(x,
......@@ -327,11 +346,6 @@ Apply <- function(data, target_dims = NULL, AtomicFun, ..., output_dims = NULL,
)
}
)
} else if (length(margins_afml[[i]]) > 0) {
margins_afml[[i]] <- margins_afml[[i]] - min(margins_afml[[i]]) + 1
# The missing margin and dim names are filled in.
margins_names[[i]] <- names(afml)[margins_afml[[i]]]
names(dim(data[[i]]))[margins[[i]]] <- margins_names[[i]]
}
}
common_margs <- margins_afml[[1]]
......@@ -347,79 +361,41 @@ Apply <- function(data, target_dims = NULL, AtomicFun, ..., output_dims = NULL,
}
}
}
non_common_margs <- 1:length(afml)
if (length(common_margs) > 0) {
non_common_margs <- non_common_margs[- common_margs]
if (length(afml) > 0) {
non_common_margs <- 1:length(afml)
if (length(common_margs) > 0) {
non_common_margs <- non_common_margs[- common_margs]
}
} else {
non_common_margs <- NULL
}
# common_margs is now a numeric vector with the indices of the common
# margins (i.e. their position in afml)
# non_common_margs is now a numeric vector with the indices of the
# non-common margins (i.e. their position in afml)
.isolate <- function(data, margin_length, drop = FALSE) {
eval(dim(environment()$data))
structure(list(env = environment(), index = margin_length,
drop = drop, subs = as.name("[")),
class = c("indexed_array"))
}
.consolidate <- function(subsets, dimnames, out_dims) {
lapply(setNames(1:length(subsets), names(subsets)),
function(x) {
if (length(out_dims[[x]]) > 0) {
dims <- dim(subsets[[x]])
if (!is_unnamed[x]) {
names(dims) <- dimnames[[x]]
}
dims <- dims[out_dims[[x]]]
array(subsets[[x]], dim = dims)
} else {
as.vector(subsets[[x]])
}
})
}
data_indexed <- vector('list', length(data))
data_indexed_indices <- vector('list', length(data))
for (i in 1 : length(data)) {
margs_i <- which(names(dim(data[[i]])) %in% names(afml[c(non_common_margs, common_margs)]))
false_margs_i <- which(margs_i %in% target_dims[[i]])
margs_i <- setdiff(margs_i, false_margs_i)
if (length(margs_i) > 0) {
margin_length <- lapply(dim(data[[i]]), function(x) 1 : x)
margin_length[- margs_i] <- ""
} else {
margin_length <- as.list(rep("", length(dim(data[[i]]))))
}
margin_length <- expand.grid(margin_length, KEEP.OUT.ATTRS = FALSE,
stringsAsFactors = FALSE)
data_indexed[[i]] <- .isolate(data[[i]], margin_length)
if (length(margs_i) > 0) {
data_indexed_indices[[i]] <- array(1:prod(dim(data[[i]])[margs_i]),
dim = dim(data[[i]])[margs_i])
} else {
data_indexed_indices[[i]] <- array(1, dim = 1)
}
}
splatted_f <- splat(AtomicFun)
# Iterate along all non-common margins
if (length(c(non_common_margs, common_margs)) > 0) {
marg_inds_ordered <- sort(c(non_common_margs, common_margs))
margins_array <- ma <- array(1:prod(unlist(afml[marg_inds_ordered])),
dim = unlist(afml[marg_inds_ordered]))
margins_array_dims <- mad <- unlist(afml[marg_inds_ordered])
} else {
ma <- array(1)
margins_array_dims <- mad <- NULL
}
arrays_of_results <- NULL
found_first_result <- FALSE
total_size <- prod(dim(ma))
if (!is.null(ncores)) {
chunk_size <- round(total_size / (ncores * 4))
# Sharing workload across cores. Each core will run 4 chunks if possible.
# the larger the split factor, the smaller the amount of data that
# will be processed at once and the finer the granules to be distributed
# across cores, but the larger the overhead for granule startup, etc.
total_size <- prod(mad)
if (split_factor == 'greatest') {
chunks_per_core <- ceiling(total_size / ncores)
} else {
chunk_size <- 4
chunks_per_core <- 4 * split_factor
}
if (!is.null(ncores)) {
chunk_size <- round(total_size / (ncores * chunks_per_core))
}
#} else {
# chunk_size <- 4
#}
if (chunk_size < 1) {
chunk_size <- 1
}
......@@ -429,32 +405,89 @@ Apply <- function(data, target_dims = NULL, AtomicFun, ..., output_dims = NULL,
chunk_sizes <- c(chunk_sizes, total_size %% chunk_size)
}
# need to add progress bar
input_margin_weights <- vector('list', length(data))
for (i in 1:length(data)) {
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]))