R/optimizer_lhs.R

Defines functions lhs_check_count lhs_check_scale lhs_check_bounds lhs_par_names lhs_agreement lhs_best_run lhs_min_distance lhs_trpars_to_unit lhs_unit_to_trpars lhs_unit optimizer_lhs_dispatch lhs_report_error lhs_worker_optimize lhs_worker_eval lhs_worker_init lhs_clean_result lhs_optimize_one lhs_eval_one optimizer_lhs lhs_sample

Documented in lhs_sample optimizer_lhs

#' Latin hypercube sample of parameter sets
#'
#' Draws a Latin hypercube sample of parameter sets within user-specified
#' ranges and returns them on the transformed scale on which
#' \code{\link{optimizer}} works (see \code{\link{transform_pars}}). Each
#' parameter range is divided into \code{n} strata of equal width on the
#' sampling scale and every stratum is sampled exactly once per parameter.
#'
#' @param n Number of parameter sets to draw.
#' @param lower Vector with the lower bounds of the parameters on the
#' original (untransformed) scale. If the vector is named, the names are used
#' for the columns of the result.
#' @param upper Vector with the upper bounds of the parameters on the
#' original (untransformed) scale.
#' @param sampling_scale The scale on which the strata have equal width.
#' Either a single value used for all parameters, or one value per parameter:
#' \itemize{
#'   \item \code{'transformed'}: uniform on the transformed scale
#'   \code{transform_pars(pars)}, i.e. the scale on which the optimization
#'   takes place. Bounds of \code{0} and \code{Inf} are allowed.
#'   \item \code{'original'}: uniform on the original scale. Bounds must be
#'   finite.
#'   \item \code{'log'}: uniform on the logarithm of the original scale.
#'   Bounds must be positive and finite. Useful for parameters that span
#'   several orders of magnitude, such as the carrying capacity K.
#' }
#' @return A matrix with \code{n} rows and \code{length(lower)} columns
#' with the sampled parameter sets on the transformed scale. Use
#' \code{\link{untransform_pars}} to obtain the values on the original scale.
#' @author Rampal S. Etienne
#' @seealso \code{\link{optimizer_lhs}}
#' @examples
#' set.seed(42)
#' trpars <- lhs_sample(n = 5,
#'                      lower = c(lambda = 0.1, mu = 0, K = 10),
#'                      upper = c(lambda = 2, mu = 1, K = 1000),
#'                      sampling_scale = c('transformed', 'transformed', 'log'))
#' untransform_pars(trpars)
#' @export lhs_sample
lhs_sample <- function(n,
                       lower,
                       upper,
                       sampling_scale = 'transformed')
{
  lhs_check_bounds(lower = lower, upper = upper)
  sampling_scale <- lhs_check_scale(sampling_scale = sampling_scale,
                                    lower = lower,
                                    upper = upper)
  lhs_check_count(n, 'n')
  unit <- lhs_unit(n = n, numpar = length(lower))
  trpars <- lhs_unit_to_trpars(unit = unit,
                               lower = lower,
                               upper = upper,
                               sampling_scale = sampling_scale)
  colnames(trpars) <- lhs_par_names(lower)
  return(trpars)
}

