I intend to use nloptr
package in a for
loop as below:
for(n in 1:ncol(my.data.matrix.prod))
{
alpha.beta <- as.vector(Alpha.beta.Matrix.Init[,n])
opts = list("algorithm"="NLOPT_LN_COBYLA",
"xtol_rel"=1.0e-8, "maxeval"= 2000)
lb = vector("numeric",length= length(alpha.beta))
result <- nloptr(alpha.beta,eval_f = Error.func.oil,lb=lb,
ub = c(Inf,Inf),eval_g_ineq=Const.func.oil,
opts = opts)
Final.Alpha.beta.Matrix[,n] <- result$solution
}
Apart from passing the "optimization parameters: alpha.beta
" to the error function(minimization function) , I also would like to send n
from the for
loop. Is there anyway to do this?
The error func is defined as:
Error.func.oil <- function(my.data.var,n)
{
my.data.var.mat <- matrix(my.data.var,nrow = 2,ncol = ncol(my.data.matrix.prod) ,byrow = TRUE)
qo.est.matrix <- Qo.Est.func(my.data.var.mat)
diff.values <- well.oilprod-qo.est.matrix #FIND DIFFERENCE BETWEEN CAL. MATRIX AND ORIGINAL MATRIX
Error <- ((colSums ((diff.values^2), na.rm = FALSE, dims = 1))/nrow(well.oilprod))^0.5 #sum of square root of the diff
Error[n]
}
The constraint function is simple and defined as:
Const.func.oil <- function(alpha.beta)
{
cnst <- alpha.beta[2]-1
cnst
}
So, when I run the above code, I get an error
Error in .checkfunargs(eval_f, arglist, "eval_f") : eval_f requires argument 'n' but this has not been passed to the 'nloptr' function.
How do I pass "n" to the error function? note that "n" is not to be optimized. It's just an index.
Okay. I read some examples online and found out that I can probably mention "n" in the definition of nloptr
itself as:
for(n in 1:ncol(my.data.matrix.prod))
{
alpha.beta <- as.vector(Alpha.beta.Matrix.Init[,n])
opts = list("algorithm"="NLOPT_LN_COBYLA",
"xtol_rel"=1.0e-8, "maxeval"= 5000)
lb = c(0,0)
result <- nloptr(alpha.beta,eval_f = Error.func.oil,lb=lb,
ub = c(Inf,Inf),
opts = opts, n=n) #Added 'n' HERE
Final.Alpha.beta.Matrix[,n] <- result$solution
}
This seems to have worked for me. Hence, I am setting this as closed.