Search code examples
rgenetic-algorithm

How to build a mutation algorithm for GA in R


I'm trying to build my mutation algorithm for GA.

It supposed to work like this: with a probability Pm the mutation passes - we draw two gens a & b. After that we change them order or a sequence between those two (if they're not neighbours). If the mutation doesn't pass - we don't do nothing.

Let's say we have an offspring [010110], if mutation starts, we choose AB = [2,5] that points at [0{1}01{1}0]. We do reverse and obtain [011010].

I build something like this:

for(i in 1 : popSize){
  genomeMutId <- which(runif(2, Dim*cel)>pMut

   for(j in 1:length(genomeMutId)){
    drawn <- runif(1,genomeMutId[j],lenght(genomeMutId))
    iter <- 0
    for(k in genomeMutId[j]:drawn) {
      tmpValue <- nextGeneration[i, k]
      nextGeneration[i, k] = nextGeneration[i, drawn-iter]
      nextGeneration[i, drawn-iter] = tmpValue 
      iter <- iter + 1
    }
   }
}

Unfortunately it doesn't work properly. Any suggestions? Maybe i use sample instead of runif?


Solution

  • You can do in this way :

    offspring <- c(0,1,0,1,1,0,1,1,0,1)
    
    # given an offspring vector (e.g. 0,1,0,0,1,0)
    # choose 2 cut points AB and invert the values between them
    getNewOffspring <- function(offspring){
      AB <- sort(sample.int(length(offspring),2))
      if(AB[2] - AB[1] > 2){
        subSqIdxs <- seq.int(from=AB[1]+1,to=AB[2]-1)
        offspring[subSqIdxs] <- rev(offspring[subSqIdxs])
      }
      offspring
    }
    

    Example usage :

    getNewOffspring(c(0,1,0,1,1,0,1,1,0,1))
    # e.g. with AB being 3,8
    > 0 1 0 1 0 1 1 1 0 1
    

    EDIT :

    Assuming the list of offsprings being stored in a list called offspringsList you can extract a random number for each offspring to decide which has to be mutated, and then call the previous function :

    offspringsToMutate <- which(runif(lenght(offspringsList)) > pM)
    
    for(offspringIndex in seq_len(length(offspringsToMutate))){
       mutated <- getNewOffspring(offspringsList[[offspringIndex]])
       offspringsToMutate[[offspringIndex]] <- mutated
    }
    # now the list contains the mutated offsprings