“multiple inequality constraints” - Minimization with R nloptr package

北城余情 提交于 2020-01-14 03:54:07

问题


Is there a way to define multiple "inequality constraints" in nloptr package in R?

The inequality function needs to have five inequality constraints; colsum of a matrix (stacked from a integer vector) <=1 . (5 out of 6 columns)

This is how I implemented to achieve it:

 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 is numeric vector that is stacked as a matrix.

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 is defined as below but when I run it, it says "number of inequality constraints =0".

  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)

Updated Answer: I defined the Constraint.func as

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:


I updated the the Constraint.func as and now the nloptr picks the inequality constraints.

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) }


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

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