########################### GATEWAY HEADER ############################# # # _| _| _|_|_| _|_|_| _|_| _|_|_| _|_| # _|_| _|_| _| _| _| _| _| _| _| _| # _| _| _| _| _| _| _|_|_|_| _| _| _| # _| _| _| _| _| _| _| _| _| _| # _| _| _|_|_| _|_|_| _| _| _|_|_| _|_| # # Version 7 # ######################################################################## # # See the MIDACO user manual for detailed information # ######################################################################## # # USAGE # # source("midaco.R") # solution <- midaco(problem, option, key) # # problem list with the problem function and the problem definition # # problem$fn problem function, called as fn(x) and # returning list(f = f, g = g) # problem$o, $n, $ni, $m, $me problem dimensions # problem$xl, $xu, $x bounds and starting point # # option list with the MIDACO options # # option$maxeval, $maxtime stopping criteria # option$printeval, $save2file printing options # option$resumable optional, default 0 # option$param MIDACO parameters (below) # option$parallel optional, default 0 # # key the MIDACO license key (character string) # # solution list with the result # # solution$f, $g, $x best solution # solution$iflag MIDACO information flag # solution$eval, $time evaluations and seconds # solution$psize, $paretofront pareto front (o > 1) # # option$param is a numeric vector with up to 15 entries. Missing # entries are zero (= default). The entries may be named: # # ACCURACY SEED FSTOP ALGOSTOP EVALSTOP FOCUS ANTS KERNEL ORACLE # PARETOMAX EPSILON BALANCE CHARACTER SURROGATE PMISQP # # PARALLELIZATION: with option$parallel = P > 1 the P points of a # cycle are evaluated on P R processes of a 'parallel' cluster (base # R, no extra package). The cluster starts empty: midaco() gives it # the objects of the global environment and loads the packages that # are attached, so a problem function written as in the example # works there unchanged. # ######################################################################## # # The MIDACO library (midacor.so, on Windows midacor.dll) is looked # for in the folder of midaco.R and in the working directory. # ######################################################################## # Folders of the MIDACO library: the folder of this file (as given to # source()) and the working directory .midaco_dir <- local({ path <- NULL for (i in rev(seq_len(sys.nframe()))) { path <- sys.frame(i)$ofile if (!is.null(path)) break } dir <- NULL if (is.character(path) && length(path) == 1) dir <- dirname(normalizePath(path, mustWork = FALSE)) unique(c(dir, getwd())) }) ######################################################################## ######################################################################## ######################################################################## midaco <- function(problem, option, key) { ###################################################################### # Problem definition ###################################################################### fn <- problem$fn if (!is.function(fn)) stop("MIDACO: problem$fn must be the problem function, fn(x)") o <- .midaco_count(problem$o, "problem$o", 1) n <- .midaco_count(problem$n, "problem$n", 1) ni <- .midaco_count(problem$ni, "problem$ni", 0) m <- .midaco_count(problem$m, "problem$m", 0) me <- .midaco_count(problem$me, "problem$me", 0) xl <- .midaco_vector(problem$xl, n, "problem$xl") xu <- .midaco_vector(problem$xu, n, "problem$xu") x <- .midaco_vector(problem$x, n, "problem$x") # Re-scale Infinity values: MIDACO needs finite bounds if (any(is.infinite(c(xl, xu, x)))) { xl[is.infinite(xl)] <- -1.0e+6 xu[is.infinite(xu)] <- 1.0e+6 x[is.infinite(x)] <- xl[is.infinite(x)] cat("\n NOTE: Infinity Values have been rescaled to 1.0E+6 \n") } ###################################################################### # Options ###################################################################### maxeval <- option$maxeval maxtime <- option$maxtime printeval <- option$printeval save2file <- option$save2file resumable <- if (is.null(option$resumable)) 0 else option$resumable param <- .midaco_param(option$param) P <- if (is.null(option$parallel)) 1 else round(option$parallel) if (P < 1) P <- 1 ###################################################################### # The P points of a cycle: point c in column c ###################################################################### xxx <- matrix(x, nrow = n, ncol = P) fff <- matrix(0, nrow = o, ncol = P) ggg <- matrix(0, nrow = m, ncol = P) ###################################################################### # Parallel cluster (P > 1) ###################################################################### cl <- NULL if (P > 1) { cl <- parallel::makeCluster(P) on.exit(parallel::stopCluster(cl), add = TRUE) parallel::clusterExport(cl, ls(globalenv(), all.names = TRUE), envir = globalenv()) parallel::clusterCall(cl, function(pkgs) { for (p in rev(pkgs)) suppressPackageStartupMessages(library(p, character.only = TRUE)) NULL }, .packages()) } ###################################################################### # Start MIDACO: workspace and head print. A resumed run # (resumable = 1) comes back with the points it was paused at. ###################################################################### .midaco_load() run <- .Call("midacor_start", as.double(c(P, o, n, ni, m, me)), xl, xu, param, as.character(key), as.double(c(printeval, save2file, resumable, maxeval, maxtime)), as.double(xxx), PACKAGE = "midacor") xxx[] <- run$x istop <- run$istop iflag <- run$iflag # F and G of the result. If MIDACO stops already at the start (IFLAG 9, # e.g. a broken midaco.workspace) the loop below never runs. f <- numeric(o) g <- numeric(m) while (istop == 0) # Call MIDACO by Reverse Communication Loop { # Evaluate Objective Functions F(X) and Constraints G(X) if (P == 1) { result <- list(fn(xxx[, 1])) } else { result <- parallel::parLapply(cl, split(xxx, col(xxx)), fn) } for (c in seq_len(P)) { fff[, c] <- .midaco_result(result[[c]][[1]], o, "f") if (m > 0) ggg[, c] <- .midaco_result(result[[c]][[2]], m, "g") } # Check and repair NaN and Inf values fff[is.na(fff)] <- 1.0e+33 ggg[is.na(ggg)] <- -1.0e+33 fff[is.infinite(fff)] <- 1.0e+32 ggg[is.infinite(ggg)] <- -1.0e+32 # Call MIDACO (and the MIDACO printer) res <- .Call("midacor_cycle", run$ws, as.double(xxx), as.double(fff), as.double(ggg), PACKAGE = "midacor") xxx[] <- res$x iflag <- res$iflag istop <- res$istop f <- res$f g <- res$g } fin <- .Call("midacor_finish", run$ws, PACKAGE = "midacor") ###################################################################### # Solution ###################################################################### list(f = f, g = g, x = xxx[, 1], iflag = iflag, eval = fin$eval, time = fin$time, psize = fin$pf[1], # Number of pareto points paretofront = fin$pf) } ######################################################################## ############################### HELPERS ################################ ######################################################################## # Load the MIDACO library midacor .midaco_load <- function() { if (!is.null(getLoadedDLLs()[["midacor"]])) return(invisible()) dirs <- unique(c(.midaco_dir, getwd())) exts <- unique(c(.Platform$dynlib.ext, ".so", ".dll")) libs <- file.path(rep(dirs, each = length(exts)), paste0("midacor", exts)) lib <- libs[file.exists(libs)][1] if (is.na(lib)) stop("MIDACO: the MIDACO library midacor", .Platform$dynlib.ext, " was not found. Put it into the folder of midaco.R.", " Folders searched:\n ", paste(dirs, collapse = "\n "), call. = FALSE) err <- tryCatch({ dyn.load(lib); NULL }, error = function(e) conditionMessage(e)) if (!is.null(err)) stop("MIDACO: the MIDACO library could not be loaded: ", lib, "\n ", err, call. = FALSE) invisible() } .midaco_count <- function(v, name, lo) { if (!is.numeric(v) || length(v) != 1 || is.na(v) || v != round(v) || v < lo) stop(sprintf("MIDACO: %s must be an integer >= %d", name, lo)) as.integer(v) } .midaco_vector <- function(v, n, name) { if (!is.numeric(v) || length(v) != n) stop(sprintf("MIDACO: %s must be a numeric vector of length n = %d", name, n)) as.double(v) } .midaco_param_names <- c("ACCURACY", "SEED", "FSTOP", "ALGOSTOP", "EVALSTOP", "FOCUS", "ANTS", "KERNEL", "ORACLE", "PARETOMAX", "EPSILON", "BALANCE", "CHARACTER", "SURROGATE", "PMISQP") # option$param: up to 15 numbers, positional or named, missing = 0 .midaco_param <- function(v) { param <- numeric(15) if (is.null(v)) return(param) if (!is.numeric(v) || length(v) > 15) stop("MIDACO: option$param must be a numeric vector of up to 15 entries") if (is.null(names(v)) || all(names(v) == "")) { param[seq_along(v)] <- v } else { k <- match(toupper(gsub("[-.]", "_", names(v))), .midaco_param_names) if (any(is.na(k))) stop("MIDACO: unknown option$param name(s): ", paste(names(v)[is.na(k)], collapse = ", ")) param[k] <- v } as.double(param) } # f or g as returned by the problem function -> k numbers .midaco_result <- function(v, k, name) { if (!is.numeric(v) || length(v) != k) stop(sprintf("MIDACO: the problem function returned %d value(s) for %s, but %s", length(v), name, if (name == "f") sprintf("o = %d", k) else sprintf("m = %d", k))) v } ######################################################################## ############################ END OF FILE ############################### ########################################################################