I've an R
code with two nested optimisations. There's an outer and an inner function. The outer function passed certain parameters along to the inner function, which performs an optimisation on another set of parameters. These parameters are then sent to the outer function which optimizes an objective function based on the parameters estimated in the inner function. The estimates on the outer function are then passed to the inner function, which finds the new optimal set of parameters in the inner function, and passes them to the outer function. These loops repeat until the objective function in the outer loop is minimised.
The code works by setting the inner parameters as global variables, so that after the maximisation in the outer loop, the code passes these global variables to the inner loop.
I would like to run this procedure for different datasets in parallel. I understand that I cannot use the global variables in parallel, and I was thinking of saving text files with different file names at each loop: I would save a file with the value of the parameters at the end of the outer loop and reopen it at the beginning of the outer loop. However, is there a more efficient way to do this? I don't think that using a list
would work. Thank you.
Example:
require(nloptr)
y = rnorm(100)
x = runif(100)*5
inner <- function(beta) mean((y-beta*x)^2)
outer <- function(alpha) {
if (!exists("storage") | is.null(storage$solution))
beta <- runif(1)
else
beta <- storage$solution
sol.inner <-nloptr(
x0 = beta,
eval_f = inner,
opts = list(
algorithm = "NLOPT_LN_BOBYQA",
ftol_rel = 1.e-6,
ftol_abs = 1.e-7,
xtol_rel = 1.e-6,
xtol_abs = 0,
maxeval = 1000000
)
)
storage <- c()
storage <<- append(storage,sol.inner)
beta <- sol.inner$solution
mean(x^2 - alpha* x + beta)^2
}
alpha0 <- runif(1)
storage <- c()
sol.outer <- nloptr(
x0 = alpha0,
eval_f = outer,
opts = list(
algorithm ="NLOPT_LN_BOBYQA",
ftol_rel = 1.e-6,
ftol_abs = 1.e-7,
xtol_rel = 1.e-6,
xtol_abs = 0,
maxeval = 1000000
)
)
sol.outer