#' Carries out optimization from multiple starting points chosen by Latin
#' hypercube sampling
#'
#' A wrapper around \code{\link{optimizer}} that runs the optimization from
#' several starting parameter sets obtained by Latin hypercube sampling (see
#' \code{\link{lhs_sample}}) within user-specified ranges, and returns the
#' best result. Three strategies are available:
#' \describe{
#'   \item{\code{'starts'}}{\code{num_starts} parameter sets are drawn and
#'   each is used as a starting point for \code{optimizer}.}
#'   \item{\code{'screen'}}{\code{num_samples} parameter sets are drawn (a
#'   much finer sample than for \code{'starts'}) and only the likelihood is
#'   computed for each of them. The \code{num_best} parameter sets with the
#'   largest likelihood are then used as starting points for
#'   \code{optimizer}, skipping parameter sets that are adjacent to a
#'   starting point already used (see \code{min_dist}).}
#'   \item{\code{'agree'}}{As \code{'screen'}, but the number of starting
#'   points is not fixed in advance. The \code{num_agree} best parameter sets
#'   are optimized first. If fewer than \code{num_agree} of the optimizations
#'   end up at the best maximum found so far (within the tolerances in
#'   \code{tol_agree}), the next best parameter set is optimized, and so on,
#'   until \code{num_agree} optimizations agree on the best maximum or
#'   \code{max_starts} optimizations have been run.}
#' }
#' The Latin hypercube spreads the samples over the parameter space, but the
#' samples with the largest likelihood tend to lie close together, in the
#' basin of attraction of the same maximum. Optimizing from all of them
#' mostly repeats the same optimization, and agreement among them says little
#' about whether the global maximum has been found. Therefore, in strategies
#' \code{'screen'} and \code{'agree'} a sample is skipped when it lies within
#' \code{min_dist} of a starting point that has already been used, in every
#' parameter. Distances are measured on the sampling scale, with the range of
#' each parameter scaled to [0, 1]. When no samples remain that are far
#' enough from all starting points used so far, \code{min_dist} is halved.
#' The column \code{min_dist} of \code{runs} shows the value in force when
#' each starting point was chosen.
#'
#' \strong{Parallel computing.} With \code{num_cores} larger than 1, or with a
#' cluster supplied as \code{cl}, the likelihood of the samples is computed
#' and/or the optimizations are run in parallel (see \code{parallel_phase}).
#' The workers are separate R processes (a PSOCK cluster, which also works on
#' Windows), not forked processes, so a likelihood function that is itself
#' parallelized, for example with multiple threads set by an argument passed
#' through \code{...}, or with its own cluster, keeps working within each
#' worker. The total number of cores used is then \code{num_cores} times the
#' number used by one likelihood evaluation. Strategies 'starts' and 'screen'
#' divide all optimizations over the workers: a worker starts the next
#' optimization as soon as it has finished one. Strategy 'agree' does the
#' same when the package future is installed: it starts a new optimization
#' whenever a worker is free and checks agreement after each finished
#' optimization. When agreement is reached, optimizations that are still
#' running are abandoned if the cluster was created by \code{optimizer_lhs},
#' and finished (and included in the results) if the cluster was supplied as
#' \code{cl}, so that it can be used again. Without the package future,
#' strategy 'agree' runs the optimizations in batches of as many as there are
#' workers. With strategy 'agree', the number and order of the optimizations
#' can therefore differ from those without parallel computing. The Latin
#' hypercube sample, and hence the candidate starting points, are the same
#' with and without parallel computing. Each optimization on a worker gets
#' its own random number seed, drawn from the random number generator of the
#' main R session, so that optimization methods that use random numbers give
#' the same result whichever worker runs them. The function to be optimized
#' and the arguments in
#' \code{...} are sent to the workers once. A function defined by the user
#' that calls functions from packages other than DDD without \code{::} needs
#' these packages in \code{packages}; a function that uses other objects from
#' the user's workspace needs a cluster set up by the user (with
#' \code{parallel::clusterExport}) and supplied as \code{cl}.
#'
#' \strong{Running the optimizations as separate jobs.} On a computer
#' cluster, it can be more efficient to run each optimization as a separate
#' job (e.g. a job array in SLURM), because such jobs can start as soon as a
#' single core is free. With \code{starts_file}, the starting points are
#' saved to a file (with \code{saveRDS}), in the order in which they would be
#' optimized: \code{num_starts} Latin hypercube samples for strategy
#' 'starts', the \code{num_best} best screened samples for strategy 'screen'
#' and the \code{max_starts} best screened samples for strategy 'agree' (all
#' at least \code{min_dist} apart). With \code{run_optimizations = FALSE}, the
#' function stops after saving them. The file contains a list with the
#' starting points on the original scale (\code{pars}, a matrix with one row
#' per starting point, which can be used as \code{initparsopt} of the maximum
#' likelihood functions) and on the transformed scale (\code{trpars}), a data
#' frame \code{starts} with their positions among the samples, whether they
#' are Latin hypercube samples or the initial guess, their likelihoods and the
#' value of \code{min_dist} when they were chosen, the
#' data frame \code{samples} with all samples, and the settings.
#'
#' The function can also be called through \code{\link{optimizer}}, and hence
#' through all maximum likelihood functions in this package, by supplying a
#' list with the settings for \code{optimizer_lhs} as \code{optimmethod}; see
#' \code{\link{optimizer}}.
#'
#' @inheritParams optimizer
#' @inheritParams lhs_sample
#' @param fun Function to be optimized (maximized). Like in
#' \code{\link{optimizer}}, it must take the transformed parameters to be
#' optimized as an argument called \code{trparsopt}.
#' @param strategy The multi-start strategy: \code{'starts'}, \code{'screen'}
#' or \code{'agree'}; see Description.
#' @param num_starts Number of Latin hypercube samples that are used as
#' starting points (strategy \code{'starts'}).
#' @param num_samples Number of Latin hypercube samples for which only the
#' likelihood is computed (strategies \code{'screen'} and \code{'agree'}).
#' The default is 100 times the number of parameters.
#' @param num_best Number of samples with the largest likelihood that are
#' used as starting points (strategy \code{'screen'}).
#' @param num_agree Number of optimizations that must agree on the best
#' maximum before the search stops (strategy \code{'agree'}).
#' @param max_starts Maximum number of optimizations (strategy
#' \code{'agree'}). The default is \code{10 * num_agree}. Use \code{Inf} to
#' allow all samples with a finite likelihood to be used.
#' @param min_dist Minimum distance between starting points (strategies
#' \code{'screen'} and \code{'agree'}), as a fraction of the range of each
#' parameter on its sampling scale. A sample is skipped as a starting point
#' when it differs by less than \code{min_dist} in every parameter from a
#' starting point that has already been used. Set to 0 to use the best
#' samples regardless of where they are.
#' @param tol_agree Vector of two tolerances used to decide whether two
#' optimization results are the same: 1) absolute tolerance in the maximum
#' (log)likelihood and 2) absolute tolerance in each of the parameters on the
#' transformed scale (the scale on which \code{optimizer} works, so that
#' parameters close to 0 or very large, such as K tending to infinity, can
#' still be compared). This is used to stop strategy \code{'agree'} and,
#' for all strategies, to report which runs found the best maximum.
#' @param trparsopt Optional initial guess of the parameters to be optimized
#' (on the transformed scale), as a vector or as a matrix with one parameter
#' set per row. It is added to the Latin hypercube samples as a candidate
#' starting point: for strategy \code{'starts'} it is always used (first),
#' for the other strategies it is ranked by its likelihood together with the
#' samples.
#' @param optimmethod The optimization method used from each starting point;
#' any of the methods of \code{\link{optimizer}}.
#' @param optimpars Parameters of the optimization as in
#' \code{\link{optimizer}}. The default sets the verbose level of
#' \code{optimizer} (the fifth element) to 0, so that the trajectory of each
#' individual optimization is not shown.
#' @param lhs_verbose Verbose level of the multi-start procedure itself:
#' 0 = no output, >= 1 shows one line per optimization and a summary.
#' @param starts_file Optional name of a file to which the starting points
#' are saved, in the order in which they are optimized; see Details.
#' @param run_optimizations Whether to run the optimizations. With
#' \code{FALSE}, the function stops after choosing (and saving) the starting
#' points.
#' @param num_cores Number of R processes used for parallel computing. The
#' default, 1, means no parallel computing. Ignored when \code{cl} is given.
#' @param cl Optional cluster, created with \code{parallel::makeCluster} or
#' \code{parallel::makePSOCKcluster}, to use for parallel computing instead
#' of a cluster of \code{num_cores} processes created (and stopped) by this
#' function. Useful to reuse a cluster, to run on several machines, or to
#' export objects that the function to be optimized needs.
#' @param parallel_phase What to compute in parallel: 'both' (the default),
#' 'screening' (only the likelihood of the samples) or 'optimizations' (only
#' the optimizations).
#' @param packages Names of packages to attach on the workers, in addition to
#' DDD, for functions that call functions from these packages without
#' \code{::}.
#' @param ... Any other arguments of the function to be optimized, or
#' settings of the optimization routine, which are passed on to
#' \code{fun} and \code{optimizer}.
#' @return A list containing
#' \item{par}{The parameters (on the transformed scale) of the best
#' optimization result.}
#' \item{fvalues}{The best function value found.}
#' \item{conv}{The convergence code of the best optimization (0 means
#' converged).}
#' The first three elements are the same as the output of
#' \code{\link{optimizer}}, so \code{optimizer_lhs} can be used in its place.
#' In addition the list contains
#' \item{runs}{A data frame with one row per optimization, in the order in
#' which they were run, with the row of \code{samples} used as starting point
#' (\code{sample}), the value of \code{min_dist} in force when it was chosen
#' (\code{min_dist}), the function value at the start (\code{init_fvalue})
#' and at the end (\code{fvalue}), the convergence code (\code{conv},
#' \code{NA} if \code{optimizer} gave an error), whether the result agrees
#' with the best result within \code{tol_agree} (\code{agrees}), and the
#' starting (\code{*_init}) and optimized parameter values on the original
#' (untransformed) scale.}
#' \item{samples}{A data frame with all candidate starting points on the
#' original scale, their function values and their source (\code{'lhs'} for
#' Latin hypercube samples, \code{'initial'} for the initial guess).}
#' \item{num_agreeing}{The number of optimizations that agree with the best
#' result.}
#' \item{agreement_reached}{For strategy \code{'agree'}, whether
#' \code{num_agree} optimizations agree on the best result; \code{NA} for the
#' other strategies.}
#' \item{strategy}{The strategy used.}
#' With \code{run_optimizations = FALSE}, \code{par} and \code{fvalues} are
#' those of the first starting point, \code{conv} is -99 (which the maximum
#' likelihood functions recognize as 'no optimization was run'), \code{runs} is
#' \code{NULL} and the list contains a data frame \code{starts} with the
#' starting points.
#' @author Rampal S. Etienne
#' @seealso \code{\link{optimizer}}, \code{\link{lhs_sample}}
#' @keywords models
#' @examples
#' # A function with a local maximum at (0.25, 0.25) and the global maximum
#' # at (0.7, 0.6), both on the transformed scale
#' fun <- function(trparsopt) {
#'   log(0.5 * exp(-sum((trparsopt - c(0.25, 0.25))^2) / 0.02) +
#'       exp(-sum((trparsopt - c(0.7, 0.6))^2) / 0.01))
#' }
#' set.seed(1)
#' out <- optimizer_lhs(fun = fun,
#'                      lower = c(0, 0),
#'                      upper = c(Inf, Inf),
#'                      strategy = 'agree',
#'                      num_samples = 100,
#'                      num_agree = 3)
#' out$par
#' out$runs
#' @export optimizer_lhs
optimizer_lhs <- function(
    fun,
    lower,
    upper,
    strategy = c('starts', 'screen', 'agree'),
    num_starts = 10,
    num_samples = 100 * length(lower),
    num_best = 10,
    num_agree = 3,
    max_starts = 10 * num_agree,
    min_dist = 0.1,
    tol_agree = c(1E-3, 1E-3),
    sampling_scale = 'transformed',
    trparsopt = NULL,
    optimmethod = 'simplex',
    optimpars = c(1E-4, 1E-4, 1E-6, 1000, 0),
    num_cycles = 1,
    jitter = 0,
    lhs_verbose = 1,
    starts_file = NULL,
    run_optimizations = TRUE,
    num_cores = 1,
    cl = NULL,
    parallel_phase = c('both', 'screening', 'optimizations'),
    packages = NULL,
    ...)
{
  strategy <- match.arg(strategy)
  parallel_phase <- match.arg(parallel_phase)
  lhs_check_count(num_cores, 'num_cores')
  if(!is.null(cl) && !inherits(cl, 'cluster'))
  {
    stop('cl should be a cluster created with parallel::makeCluster or parallel::makePSOCKcluster.')
  }
  if(!is.null(packages) && !is.character(packages))
  {
    stop('packages should be a character vector of package names.')
  }
  if(!is.null(starts_file) && (!is.character(starts_file) || length(starts_file) != 1))
  {
    stop('starts_file should be the name of a single file.')
  }
  if(!is.logical(run_optimizations) || length(run_optimizations) != 1 ||
     is.na(run_optimizations))
  {
    stop('run_optimizations should be TRUE or FALSE.')
  }
  lhs_check_bounds(lower = lower, upper = upper)
  sampling_scale <- lhs_check_scale(sampling_scale = sampling_scale,
                                    lower = lower,
                                    upper = upper)
  lhs_check_count(num_starts, 'num_starts')
  lhs_check_count(num_samples, 'num_samples')
  lhs_check_count(num_best, 'num_best')
  lhs_check_count(num_agree, 'num_agree')
  if(!is.numeric(max_starts) || length(max_starts) != 1 || is.na(max_starts) ||
     max_starts < 1)
  {
    stop('max_starts should be a single number larger than or equal to 1.')
  }
  if(strategy == 'agree' && max_starts < num_agree)
  {
    stop('max_starts should be at least as large as num_agree.')
  }
  if(!is.numeric(min_dist) || length(min_dist) != 1 || is.na(min_dist) ||
     min_dist < 0)
  {
    stop('min_dist should be a single non-negative number.')
  }
  if(!is.numeric(tol_agree) || length(tol_agree) != 2 ||
     any(is.na(tol_agree)) || any(tol_agree < 0))
  {
    stop('tol_agree should be a vector of two non-negative tolerances.')
  }
  if(!is.character(optimmethod) || length(optimmethod) != 1)
  {
    stop('optimmethod should be the name of one of the methods of optimizer.')
  }
  numpar <- length(lower)
  parnames <- lhs_par_names(lower)
  if(!is.null(trparsopt))
  {
    if(!is.numeric(trparsopt) || length(trparsopt) %% numpar != 0)
    {
      stop('The number of elements of trparsopt should match the number of parameters in lower and upper.')
    }
    trparsopt <- matrix(as.numeric(trparsopt), ncol = numpar, byrow = !is.matrix(trparsopt))
  }

  # Evaluation of fun and optimization from a starting point are done by
  # lhs_eval_one and lhs_optimize_one, either in this R session or on the
  # workers of a cluster
  dots <- list(...)
  settings <- list(optimmethod = optimmethod,
                   optimpars = optimpars,
                   num_cycles = num_cycles,
                   jitter = jitter)
  first_error <- NULL
  evaluate_many <- function(rows)
  {
    trpars_list <- lapply(rows, function(k) as.numeric(samples[k, ]))
    if(par_screen)
    {
      res <- parallel::parLapply(cl, trpars_list, lhs_worker_eval)
    } else
    {
      res <- lapply(trpars_list, lhs_eval_one, fun = fun, dots = dots)
    }
    errors <- unlist(lapply(res, function(r) r$error))
    if(is.null(first_error) && length(errors) > 0) first_error <<- errors[1]
    return(vapply(res, function(r) r$value, numeric(1)))
  }
  optimize_many <- function(rows)
  {
    if(par_opt)
    {
      tasks <- lapply(rows, function(k) list(trpars = as.numeric(samples[k, ]),
                                             seed = task_seeds[k]))
      res <- parallel::clusterApplyLB(cl, tasks, lhs_worker_optimize,
                                      settings = settings)
    } else
    {
      res <- lapply(rows, function(k) lhs_optimize_one(as.numeric(samples[k, ]),
                                                       fun = fun, dots = dots,
                                                       settings = settings))
    }
    return(lapply(res, lhs_report_error, lhs_verbose = lhs_verbose,
                  numpar = numpar))
  }

  # Candidate starting points: the Latin hypercube sample, followed by the
  # initial guess(es), if any. unit holds their positions in the unit
  # hypercube (each parameter range scaled to [0, 1] on its sampling scale).
  num_lhs <- if(strategy == 'starts') num_starts else num_samples
  unit <- lhs_unit(n = num_lhs, numpar = numpar)
  samples <- lhs_unit_to_trpars(unit = unit,
                                lower = lower,
                                upper = upper,
                                sampling_scale = sampling_scale)
  cand_source <- rep('lhs', num_lhs)
  if(!is.null(trparsopt))
  {
    samples <- rbind(samples, trparsopt)
    unit <- rbind(unit, lhs_trpars_to_unit(trpars = trparsopt,
                                           lower = lower,
                                           upper = upper,
                                           sampling_scale = sampling_scale))
    cand_source <- c(cand_source, rep('initial', nrow(trparsopt)))
  }
  num_cand <- nrow(samples)

  # Parallel computing: on the workers of a cluster supplied as cl, or of a
  # cluster of num_cores R processes created here. The workers are separate R
  # sessions, so a likelihood that is itself parallelized can still be.
  own_cl <- FALSE
  if(is.null(cl) && num_cores > 1)
  {
    cl <- parallel::makePSOCKcluster(num_cores)
    own_cl <- TRUE
    on.exit(parallel::stopCluster(cl), add = TRUE)
  }
  par_screen <- !is.null(cl) && parallel_phase %in% c('both', 'screening')
  par_opt <- !is.null(cl) && parallel_phase %in% c('both', 'optimizations')
  if(par_screen || par_opt)
  {
    parallel::clusterCall(cl, lhs_worker_init, likfun = fun, dots = dots,
                          packages = unique(c('DDD', packages)))
    if(lhs_verbose >= 1)
    {
      cat(sprintf('Using %d parallel workers for %s.\n', length(cl),
                  switch(parallel_phase,
                         both = 'the screening and the optimizations',
                         screening = 'the screening',
                         optimizations = 'the optimizations')))
    }
  }

  if(lhs_verbose >= 1)
  {
    cat(sprintf('Computing the likelihood for %d Latin hypercube samples%s.\n',
                num_lhs,
                ifelse(is.null(trparsopt), '', ' and the initial guess')))
    utils::flush.console()
  }
  init_fvalues <- evaluate_many(seq_len(num_cand))
  # With parallel optimizations, each starting point gets its own random
  # number seed, drawn from the random number generator of this R session, so
  # that optimization methods that use random numbers give the same result
  # whichever worker runs them, and in whatever order
  task_seeds <- NULL
  if(par_opt) task_seeds <- sample.int(.Machine$integer.max, num_cand)
  samples_untr <- untransform_pars(samples)
  colnames(samples_untr) <- parnames
  samples_df <- data.frame(samples_untr,
                           fvalue = init_fvalues,
                           source = cand_source,
                           check.names = FALSE,
                           stringsAsFactors = FALSE)
  rownames(samples_df) <- NULL
  num_finite <- sum(is.finite(init_fvalues))
  if(num_finite == 0)
  {
    msg <- 'None of the candidate starting points has a finite likelihood. Please check fun and the parameter ranges.'
    if(!is.null(first_error))
    {
      msg <- paste0(msg, ' The first error returned by fun was: ', first_error)
    }
    stop(msg)
  }
  if(num_finite < num_cand && lhs_verbose >= 1)
  {
    cat(sprintf('%d of the %d candidate starting points have a likelihood of 0 (or a numerical problem) and are not used.\n',
                num_cand - num_finite, num_cand))
  }

  # Order in which candidates are considered, and maximum number of runs
  finite <- which(is.finite(init_fvalues))
  if(strategy == 'starts')
  {
    cand_order <- c(finite[cand_source[finite] == 'initial'],
                    finite[cand_source[finite] == 'lhs'])
    max_runs <- length(cand_order)
    cur_dist <- 0
  } else
  {
    cand_order <- finite[order(init_fvalues[finite], decreasing = TRUE)]
    cur_dist <- min_dist
    if(strategy == 'screen')
    {
      max_runs <- min(num_best, length(cand_order))
      if(max_runs < num_best && lhs_verbose >= 1)
      {
        cat(sprintf('Only %d candidates have a finite likelihood, so only %d optimizations are run.\n',
                    max_runs, max_runs))
      }
    } else
    {
      max_runs <- min(max_starts, length(cand_order))
      if(max_runs < num_agree)
      {
        warning(sprintf('Only %d candidates have a finite likelihood, which is fewer than num_agree = %d.',
                        max_runs, num_agree))
      }
    }
  }

  # Next starting point: the first candidate in cand_order that has not been
  # used and is at least cur_dist away from all used starting points;
  # cur_dist is halved when there is no such candidate
  used <- integer(0)
  pick_verbose <- TRUE
  pick_next <- function()
  {
    remaining <- cand_order[!(cand_order %in% used)]
    if(length(remaining) == 0) return(NA)
    if(cur_dist <= 0 || length(used) == 0) return(remaining[1])
    dmin <- lhs_min_distance(unit[remaining, , drop = FALSE],
                             unit[used, , drop = FALSE])
    while(cur_dist > 0 && !any(dmin >= cur_dist))
    {
      new_dist <- cur_dist / 2
      if(new_dist < 1E-6) new_dist <- 0
      if(lhs_verbose >= 1 && pick_verbose)
      {
        cat(sprintf('No candidates left at a distance of at least %g from the starting points used so far; min_dist is reduced to %g.\n',
                    cur_dist, new_dist))
      }
      cur_dist <<- new_dist
    }
    return(remaining[which(dmin >= cur_dist)[1]])
  }

  # The starting points in the order in which they are optimized: these can be
  # saved to a file, e.g. to run the optimizations as separate jobs on a
  # computer cluster. The order only depends on the positions and likelihoods
  # of the samples, not on the results of the optimizations.
  if(!is.null(starts_file) || !run_optimizations)
  {
    pick_verbose <- FALSE
    plan_k <- integer(0)
    plan_dist <- numeric(0)
    while(length(plan_k) < max_runs)
    {
      k <- pick_next()
      if(is.na(k)) break
      used <- c(used, k)
      plan_k <- c(plan_k, k)
      plan_dist <- c(plan_dist, if(strategy != 'starts') cur_dist else NA)
    }
    used <- integer(0)
    cur_dist <- if(strategy == 'starts') 0 else min_dist
    pick_verbose <- TRUE
    starts_pars <- untransform_pars(samples[plan_k, , drop = FALSE])
    colnames(starts_pars) <- parnames
    starts <- data.frame(sample = plan_k,
                         source = cand_source[plan_k],
                         min_dist = plan_dist,
                         init_fvalue = init_fvalues[plan_k],
                         as.data.frame(starts_pars),
                         check.names = FALSE)
    rownames(starts) <- NULL
    if(!is.null(starts_file))
    {
      starts_trpars <- samples[plan_k, , drop = FALSE]
      colnames(starts_trpars) <- parnames
      saveRDS(list(pars = starts_pars,
                   trpars = starts_trpars,
                   starts = starts,
                   samples = samples_df,
                   settings = list(lower = lower,
                                   upper = upper,
                                   sampling_scale = sampling_scale,
                                   strategy = strategy,
                                   min_dist = min_dist)),
              file = starts_file)
      if(lhs_verbose >= 1)
      {
        cat(sprintf('The %d starting points were saved to %s.\n', length(plan_k),
                    starts_file))
      }
    }
    if(!run_optimizations)
    {
      if(lhs_verbose >= 1)
      {
        cat('No optimizations were run (run_optimizations = FALSE).\n')
      }
      out_par <- as.numeric(samples[plan_k[1], ])
      names(out_par) <- names(lower)
      return(invisible(list(par = out_par,
                            fvalues = init_fvalues[plan_k[1]],
                            conv = -99,
                            runs = NULL,
                            starts = starts,
                            samples = samples_df,
                            num_agreeing = 0,
                            agreement_reached = NA,
                            strategy = strategy)))
    }
  }

  # Storage of the results, in the order in which the optimizations finish
  opt_pars <- matrix(NA_real_, nrow = max_runs, ncol = numpar)
  opt_fvalues <- rep(NA_real_, max_runs)
  opt_conv <- rep(NA_real_, max_runs)
  run_dist <- rep(NA_real_, max_runs)
  run_sample <- rep(NA_integer_, max_runs)
  num_runs <- 0
  best <- NA
  agrees <- logical(0)
  record_run <- function(k, dist, res)
  {
    num_runs <<- num_runs + 1
    run_sample[num_runs] <<- k
    run_dist[num_runs] <<- dist
    opt_pars[num_runs, ] <<- res$par
    opt_fvalues[num_runs] <<- res$fvalue
    opt_conv[num_runs] <<- res$conv
    if(lhs_verbose >= 1)
    {
      cat(sprintf('Optimization %d (%s %d): initial value %s, optimized value %s, convergence code %s.\n',
                  num_runs,
                  ifelse(cand_source[k] == 'lhs', 'sample', 'initial guess, row'),
                  ifelse(cand_source[k] == 'lhs', k, k - num_lhs),
                  format(init_fvalues[k], digits = 8),
                  format(res$fvalue, digits = 8),
                  format(res$conv)))
      utils::flush.console()
    }
  }
  # Updates the best result and the agreement with it; returns TRUE when
  # strategy 'agree' has reached agreement
  update_agreement <- function()
  {
    best <<- lhs_best_run(opt_fvalues[1:num_runs],
                          opt_pars[1:num_runs, , drop = FALSE],
                          opt_conv[1:num_runs])
    agrees <<- lhs_agreement(best,
                             opt_fvalues[1:num_runs],
                             opt_pars[1:num_runs, , drop = FALSE],
                             opt_conv[1:num_runs],
                             tol_agree)
    if(strategy == 'agree' && num_runs >= num_agree)
    {
      if(lhs_verbose >= 1)
      {
        cat(sprintf('%d of the %d optimizations agree on the best value found so far.\n',
                    sum(agrees), num_runs))
      }
      return(sum(agrees) >= num_agree)
    }
    return(FALSE)
  }

  use_future <- par_opt && strategy == 'agree' &&
    requireNamespace('future', quietly = TRUE)
  if(par_opt && strategy == 'agree' && !use_future && lhs_verbose >= 1)
  {
    cat("The optimizations are run in batches; install the package future to run them asynchronously.\n")
  }

  if(use_future)
  {
    # Strategy 'agree' with parallel computing: a new optimization is started
    # as soon as a worker is free, and agreement is checked after each
    # finished optimization (futures on the workers of the cluster)
    oplan <- future::plan(future::cluster, workers = cl)
    on.exit(future::plan(oplan), add = TRUE, after = FALSE)
    running <- list()
    num_submitted <- 0
    submit_next <- function()
    {
      if(num_submitted >= max_runs) return(FALSE)
      k <- pick_next()
      if(is.na(k)) return(FALSE)
      used <<- c(used, k)
      num_submitted <<- num_submitted + 1
      task <- list(trpars = as.numeric(samples[k, ]), seed = task_seeds[k])
      f <- future::future(lhs_worker_optimize(task, settings),
                          globals = list(lhs_worker_optimize = lhs_worker_optimize,
                                         task = task,
                                         settings = settings),
                          packages = 'DDD',
                          seed = TRUE,
                          lazy = FALSE)
      running[[length(running) + 1]] <<- list(f = f, k = k, dist = cur_dist)
      return(TRUE)
    }
    collect <- function(r)
    {
      res <- tryCatch(future::value(r$f),
                      error = function(e) list(out = NULL, error = conditionMessage(e)))
      record_run(r$k, r$dist, lhs_report_error(res, lhs_verbose = lhs_verbose,
                                               numpar = numpar))
    }
    while(length(running) < length(cl) && submit_next()) {}
    agreed <- FALSE
    while(length(running) > 0 && !agreed)
    {
      done <- which(vapply(running, function(r) future::resolved(r$f), logical(1)))
      if(length(done) == 0)
      {
        Sys.sleep(0.05)
        next
      }
      for(d in done) collect(running[[d]])
      running <- running[-done]
      agreed <- update_agreement()
      if(!agreed)
      {
        while(length(running) < length(cl) && submit_next()) {}
      }
    }
    if(length(running) > 0)
    {
      if(own_cl)
      {
        # the cluster is stopped on exit, which ends these optimizations
        if(lhs_verbose >= 1)
        {
          cat(sprintf('%d optimizations that were still running are not used.\n',
                      length(running)))
        }
      } else
      {
        # a cluster supplied by the user must be free again when this
        # function returns, so the running optimizations are finished
        for(r in running) collect(r)
        update_agreement()
      }
    }
  } else
  {
    # Without parallel computing the optimizations are run one by one. With
    # parallel computing, strategies 'starts' and 'screen' run all
    # optimizations at once, divided over the workers; strategy 'agree' runs
    # them in batches of as many as there are workers when the package future
    # is not available.
    batch_size <- 1
    if(par_opt)
    {
      batch_size <- if(strategy == 'agree') length(cl) else max_runs
    }
    while(num_runs < max_runs)
    {
      batch <- integer(0)
      batch_dist <- numeric(0)
      while(length(batch) < min(batch_size, max_runs - num_runs))
      {
        k <- pick_next()
        if(is.na(k)) break
        used <- c(used, k)
        batch <- c(batch, k)
        batch_dist <- c(batch_dist, if(strategy != 'starts') cur_dist else NA)
      }
      if(length(batch) == 0) break
      results <- optimize_many(batch)
      for(b in seq_along(batch)) record_run(batch[b], batch_dist[b], results[[b]])
      if(update_agreement()) break
    }
  }

  opt_pars <- opt_pars[seq_len(num_runs), , drop = FALSE]
  opt_fvalues <- opt_fvalues[seq_len(num_runs)]
  opt_conv <- opt_conv[seq_len(num_runs)]
  run_dist <- run_dist[seq_len(num_runs)]
  num_agreeing <- sum(agrees)
  agreement_reached <- NA
  if(strategy == 'agree')
  {
    agreement_reached <- num_agreeing >= num_agree
    if(!agreement_reached)
    {
      warning(sprintf('Only %d of the %d optimizations agree on the best value; %d were required. Consider increasing max_starts or num_samples, or relaxing tol_agree.',
                      num_agreeing, num_runs, num_agree))
    }
  }
  if(is.na(best))
  {
    warning('None of the optimizations returned a finite result.')
    out_par <- rep(NA_real_, numpar)
    out_fvalue <- NA_real_
    out_conv <- NA_real_
  } else
  {
    out_par <- opt_pars[best, ]
    out_fvalue <- opt_fvalues[best]
    out_conv <- opt_conv[best]
    if(is.na(out_conv) || out_conv != 0)
    {
      warning('None of the optimizations converged; the best unconverged result is returned.')
    }
  }
  names(out_par) <- names(lower)

  run_sample <- run_sample[seq_len(num_runs)]
  runs <- data.frame(sample = run_sample,
                     min_dist = run_dist,
                     init_fvalue = init_fvalues[run_sample],
                     fvalue = opt_fvalues,
                     conv = opt_conv,
                     agrees = agrees)
  init_untr <- untransform_pars(samples[run_sample, , drop = FALSE])
  colnames(init_untr) <- paste0(parnames, '_init')
  opt_untr <- untransform_pars(opt_pars)
  colnames(opt_untr) <- parnames
  runs <- cbind(runs, as.data.frame(init_untr), as.data.frame(opt_untr))
  rownames(runs) <- NULL

  if(lhs_verbose >= 1 && !is.na(best))
  {
    cat(sprintf('The best value is %s; %d of the %d optimizations found it.\n',
                format(out_fvalue, digits = 8), num_agreeing, num_runs))
    cat('The corresponding parameters are: ')
    cat(untransform_pars(out_par))
    cat('\n')
  }
  out <- list(par = out_par,
              fvalues = out_fvalue,
              conv = out_conv,
              runs = runs,
              samples = samples_df,
              num_agreeing = num_agreeing,
              agreement_reached = agreement_reached,
              strategy = strategy)
  return(invisible(out))
}

