使用R nloptr包最小化-多个相等约束

Paw*_*ski 5 equality r constraints nonlinear-optimization nlopt

是否可以nloptr在R 中的函数中指定多个相等约束?我尝试运行的代码如下:

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 )
Run Code Online (Sandbox Code Playgroud)

它产生的结果如下:

Current value of controls: -1.035323 3.093593 2.409501 0.2708714
Run Code Online (Sandbox Code Playgroud)

但是,这些值不具有相等约束,即

-1.035323 + 3.093593 + 2.409501 = 4.467771
(-1.035323)^2 + 3.093593^2 + 0.2708714 = 10.91308
Run Code Online (Sandbox Code Playgroud)

我猜想要么无法在nloptr函数中指定多个相等约束,要么我以错误的方式传递了它们。我没有在软件包文档中找到任何具有多个平等约束的示例。

更新

好的,我解决了。情况是指定constrgradin eval_g_eq,应该用rbind()代替c()

小智 0

我最近在另一篇关于不等式约束的文章中回答了这个问题,但是您应该能够使用向量返回多个等式约束c()

“多重不等式约束” - 使用 R nloptr 包进行最小化