#Baseball - Genetic algorithm
rm(list=ls())
#setwd("V:/PROMAX/PROMAX-Odd/Lecture/STK4051-9051/Lectures_Odd/Lecture2_R/wd")
baseball <- read.table("baseball.dat",header=T)
baseball$freeagent = factor(baseball$freeagent)
baseball$arbitration = factor(baseball$arbitration)
p = ncol(baseball)-1
P = 50   # Population size
pop = matrix(NA,nrow=P,ncol=p)
AICfit = rep(NA,P)
set.seed(232323)

#Generate initial population
for(k in 1:P)
{
 pop[k,] = sample(0:1,p,replace=T)
 ind = c(1:p)[pop[k,]==1]
 base2 = baseball[,c(1,1+ind)]
 AICfit[k] = AIC(lm(log(salary)~.,data=base2))
}

AICseq = AICfit
more = TRUE
Numit=100
pop.new = pop
AICfit.new = AICfit
mu = 0.01   #Probability for mutation
#Start iteration on updating populations
for(i in 1:Numit)
{
 for(k in 1:P) # for all individuals in the next generation
  {
    #Selecting parents with probability proportional to exp(-AIC)
    phi1 = exp(-AICfit)
    phi2 = exp(-AICfit)
   
    #Selecting parents
    parent1 = sample(1:P,1,prob=phi1)
    parent2 = sample(1:P,1,prob=phi2*0+1)

    #Sampling independently which parent to inherit from
    bred = sample(1:2,p,replace=T)
    pop.new[k,bred==1] = pop[parent1,bred==1]
    pop.new[k,bred==2] = pop[parent2,bred==2]
    
    #Mutation
    ind2 = sample(0:1,p,replace=T,prob=c(1-mu,mu))
    if(sum(ind2)>0)
      pop.new[k,ind2==1] = 1-pop.new[k,ind2==1]
    
    #Extract only those components that are selected
    ind = c(1:p)[pop.new[k,]==1]
    base2 = baseball[,c(1,1+ind)]
    #Fit the new model
    AICfit.new[k] = AIC(lm(log(salary)~.,data=base2))
  }
  pop = pop.new
  AICfit = AICfit.new
  AICseq = rbind(AICseq,AICfit)
}
matplot(AICseq,pch=1)
show(min(AICseq))
plot.ts(apply(AICseq,1,min))