# Functions for evaluating fun and optimizing from one starting point; they
# return the result and an error message (NULL when there was no error)
lhs_eval_one <- function(trpars, fun, dots)
{
  error <- NULL
  val <- tryCatch(suppressWarnings(do.call(fun, c(list(trparsopt = trpars), dots))),
                  error = function(e)
                  {
                    error <<- conditionMessage(e)
                    return(-Inf)
                  })
  val <- suppressWarnings(as.numeric(unlist(val)))
  # anything that is not a finite number or -Inf is an unusable starting point
  if(length(val) != 1 || is.na(val) || val == Inf) val <- -Inf
  return(list(value = val, error = error))
}

lhs_optimize_one <- function(trpars, fun, dots, settings, seed = NULL)
{
  # on the workers of a cluster, each optimization gets its own seed
  if(!is.null(seed)) set.seed(seed, kind = "L'Ecuyer-CMRG")
  error <- NULL
  out <- tryCatch(do.call(optimizer,
                          c(list(optimmethod = settings$optimmethod,
                                 optimpars = settings$optimpars,
                                 num_cycles = settings$num_cycles,
                                 fun = fun,
                                 trparsopt = trpars,
                                 jitter = settings$jitter),
                            dots)),
                  error = function(e)
                  {
                    error <<- conditionMessage(e)
                    return(NULL)
                  })
  return(list(out = out, error = error))
}

