Minimization with R nloptr package - multiple equality constraints

試著忘記壹切 提交于 2019-12-22 06:27:14

问题


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().

来源:https://stackoverflow.com/questions/31431575/minimization-with-r-nloptr-package-multiple-equality-constraints

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!