#######################################################
# This R code allows one to identify the maximum of a set 
# of optimisation problems defined in the n-dimensional 
# Euclidean space, by using the GA-package of R.
#
# Designed by Ebert Brea
# emails: ebertbrea@gmail, ebert.brea@ucv.ve
#######################################################
setwd("~/My R/GA")
rm(list=ls())
require(GA)
## Loading required package: GA
## Loading required package: foreach
## Loading required package: iterators
## Package 'GA' version 3.1.1
## Type 'citation("GA")' for citing this R package in publications.
#####################
probl=5
dim=2
#####################
x<-numeric(dim)
f<-function(x,probl,dim){
  g=0
  switch(probl,
         {for(k in 1:dim){g=g+(x[k])^2}},
         {g=(1+(x[1]+x[2]+1)^2*(19-14*x[1]+3*x[1]^2-14*x[2]+6*x[1]*x[2]+3*x[2]^2))*
           (30+(2*x[1]-3*x[2])^2*(18-32*x[1]+12*x[1]^2+48*x[2]-36*x[1]*x[2]+27*x[2]^2))+
           10^6*max(-2.5-x[1],0)+10^6*max(x[1]-2.5,0)+
           10^6*max(-2.5-x[2],0)+10^6*max(x[2]-2.5,0)},
         {for(k in 1:dim){g=g+(x[k])^2-cos(2*pi*x[k])}},
         {for(k in 1:dim){g=g+sin(x[k])+sin(2*x[k]/3)+10^6*max(3-x[k],0)+10^6*max(x[k]-13,0)}},
         {for(k in 1:dim){g=g+(x[k]/5)^4-(x[k]-2)^2}})
  return(g)
}

lo<-numeric(dim)
hi<-numeric(dim)
for(k in 1:dim){lo[k]=-20; hi[k]=20}

GA <-ga(type = "real-valued", 
        fitness = function(x) -f(x,probl,dim),
        lower = lo, upper = hi, popSize =(50*dim), 
        maxiter = 400, run = 20, pmutation=0.1, 
        pcrossover=0.7, elitism = max(1,round(0.05*50*dim)), 
        monitor=FALSE)

summary(GA)
## -- Genetic Algorithm ------------------- 
## 
## GA settings: 
## Type                  =  real-valued 
## Population size       =  100 
## Number of generations =  400 
## Elitism               =  5 
## Crossover probability =  0.7 
## Mutation probability  =  0.1 
## Search domain = 
##        x1  x2
## lower -20 -20
## upper  20  20
## 
## GA results: 
## Iterations             = 75 
## Fitness function value = 465.6431 
## Solution = 
##             x1        x2
## [1,] -18.42418 -18.59413
plot(GA)