# 1) one-dimensional function
f <- function(x) abs(x)+cos(x)
curve(f, -20, 20)
DE <- de(fitness = function(x) -f(x), lower = -20, upper = 20)
plot(DE)
summary(DE)
curve(f, -20, 20, n = 1000)
abline(v = DE@solution, lty = 3)
# 2) "Wild" function, global minimum at about -15.81515
wild <- function(x) 10*sin(0.3*x)*sin(1.3*x^2) + 0.00001*x^4 + 0.2*x + 80
plot(wild, -50, 50, n = 1000)
# from help("optim")
SANN <- optim(50, fn = wild, method = "SANN",
control = list(maxit = 20000, temp = 20, parscale = 20))
unlist(SANN[1:2])
DE <- de(fitness = function(...) -wild(...), lower = -50, upper = 50)
plot(DE)
summary(DE)
# 3) two-dimensional Rastrigin function
Rastrigin <- function(x1, x2)
{
20 + x1^2 + x2^2 - 10*(cos(2*pi*x1) + cos(2*pi*x2))
}
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)
DE <- de(fitness = function(x) -Rastrigin(x[1], x[2]),
lower = c(-5.12, -5.12), upper = c(5.12, 5.12),
popSize = 50)
plot(DE)
summary(DE)
filled.contour(x1, x2, f, color.palette = bl2gr.colors,
plot.axes = { axis(1); axis(2);
points(DE@solution,
col = "yellow", pch = 3, lwd = 2) })
# 4) two-dimensional Ackley function
Ackley <- function(x1, x2)
{
-20*exp(-0.2*sqrt(0.5*(x1^2 + x2^2))) -
exp(0.5*(cos(2*pi*x1) + cos(2*pi*x2))) + exp(1) + 20
}
x1 <- x2 <- seq(-3, 3, by = 0.1)
f <- outer(x1, x2, Ackley)
persp3D(x1, x2, f, theta = 50, phi = 20, col.palette = bl2gr.colors)
DE <- de(fitness = function(x) -Ackley(x[1], x[2]),
lower = c(-3, -3), upper = c(3, 3),
stepsize = NA)
plot(DE)
summary(DE)
filled.contour(x1, x2, f, color.palette = bl2gr.colors,
plot.axes = { axis(1); axis(2);
points(DE@solution,
col = "yellow", pch = 3, lwd = 2) })
# 5) Curve fitting example (see Scrucca JSS 2013)
if (FALSE) {
# subset of data from data(trees, package = "spuRs")
tree <- data.frame(Age = c(2.44, 12.44, 22.44, 32.44, 42.44, 52.44, 62.44,
72.44, 82.44, 92.44, 102.44, 112.44),
Vol = c(2.2, 20, 93, 262, 476, 705, 967, 1203, 1409,
1659, 1898, 2106))
richards <- function(x, theta)
{ theta[1]*(1 - exp(-theta[2]*x))^theta[3] }
fitnessL2 <- function(theta, x, y)
{ -sum((y - richards(x, theta))^2) }
DE <- de(fitness = fitnessL2, x = tree$Age, y = tree$Vol,
lower = c(3000, 0, 2), upper = c(4000, 1, 4),
popSize = 500, maxiter = 1000, run = 100,
names = c("a", "b", "c"))
summary(DE)
}
Run the code above in your browser using DataLab