I am working with the R programming language. I am trying to learn about different optimization algorithms such as the "Genetic Algorithm" (e.g. https://cran.r-project.org/web/packages/GA/vignettes/GA.html, https://cran.r-project.org/web/packages/GA/index.html) vs. the "Evolutionary Grammar Algorithm" (e.g. https://cran.r-project.org/web/packages/gramEvol/gramEvol.pdf , https://www.jstatsoft.org/article/view/v071i01).
For instance, I can use the Genetic Algorithm to optimize the following function ("Rastrigin") :
#PART 1: Optimize Rastrigin Function with the Genetic Algorithm
library(GA)
#define function
Rastrigin <- function(x1, x2)
{
20 + x1^2 + x2^2 - 10*(cos(2*pi*x1) + cos(2*pi*x2))
}
#plot
x1 <- x2 <- seq(-5.12, 5.12, by = 0.1)
f <- outer(x1, x2, Rastrigin)
persp3D(x1, x2, f, theta = 50, phi = 20, col.palette = bl2gr.colors)
#run optimization algorithm and plot results
GA <- ga(type = "real-valued",
fitness = function(x) -Rastrigin(x[1], x[2]),
lower = c(-5.12, -5.12), upper = c(5.12, 5.12),
popSize = 50, maxiter = 1000, run = 100)
plot(GA)
summary(GA)
Fitness function value = -2.502466e-07
Solution =
x1 x2
[1,] 3.341508e-05 1.203355e-05
Problem: However, I am running into errors when I try to use the "Evolutionary Grammar Algorithm" to optimize the same function:
#PART 2: Optimize Rastrigin Function with the Evolutionary Grammar Algorithm:
library(gramEvol)
ruleDef <- list(expr = gsrule("<der.expr><op><der.expr>"),
der.expr = grule(func(var), var),
func = grule(log, exp, sin, cos),
op = gsrule("+", "-", "*"),
var = grule(x1, x2, n),
n = grule(1, 2, 3, 4))
# Creating the grammar object
grammarDef <- CreateGrammar(ruleDef)
#redine the same function in a format acceptable to the "gramEvol" library
Rastrigin <- function(expr) {
# expr: a string containing a symbolic expression
# returns: Symbolic regression Error
x1 <- c(5.12, 5.12)
x2 <- c(5.12, 5.12)
result <- eval(as.expression(expr))
err <- 20 + x1^2 + x2^2 - 10*(cos(2*pi*x1) + cos(2*pi*x2))
return(err)
}
#run optimization (problem)
ge <- GrammaticalEvolution(grammarDef, evalFunc, terminationCost = 0.001)
# print results (problem)
print(ge, sequence = TRUE)
The last two lines of code return the following errors:
Error in EvolutionStrategy.int(genomeLen = chromosomeLen, codonMin = 0, :
Invalid cost function return value (NA or NaN).
In addition: Warning messages:
1: In result - X :
longer object length is not a multiple of shorter object length
2: In result - X :
longer object length is not a multiple of shorter object length
#etc
Question: Can someone please show me how to fix this problem? What is result - X ? What exactly is longer object length is not a multiple of shorter object length referring to?
Thanks!
Source: https://rdrr.io/cran/gramEvol/man/GrammaticalEvolution.html