lhs_clean_result <- function(res, numpar)
{
  par <- as.numeric(unlist(res$out$par))
  fvalue <- as.numeric(unlist(res$out$fvalues))
  conv <- as.numeric(unlist(res$out$conv))
  if(length(par) != numpar) par <- rep(NA_real_, numpar)
  if(length(fvalue) != 1) fvalue <- NA_real_
  if(length(conv) != 1) conv <- NA_real_
  return(list(par = par, fvalue = fvalue, conv = conv))
}

# Storage on the workers of a cluster for the function to be optimized and its
# other arguments, which are sent once, by lhs_worker_init
lhs_worker_env <- new.env(parent = emptyenv())

lhs_worker_init <- function(likfun, dots, packages)
{
  for(pkg in packages)
  {
    loadNamespace(pkg)
    if(!(paste0('package:', pkg) %in% search())) attachNamespace(pkg)
  }
  lhs_worker_env$fun <- likfun
  lhs_worker_env$dots <- dots
  return(invisible(NULL))
}

lhs_worker_eval <- function(trpars)
{
  return(lhs_eval_one(trpars, fun = lhs_worker_env$fun, dots = lhs_worker_env$dots))
}

lhs_worker_optimize <- function(task, settings)
{
  return(lhs_optimize_one(task$trpars, fun = lhs_worker_env$fun,
                          dots = lhs_worker_env$dots, settings = settings,
                          seed = task$seed))
}

lhs_report_error <- function(res, lhs_verbose, numpar)
{
  if(!is.null(res$error) && lhs_verbose >= 1)
  {
    cat('optimizer gave an error:', res$error, '\n')
  }
  return(lhs_clean_result(res, numpar = numpar))
}

# Called by optimizer() when optimmethod is a list with settings for
# optimizer_lhs. The elements of the list override the settings passed on by
# optimizer (e.g. optimpars); an element trparsopt = NULL leaves the initial
# guess out of the candidate starting points.
optimizer_lhs_dispatch <- function(settings,
                                   fun,
                                   trparsopt,
                                   optimpars,
                                   num_cycles,
                                   jitter,
                                   ...)
{
  setnames <- names(settings)
  if(is.null(setnames) || any(is.na(setnames)) || any(setnames == ''))
  {
    stop('When optimmethod is a list, all its elements should be named after arguments of optimizer_lhs.')
  }
  if(!all(c('lower', 'upper') %in% setnames))
  {
    stop("When optimmethod is a list, it should at least contain the ranges of the parameters as elements 'lower' and 'upper'.")
  }
  if('fun' %in% setnames)
  {
    stop("The list given as optimmethod should not contain 'fun'.")
  }
  if(!('optimmethod' %in% setnames)) settings$optimmethod <- 'simplex'
  if(!is.character(settings[['optimmethod']]) ||
     length(settings[['optimmethod']]) != 1)
  {
    stop("The element 'optimmethod' of the list given as optimmethod should be the name of one of the methods of optimizer, e.g. 'simplex'.")
  }
  # The ranges may be given for the optimized parameters only, or for all
  # parameters of the model; in the latter case the optimized ones are
  # selected with idparsopt, which all likelihood functions in DDD take
  numpar <- length(trparsopt)
  lower <- settings[['lower']]
  upper <- settings[['upper']]
  if(length(lower) != numpar || length(upper) != numpar)
  {
    idparsopt <- list(...)[['idparsopt', exact = TRUE]]
    if(!is.null(idparsopt) && length(idparsopt) == numpar &&
       length(lower) == length(upper) && length(lower) > numpar &&
       max(idparsopt) <= length(lower))
    {
      scale <- settings[['sampling_scale']]
      if(length(scale) == length(lower))
      {
        settings$sampling_scale <- scale[idparsopt]
      }
      settings$lower <- lower[idparsopt]
      settings$upper <- upper[idparsopt]
    } else
    {
      stop('The ranges lower and upper should be given either for the parameters that are optimized, or for all parameters of the model.')
    }
  }
  base <- list(fun = fun,
               trparsopt = trparsopt,
               optimpars = optimpars,
               num_cycles = num_cycles,
               jitter = jitter)
  args <- utils::modifyList(base, settings)
  return(do.call(optimizer_lhs, c(args, list(...))))
}

