"多重不平等约束" - 使用R nloptr包最小化

时间:2016-06-21 18:15:43

标签: r nonlinear-optimization

有没有办法定义多个"不等式约束"在R?

nloptr包中

不平等函数需要有五个不等式约束;矩阵的colsum(从整数向量堆叠)< = 1。 (6列中的5列)

这是我实现它的方式:

 constraint.func <- function(my.data.var)
{
  column = 2
  constr <- c("numeric",ncol(my.data.matrix.inj) ) 

  for(index in 1:ncol(my.data.matrix.inj)) #1 to 5
  {
    constr[index] <- sum(my.data.var[column], my.data.var[column+6],  my.data.var[column+12], my.data.var[column+18])-1 
    column = column+1
  }
   constr.1 <- c(constr[1],constr[2],constr[3],constr[4],constr[5])

 return(constr.1)
}

my.data.var是数字向量,以矩阵形式堆叠。

my.data.var <- c(10,0.25,0.25,0.25,0.25,0.25,
             10,0.25,0.25,0.25,0.25,0.25,
             10,0.25,0.25,0.25,0.25,0.25,
             10,0.25,0.25,0.25,0.25,0.25)

my.data.var

NLOPTR定义如下,但是当我运行它时,它表示&#34;不等式约束的数量= 0&#34;。

  opts = list("algorithm"="NLOPT_LN_COBYLA",
            "xtol_rel"=1.0e-5, "maxeval"=500)

result <- nloptr(my.data.var,eval_f = Error.func,lb=c(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0),
                 ub = (Inf,1,1,1,1,1,Inf,1,1,1,1,1,Inf,1,1,1,1,1,Inf,1,1,1,1,1),
           eval_g_ineq=constraint.func,opts = opts)

print(result)

更新的答案: 我将Constraint.func定义为

constraint.func <- function(my.data.var)
{
  column = 2
  constr <- vector("numeric",length = 5)
  for(index in 1:ncol(my.data.matrix.inj))
  {
    constr[index] <- sum(my.data.var[column], my.data.var[column+6], my.data.var[column+12], my.data.var[column+18])-1
    column = column+1
  }
 return(constr)
}

2 个答案:

答案 0 :(得分:3)

更新了 Constraint.func ,现在 nloptr 选择了不等式约束。

constraint.func <- function(my.data.var)
{
  column = 2
  constr <- vector("numeric",length = 5)

 for(index in 1:ncol(my.data.matrix.inj))
  {
    constr[index] <- sum(my.data.var[column], my.data.var[column+6], my.data.var[column+12], my.data.var[column+18])-1
    column = column+1
  }
 return(constr) }

答案 1 :(得分:1)

我知道这已经晚了好几年了,但我最近也遇到了这个问题,似乎 eval_g_ineq 可以返回一个约束值向量:


library(nloptr)

# objective function
eval_f0 <- function( x, a, b ){return( sqrt(x[2]) )}

# constraint functions
eval_g0 <- function( x, a, b ) {
  
  g1 <- (a*x[1] + b)^3 - x[2] ^2
  g2 <- (a*x[1] + 2 * b)^3 - x[2]
  
  return( c(g1, g2) )
}

a <- c(2,-1)
b <- c(0, 1)
x0 <- c(1.234,5.678)

# Solve using NLOPT_LN_COBYLA without gradient information
res1 <- nloptr( x0=x0 ,
                eval_f=eval_f0,
                lb = c(-Inf,0),
                ub = c(Inf,Inf),
                eval_g_ineq = eval_g0,
                opts = list("algorithm" = "NLOPT_LN_COBYLA",
                            "xtol_rel" = 1e-8,
                            "maxeval" = 1e4,
                            "print_level" = 2),
                a = a, 
                b = b )
print( res1 )