Search code examples
roptimizationdata.tabledifferential-evolution

DEoptim error: objective function result has different length than parameter matrix


I'm trying to use the DEoptim command (from the R package of the same name) to minimize a function, but am getting this strange error “objective function result has different length than parameter matrix.” I can't find anything about this problem, other than some posted C code I can't read.

The error comes up when I try to pass additional parameters to the function through the ... argument. In the following example, I amend the Rosenbrock function (taken from the DEoptim documentation) to have a second argument pow (which I set to 2, so that the example is identical to the documented one). This works. Then I try to do the same with the Rastrigin function (from the GenSA documentation). The same trick fails here (but the optimizer works fine if I hardcode in my second argument, as in the documented case).

Here is the example code:

library(DEoptim)
## Note that the vector of parameters to be optimized must be the first
## argument of the objective function passed to DEoptim.
Rosenbrock <- function(x,pow){
  x1 <- x[1]
  x2 <- x[2]
  100 * (x2 - x1 * x1)^pow + (1 - x1)^pow
}

lower <- c(-10,-10)
upper <- -lower
set.seed(1234)

# works
DEoptim(Rosenbrock,pow=2, lower, upper)

Rastrigin <- function(x) {
  sum(x^2 - 10 * cos(2 * pi * x)) + 10 * length(x)
}

Rastrigin2 <- function(x,p) {
  sum(x^2 - p * cos(2 * pi * x)) + 10 * length(x)
}

dimension <- 2
lower <- rep(-5.12, dimension)
upper <- rep(5.12, dimension)

# works
DEoptim(fn=Rastrigin,lower=lower,upper=upper,
        control = list(storepopfrom = 1))

# should be same, but doesn't work
DEoptim(fn=Rastrigin2,p=10,lower=lower,upper=upper,
        control = list(storepopfrom = 1))

Naturally, this problem has come up in a more complicated example, but I'm hoping that an explanation on this simple case can help me out. If it's any additional help, the ultimate goal is to call a function from a data.table object, where the function's first argument is a (scalar) parameter to be minimized, and the remaining arguments are data taken from the data.table.


Solution

  • I'd have to look deeper for the root cause, but it looks like your p argument is partially matching another argument somewhere down the optimization/evaluation process. The work-around is to use a different name for that argument.

    require(DEoptim)
    Rastrigin2 <- function(x,p.) {
      sum(x^2 - p. * cos(2 * pi * x)) + 10 * length(x)
    }
    lower <- rep(-5.12, 2)
    upper <- -lower
    de <- DEoptim(Rastrigin2, lower, upper, list(storepopfrom=1), p.=10)
    

    I'll file a bug report. Thanks for the reproducible example!