# Maximize a trivial 5 variable function
# The function and search-space below will be used for all examples
fitness.FUN = function(x) sum(x)
lb = c(0, 0, 0, 0, 0)
ub = c(10, 10, 10, 10, 10)
ga1 = GAReal(fitness.FUN, lb, ub)
ga1$evolve(200)
plot(ga1)
# A custom selection example
selec.FUN = function(population, fitnessVec, nleft)
{
# population - The population matrix
# fitnessVec - The corresponding fitness vector for the population matrix
# nleft - The number of individuals you should select
half = as.integer(nleft/2)
remain = nleft - half
idxs = 1:nrow(population)
# pick half using fitness-proportionate
rowIdxs = sample(idxs, half, replace = TRUE, prob = fitnessVec)
# pick the other half randomly
rowIdxs = c(rowIdxs, sample(idxs, remain, replace = TRUE))
# Just return the nLeft selected row indexes
return(rowIdxs)
}
ga2 = GAReal(fitness.FUN, lb, ub, selection = selec.FUN)
ga2$evolve(200)
summary(ga2)
# A custom crossover example
crossover.FUN = function(parent1, parent2, prob)
{
# parent1, parent2 - The individuals to crossover
# prob - The probability of a crossover happen (cxRate parameter)
# Respect the cxRate parameter: if DNA is not exchanged, just return the parents
if (runif(1) > prob)
return(matrix(c(parent1, parent2), nrow = 2, byrow = TRUE))
# A simple uniform crossover - just swap the 'genes' with a probability of 0.5
for (i in 1:length(parent1))
{
if (runif(1) > 0.5)
{
tempval = parent1[i]
parent1[i] = parent2[i]
parent2[i] = tempval
}
}
# You should return a matrix in this format
return(matrix(c(parent1, parent2), nrow = 2, byrow = TRUE))
}
ga3 = GAReal(fitness.FUN, lb, ub, crossover = crossover.FUN)
ga3$evolve(200)
plot(ga3)
# A custom mutation example
mutation.FUN = function(population, nMut)
{
# population - The population matrix to apply mutation
# nMut - The number of mutations you supposed to apply, according to mutRate
rows = sample(1:nrow(population), nMut, replace = TRUE)
cols = sample(1:ncol(population), nMut, replace = TRUE)
noise = (runif(nMut))^2
# extract the matrix indexes
ext = matrix(c(rows, cols), nMut, 2)
population[ext] = noise
return(population)
}
ga4 = GAReal(fitness.FUN, lb, ub, mutation = mutation.FUN)
ga4$evolve(200)
summary(ga4)
Run the code above in your browser using DataLab