简体   繁体   中英

DEOptim keeps telling: NaN value of objective function

I've written a simulation program in C++ and like to find parameters in R, using DEoptim. Sometimes everything works well and sometimes DEoptim stops and tells:

Error in DEoptim(simulate, lower = lb, upper = ub, control = opt) : 
  NaN value of objective function! 
Perhaps adjust the bounds.

My R-script defines a function that calls the external binary. The parameters are attached to the command. I tested my C++ program and have never seen NaN's returned. Further, to investigate I check for NaN's in the simulate() R-function, such that it would stop and tell that there is actually a NaN value. However, it does never stop there - but later in DEoptim. What is the problem? Is this a DEoptim-Bug?

library("DEoptim")
setwd("some-path")

simulate <- function(theta)
{
  strcom <- paste(c("./ExternalBinary", theta),collapse=" ")
  ret <- as.numeric(system(strcom, intern=T)) #will return a couple of integer numbers
  ret <- mean(ret) #average those numbers
  if(any(is.nan(ret))){ #check against NaNs
    stop('Found a NaN?!') #this line is NEVER called, even if DEoptim stops
  }
  return(ret)
}

lb <- rep(-10.,18) #18 parameters in the range of -10...10
ub <- -lb

opt <- list(NP=500,itermax=10, storepopfrom=1, storepopfreq=1, parallelType=1)
est <- DEoptim(simulate,lower=lb,upper=ub, control=opt)

EDIT: I found that the return is actually not NaN but NA. The simulate() function stops if I replace is.nan(ret) with is.na(ret) . I also went through my c++ program again and could not find a way how it quits without writing a number to cout . Hence I asked this question: Can a main() return before all cout has been written to the consol?

To go around this problem with DEoptim, I return a high value when there is a NaN or NA. If you want to minimize the function simulate, it should work. I often use this "trick" with DEoptim.

simulate <- function(theta)
{
  strcom <- paste(c("./ExternalBinary", theta), collapse =" ")
  ret <- as.numeric(system(strcom, intern = TRUE)) 
  ret <- mean(ret) 
  
  if(any(is.nan(ret)))
  { 
    return(10 ^ 30)
    
  }else
  {
    return(ret)
  }
}

This indicates to DEoptim that these parameters are not a candidate solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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