# Unit Latin hypercube: one point in each of the n strata of (0, 1), in
# random order, for each parameter
lhs_unit <- function(n, numpar)
{
  unit <- matrix(0, nrow = n, ncol = numpar)
  for(j in seq_len(numpar))
  {
    unit[, j] <- (sample.int(n) - stats::runif(n)) / n
  }
  return(unit)
}

# From positions in the unit hypercube to transformed parameters
lhs_unit_to_trpars <- function(unit, lower, upper, sampling_scale)
{
  trpars <- matrix(0, nrow = nrow(unit), ncol = ncol(unit))
  for(j in seq_len(ncol(unit)))
  {
    u <- unit[, j]
    if(sampling_scale[j] == 'transformed')
    {
      trlower <- transform_pars(lower[j])
      trupper <- transform_pars(upper[j])
      trpars[, j] <- trlower + u * (trupper - trlower)
    } else if(sampling_scale[j] == 'original')
    {
      trpars[, j] <- transform_pars(lower[j] + u * (upper[j] - lower[j]))
    } else
    {
      trpars[, j] <- transform_pars(exp(log(lower[j]) +
                                          u * (log(upper[j]) - log(lower[j]))))
    }
  }
  return(trpars)
}

# From transformed parameters to positions in the unit hypercube (outside
# [0, 1] for parameters outside their range; 0 for parameters whose range
# has zero width)
lhs_trpars_to_unit <- function(trpars, lower, upper, sampling_scale)
{
  unit <- matrix(0, nrow = nrow(trpars), ncol = ncol(trpars))
  for(j in seq_len(ncol(trpars)))
  {
    if(sampling_scale[j] == 'transformed')
    {
      a <- transform_pars(lower[j])
      b <- transform_pars(upper[j])
      x <- trpars[, j]
    } else if(sampling_scale[j] == 'original')
    {
      a <- lower[j]
      b <- upper[j]
      x <- untransform_pars(trpars[, j])
    } else
    {
      a <- log(lower[j])
      b <- log(upper[j])
      x <- suppressWarnings(log(untransform_pars(trpars[, j])))
    }
    if(b > a) unit[, j] <- (x - a) / (b - a)
  }
  return(unit)
}

