I need to optimize a set of variables relative to an object function. I have an analytic function gradient, and I would like to use it in an optimization routine. Object and gradient have some common calculations, and I would like to define functions in the most efficient way. The following example demonstrates the problem.
Let f_obj, f_gradand f_commonbe functions for object, gradient and general calculations, respectively. Optimization is performed on the vector x. In the code below, the polynomial root is found y^3 - 3*y^2 + 6*y + 1, where yis the function c(x[1], x[2]). Note that the function f_commonis called both in f_objand in f_grad. In my real problem, the overall calculation is much longer, so I am looking for a way to determine f_objand f_gradso that the number of calls f_commonis minimized.
f_common <- function(x) x[1]^3*x[2]^3 - x[2]
f_obj <- function(x) {
y <- f_common(x)
return ( (y^3 - 3*y^2 + 6*y + 1)^2 )
}
f_grad <- function(x) {
y <- f_common(x)
return ( 2 * (y^3 - 3*y^2 + 6*y + 1) * (3*y^2 - 6*y + 6)* c(3*x[1]^2*x[2]^3, 3*x[1]^3*x[2]^2 - 1) )
}
optim(par = c(100,100), fn = f_obj, gr = f_grad, method = "BFGS")
UPDATE
I found that the package nloptroffers a means to enter the target function and its gradient in a list. Is there a way to determine the other optimizers ( optim, optimx, nlminbetc.) the same way?
Thank.