R/core.generators.R

Defines functions genPop genPopBin genPopPerm genPopReal

#' @title
#' Population generators
#'
#' @description Utility functions to build a set of individuals. The function
#' \code{genPop} expects an R expression and a number \eqn{n} in order to create a list
#' of \eqn{n} individuals based on the given expression. Functions \code{genPopBin},
#' \code{genPopPerm} and \code{genPopReal} are shortcuts for initializing populations
#' of binary strings, permutations or real-valued vectors respectively.
#'
#' @param expr [R expression]\cr
#'   Expression to generate a single individual.
#' @param n [\code{integer(1)}]\cr
#'   Number of individuals to create.
#' @template arg_n_dim
#' @param lower [\code{numeric}]\cr
#'   Vector of minimal values for each parameter of the decision space in case
#'   of float encoding.
#' @param upper [\code{numeric}]\cr
#'   Vector of maximal values for each parameter of the decision space in case
#'   of float encoding.
#' @return [\code{list}]
#' @family population_generators
#' @rdname population_generators
#' @name population_generators
#' @export
genPop = function(expr, n) {
  sapply(integer(n), eval.parent(substitute(function(...) expr)), simplify = FALSE)
}

#' @rdname population_generators
#' @export
genPopBin = function(n, d) {
  genPop(genBitstring(d), n)
}

#' @rdname population_generators
#' @export
genPopPerm = function(n, d) {
  genPop(sample(seq_len(d)), n)
}

#' @rdname population_generators
#' @export
genPopReal = function(n, d, lower, upper) {
  #FIXME: set lower to -min representable and upper
  if (length(lower) == 1L)
    lower = rep(lower, d)
  if (length(upper) == 1L)
    upper = rep(upper, d)

  lapply(seq_len(n), function(i) {
    ind = sapply(seq_len(d), function(j) {
      runif(1L, min = lower[j], max = upper[j])
    })
    return(ind)
  })
}
jakobbossek/ecr3 documentation built on Nov. 14, 2019, 7:47 p.m.