# Smallest distance (maximum over parameters of the absolute difference in
# the unit hypercube) between each candidate and the used starting points
lhs_min_distance <- function(cand_unit, used_unit)
{
  dmin <- rep(Inf, nrow(cand_unit))
  for(k in seq_len(nrow(used_unit)))
  {
    diffs <- abs(sweep(cand_unit, 2, used_unit[k, ]))
    dk <- apply(diffs, 1, function(x) if(all(is.na(x))) Inf else max(x, na.rm = TRUE))
    dmin <- pmin(dmin, dk)
  }
  return(dmin)
}

# Index of the best optimization: the largest finite value among the
# converged runs or, if no run converged, among all runs with a finite value
lhs_best_run <- function(fvalues, pars, conv)
{
  finite <- is.finite(fvalues) & apply(is.finite(pars), 1, all)
  valid <- finite & !is.na(conv) & conv == 0
  if(!any(valid)) valid <- finite
  if(!any(valid)) return(NA)
  candidates <- which(valid)
  return(candidates[which.max(fvalues[candidates])])
}

# Which optimizations converged to the same maximum as the best one, within
# the tolerances
lhs_agreement <- function(best, fvalues, pars, conv, tol_agree)
{
  num_runs <- length(fvalues)
  if(is.na(best)) return(rep(FALSE, num_runs))
  agrees <- rep(FALSE, num_runs)
  best_converged <- !is.na(conv[best]) && conv[best] == 0
  for(i in seq_len(num_runs))
  {
    if(!is.finite(fvalues[i]) || any(!is.finite(pars[i, ]))) next
    # if the best run converged, only converged runs can agree with it
    if(best_converged && (is.na(conv[i]) || conv[i] != 0)) next
    agrees[i] <- abs(fvalues[i] - fvalues[best]) <= tol_agree[1] &&
      max(abs(pars[i, ] - pars[best, ])) <= tol_agree[2]
  }
  return(agrees)
}

