Cl17
Cl17

Reputation: 23

How to optimize a non-linear objective function with non-linear constraints in R?

Say, there is a non-linear objective function :

Z= a1 + b1 * ln(x1) + a2 + b2 *ln(x2)  with the objective of maximizing Z

subject to the following constraints-

x1 + x2 + x3 >=R1
x1 + x2 + x3 <=R2
a1 + b1 * ln(x1) >=R3

How can the objective function be optimized in R? Tried using 'Rsolnp' package available in R, however not sure how to frame the constraints and the objective function that will be given to the function 'solnp' in the package.

Can anyone help me with this?

Upvotes: 2

Views: 612

Answers (1)

Sandipan Dey
Sandipan Dey

Reputation: 23101

Try this (you may want to use other algorithms like NLOPT_LD_MMA with jacobian specified):

library(nloptr)
a1 <- b1 <- 1
a2 <- b2 <- 1
R1 <- R2 <- 1
R3 <- 25

eval_f1 <- function( x, a1, b1, a2, b2, R1, R2, R3){ 
  return(-a1 - b1 * log(x[1]) - a2 - b2 *log(x[2])) # maximize
}


eval_g1 <- function( x, a1, b1, a2, b2, R1, R2, R3) {
  return(rbind(x[1] + x[2] + x[3] - R1,
               -x[1] - x[2] - x[3] + R2,
               R3 - a1 - b1*log(x[1])))
}

nloptr(x0=c(1,1,1), 
        eval_f=eval_f1, 
        lb = c(1,1,1), 
        ub = c(5,5,5), 
        eval_g_ineq = eval_g1, 
        opts = list("algorithm"="NLOPT_LN_COBYLA"),
        a1 = a1,
        b1 = b1,
        a2 = a2,
        b2 = b2,
        R1 = R1,
        R2 = R2,
        R3 = R3)

#Call:
#nloptr(x0 = c(1, 1, 1), eval_f = eval_f1, lb = c(1, 1, 1), ub = c(5, 
#    5, 5), eval_g_ineq = eval_g1, opts = list(algorithm = "NLOPT_LN_COBYLA"),     
#a1 = a1, b1 = b1, a2 = a2, b2 = b2, R1 = R1, R2 = R2, R3 = R3)


#Minimization using NLopt version 2.4.0 

#NLopt solver status: 5 ( NLOPT_MAXEVAL_REACHED: Optimization stopped because #maxeval (above) was reached. )

#Number of Iterations....: 100 
#Termination conditions:  relative x-tolerance = 1e-04 (DEFAULT) 
#Number of inequality constraints:  3 
#Number of equality constraints:    0 
#Current value of objective function:  -5.08783644210816 
#Current value of controls: 5 4.385916 2.550764

Upvotes: 1

Related Questions