简体   繁体   English

将参数传递给nloptr目标函数-R

[英]Passing parameters to nloptr objective function - R

I intend to use nloptr package in a for loop as below: 我打算在for循环中使用nloptr包,如下所示:

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. 除了将“优化参数: alpha.beta ”传递给错误函数(最小化函数)之外,我还想从for循环中发送n 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. .checkfunargs(eval_f,arglist,“ eval_f”)中的错误:eval_f需要参数'n',但尚未传递给'nloptr'函数。

How do I pass "n" to the error function? 如何将“ n”传递给错误函数? note that "n" is not to be optimized. 注意,“ n”将不被优化。 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: 我在网上阅读了一些示例,发现我可以在nloptr本身的定义中提及“ n”:

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. 因此,我将其设置为关闭。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM