I want to maximize a function eval_f0
in R using the nloptr
interface to NLopt. One obvious way to do this is to minimize the function’s negative, i.e. function(x) { - eval_f0(x) }
. However, the NLopt manual says that there is also a feature that performs these sign flips internally:
[T]here is no need for NLopt to provide separate maximization routines in addition to its minimization routines—the user can just flip the sign to do maximization. As a convenience, however, NLopt provides a maximization interface (which performs the necessary sign flips for you, internally).
For the sake of consistency in a larger project, I would prefer using internal sign flips instead of flipping it manually. Unfortunately, I cannot find any reference as to how this option is named. How do I perform sign flips in NLopt or nloptr
?
Here is some example code:
library(nloptr)
# objective function
eval_f0 <- function( x, a, b ){
return( - sqrt(x[2]) )
}
# constraint function
eval_g0 <- function( x, a, b ) {
return( - (a*x[1] + b)^3 + x[2] )
}
# define parameters
a <- c(2,-1)
b <- c(0, 1)
# Solve using NLOPT_LN_COBYLA without gradient information
nloptr(x0 = c(1.234, 5.678),
eval_f=function(x, a, b){ - eval_f0(x, a, b) },
lb = c(-Inf, 0),
ub = c(Inf, Inf),
eval_g_ineq = function(x, a, b){ - eval_g0(x, a, b) },
opts = list("algorithm" = "NLOPT_LN_COBYLA"),
a = a,
b = b)