Minimization with R nloptr package - multiple equality constraints
Asked Answered
T

1

10

Is it possible to specify more than one equality constraint in nloptr function in R? The code that I am trying to run is the following:

eval_f <- function( x ) {
  return( list( "objective" = x[3]^2+x[4]^2,
                "gradient" = c( 0,
                                0,
                                2*x[3],
                                2*x[4] ) ) )
}
# constraint functions
# equalities
eval_g_eq <- function( x ) {
  constr <- c( x[1] + x[2] + x[3] - 4,  
               x[1]^2 + x[2]^2 + x[4] - 15
  )
  grad <- c( c(1, 1, 1, 0),
             c(2*x[1], 2*x[2], 0, 1)
  )
  return( list( "constraints"=constr, "jacobian"=grad ) )
}
# initial values
x0 <- c( 1, 5, 5, 1 )
local_opts <- list( "algorithm" = "NLOPT_LD_MMA",
                    "xtol_rel" = 1.0e-7 )
opts <- list( "algorithm" = "NLOPT_LD_AUGLAG",
              "xtol_rel" = 1.0e-7,
              "maxeval" = 1000,
              "local_opts" = local_opts )
res <- nloptr( x0=x0,
               eval_f=eval_f,
               eval_g_eq=eval_g_eq,
               opts=opts)
print( res )

The result it produce is the following:

Current value of controls: -1.035323 3.093593 2.409501 0.2708714

However these values do not hold equality constraints, i.e.

-1.035323 + 3.093593 + 2.409501 = 4.467771
(-1.035323)^2 + 3.093593^2 + 0.2708714 = 10.91308

I guess that either it is impossible to specify multiple equality constraints in nloptr function or I passed them in the wrong way. I did not find any example having more than one equality constraint in package documentation.

UPDATE

Ok, I solved it. The case was that specifying constr and grad in eval_g_eq, one should use rbind() instead of c().

Taitaichung answered 15/7, 2015 at 13:19 Comment(3)
what is the quality constraints you want? the sum of squared first, squared second and fourth equal to 15?Debut
Yes, exactly this is what I want.Kendre
Hi, please let me know if this could be used for Price with demand optimization. I want to use NLP.Defector
I
0

I answered this in a different post recently for inequality constraints, but you should be able to return multiple equality constraints in a vector as well using c()

"multiple inequality constraints" - Minimization with R nloptr package

Imperceptive answered 4/1, 2021 at 14:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.