###############################################################
# This R code allows one to identify the minimum of a set 
# of nonlinear 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.
#=============================================================================
#   No of problem         Objective function                dim
#=============================================================================
#         1               Quadratic function                  n
#         2             Goldstein Price function              2
#         3               Rastrigin function                  n
#         4                  Tang function                    n
#         5                  New W function                   n
#=============================================================================

#############################################################
rm(list=ls())
ne=0
samples=5 #100
#####################
problem=2
dim=2
#####################
x<-numeric(dim)
f<-function(x,problem,dim){
  g=0
  ne<<-ne+1
  switch(problem,
         {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]/4)^4+1-(x[k]-2)^2}}  )
  return(g)
}

TP<-numeric(dim)
lo<-numeric(dim)
hi<-numeric(dim)
for(k in 1:dim){lo[k]=-20; hi[k]=20}
if(file.exists("filltxt")){close(filtxt)}
switch(problem,
       {for(k in 1:dim){TP[k]=0}; filtxt <- file("RGA-Q.txt")},
       {TP[1]=0; TP[2]=-1; filtxt <- file("RGA-GoldsteinPrice.txt")},
       {for(k in 1:dim){TP[k]=0}; filtxt <- file("RGA-Rastrigin.txt")},
       {for(k in 1:dim){TP[k]=5.371235409403596}; filtxt <- file("RGA-Tang.txt")},
       {for(k in 1:dim){TP[k]=-12.20549696692415}; filtxt <- file("RGA-WF.txt")}   )

#############################################################
#     For printing the solution of the problem "problem".
#############################################################
print(quote=FALSE,justify ="left",c("The solution is at: ",TP))
## [1] The solution is at:  0                    -1
#############################################################
mx=5*samples
performance <- matrix(1:mx, ncol = 5)
fil <- tempfile("data")
filtxt <- file("GAdata.txt")
print(quote=FALSE,"List of Acronyms")
## [1] List of Acronyms
print(quote=FALSE,"NEOF: Number of Evaluations of the Objective Function")
## [1] NEOF: Number of Evaluations of the Objective Function
print(quote=FALSE,"DTP: Distance to the True Point")
## [1] DTP: Distance to the True Point
for(i in 1:samples){
  ne=0
  GA <-ga(type = "real-valued", 
          fitness =  function(x) -f(x,problem,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)
  vdif=TP-GA@solution
  dtp<-sum(vdif*vdif)
  dtp<-sqrt(dtp)
  Q<-1/(1+dtp*ne)
  performance[i,1]=i
  performance[i,2]=GA@fitnessValue
  performance[i,3]=ne
  performance[i,4]=dtp
  performance[i,5]=Q
  print(quote=FALSE,"=================================================")
  print(quote=FALSE,c("Replication No. ",i))
  print(quote=FALSE,c("f(x) = ",GA@fitnessValue))
  print(quote=FALSE,c("NEOF =",ne))
  print(quote=FALSE,c("DTP =",dtp))
  print(quote=FALSE,c("Q =",Q))
  print(quote=FALSE,GA@solution)
}
## [1] =================================================
## [1] Replication No.  1               
## [1] f(x) =            -3.02123794674173
## [1] NEOF = 2949  
## [1] DTP =               0.00768657531898843
## [1] Q =               0.042251657384081
##                x1       x2
## [1,] -0.002250736 -1.00735
## [1] =================================================
## [1] Replication No.  2               
## [1] f(x) =            -3.03792773482052
## [1] NEOF = 5690  
## [1] DTP =              0.0127965407111099
## [1] Q =                0.0135478744664394
##               x1         x2
## [1,] 0.009065326 -0.9909683
## [1] =================================================
## [1] Replication No.  3               
## [1] f(x) =            -3.00648588943028
## [1] NEOF = 2949  
## [1] DTP =               0.00491531038479648
## [1] Q =                0.0645359048121849
##             x1        x2
## [1,] 0.0049039 -1.000335
## [1] =================================================
## [1] Replication No.  4               
## [1] f(x) =            -5.57298171665744
## [1] NEOF = 2798  
## [1] DTP =             0.106994039243407
## [1] Q =                 0.00332923480333215
##              x1         x2
## [1,] 0.07663934 -0.9253399
## [1] =================================================
## [1] Replication No.  5               
## [1] f(x) =            -3.31533573006757
## [1] NEOF = 2938  
## [1] DTP =              0.0271161838301003
## [1] Q =                0.0123965894955313
##               x1         x2
## [1,] -0.01888047 -0.9805368
for(i in 1:samples){
  write(t(performance), fil, sep = "\t",ncol=5)
  write(t(performance), filtxt, sep = "\t",ncol=5)
  sprintf("%.3f",pi)
}
if(file.exists("filltxt")){close(filtxt)}

if(interactive()) file.show(fil)
unlink(fil) # tidy up

print(TP)
## [1]  0 -1
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             = 40 
## Fitness function value = -3.315336 
## Solution = 
##               x1         x2
## [1,] -0.01888047 -0.9805368
plot(GA)