lhs_par_names <- function(lower)
{
  parnames <- names(lower)
  if(is.null(parnames)) parnames <- rep('', length(lower))
  unnamed <- is.na(parnames) | parnames == ''
  parnames[unnamed] <- paste0('par', seq_along(lower))[unnamed]
  return(parnames)
}

lhs_check_bounds <- function(lower, upper)
{
  if(!is.numeric(lower) || !is.numeric(upper) || length(lower) == 0)
  {
    stop('lower and upper should be numeric vectors.')
  }
  if(length(lower) != length(upper))
  {
    stop('lower and upper should have the same length.')
  }
  if(any(is.na(lower)) || any(is.na(upper)))
  {
    stop('lower and upper should not contain NA.')
  }
  if(any(lower > upper))
  {
    stop('All elements of lower should be smaller than or equal to the corresponding elements of upper.')
  }
  invisible(TRUE)
}

lhs_check_scale <- function(sampling_scale, lower, upper)
{
  numpar <- length(lower)
  if(!is.character(sampling_scale) || !(length(sampling_scale) %in% c(1, numpar)))
  {
    stop('sampling_scale should be a single value or have one value per parameter.')
  }
  if(!all(sampling_scale %in% c('transformed', 'original', 'log')))
  {
    stop("sampling_scale should be 'transformed', 'original' or 'log'.")
  }
  sampling_scale <- rep(sampling_scale, length.out = numpar)
  original <- sampling_scale == 'original'
  if(any(!is.finite(c(lower[original], upper[original]))))
  {
    stop("Parameters sampled on the 'original' scale need finite bounds.")
  }
  logscale <- sampling_scale == 'log'
  if(any(!is.finite(c(lower[logscale], upper[logscale]))) ||
     any(lower[logscale] <= 0))
  {
    stop("Parameters sampled on the 'log' scale need positive, finite bounds.")
  }
  return(sampling_scale)
}

lhs_check_count <- function(x, name)
{
  if(!is.numeric(x) || length(x) != 1 || is.na(x) || x < 1 || x != round(x))
  {
    stop(paste0(name, ' should be a single positive integer.'))
  }
  invisible(TRUE)
}

Try the DDD package in your browser

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

DDD documentation built on Dec. 6, 2026, 1:08 a.m.