Modi
Modi

Reputation: 143

Set constraints in a Matrix - OPTIM in R

I have a vector of integers as input values (starting values for optim par)

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)

The constraint that I must introduce is that colSum(my.data.var.mat) <=1

The optim is defined as

sols<-optim(my.data.var,Error.func,method="L-BFGS-B",upper=c(Inf,1,1,1,1,1,Inf,1,1,1,1,1,Inf,1,1,1,1,1,Inf,1,1,1,1,1),
  lower=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))

Error Function is defined as

Error.func <- function(my.data.var){


my.data.var.mat <- matrix(my.data.var,nrow = ncol(my.data.matrix.prod),ncol = ncol(my.data.matrix.inj)+1,byrow = TRUE)

  Calc.Qjk.Value <- Qjk.Cal.func(my.data.timet0,my.data.qo,my.data.matrix.time,
                                 my.data.matrix.inj, my.data.matrix.prod,my.data.var,my.data.var.mat)

  diff.values <- my.data.matrix.prod-Calc.Qjk.Value    #FIND DIFFERENCE BETWEEN CAL. MATRIX AND ORIGINAL MATRIX

  Error <- ((colSums ((diff.values^2), na.rm = FALSE, dims = 1))/nrow(my.data.matrix.inj))^0.5    #sum of square root of the diff

  Error_total <- sum(Error,na.rm=FALSE)/ncol(my.data.matrix.prod)   # total avg error

  Error_total
}

Given Dataset: my.data.matrix.prod , my.data.timet0, my.data.qo, my.data.matrix.time, my.data.matrix.inj

So, my question is how and where should I introduce the matrix col sum constraint? Or the other way to put it as how would OPTIM vary integer vector under Matrix col sum constraint?

Upvotes: 0

Views: 587

Answers (1)

Modi
Modi

Reputation: 143

I realized that nloptr is a better option than optim since my problem consisted of "inequality constraints".

I modified the implementation as I explain in this post here. "multiple inequality constraints" - Minimization with R nloptr package

Hence, closing this thread.

Upvotes: 1

Related Questions