R/interpolation.R

Defines functions interpolation

Documented in interpolation

#' @title Parallel version of multilinear interpolation generator for function approximation
#' @description Parallel version of multilinear interpolation generator for function approximation
#' @param evalfun The objective function to be approximated.
#' @param grid_list A list for grid points (each element of list is a vector represents ticklabels on a dimension). The number of list elements are the dimension of function inputs.
#' @param cores The numbers of cores (threads) of your machine to conduct parallel computing.
#' @param int Logical indicator. \code{int = TRUE} interpolant value multiplied by 10^7 then convert to interger to save memory. Original interpolant if \code{int = FALSE}.
#' @param ... Other inputs for objective functions to be passed through.
#' @return \code{interpolation} returns
#' \itemize{
#'       \item{value: }{A list of of length p corresponding to each variable. Returns NA for continuous variable; proportion of zeros for binary/truncated variables; the cumulative proportions of zeros and ones (e.g. first value is proportion of zeros, second value is proportion of zeros and ones) for ternary variable.}
#'       \item{interpolant: }{An interpolant function generated by \code{chebpol::chebpol} for interplation.}
#' }
#' @import doFuture
#' @import foreach
#' @import future
#' @importFrom parallel detectCores
#' @export
#' @examples
#' \dontrun{grid_list = list(seq(-0.5, 0.5, by = 0.5), seq(-0.5, 0.5, by = 0.5))
#' objfun = function(x, y) {x^2 + sqrt(y)}
#' evalfun = function(X) {objfun(X[1], X[2])}
#' value = interpolation(evalfun = evalfun, grid_list = grid_list)$value
#' interpolant = interpolation(evalfun = evalfun, grid_list = grid_list)$interpolant}


interpolation = function(evalfun, grid_list, cores = detectCores(), int = FALSE, ...) {
  grid_all = expand.grid(grid_list)
  registerDoFuture()
  plan(multicore, workers = cores)
  j = NULL
  value_vector =
    foreach (j = 1:nrow(grid_all), .combine = c) %dopar% {
      grid_input = as.numeric(grid_all[j, ])
      value_list = evalfun(grid_input, ...)
    }
  d_grid = length(grid_list)
  dim_value = NULL
  for (i in 1:d_grid) {
    dim_value = c(dim_value, length(grid_list[[i]]))
  }
  if (int) {
    value = array(as.integer(value_vector * 10^7), dim = dim_value)
  } else {
    value = array(value_vector, dim = dim_value)
  }
  interpolant = ipol(val = value, grid = grid_list)
  return (list(value = value, interpolant = interpolant))
}

Try the latentcor package in your browser

Any scripts or data that you put into this service are public.

latentcor documentation built on Sept. 6, 2022, 1:06 a.m.