Package Bio :: Package GA :: Package Mutation :: Module Simple
[hide private]
[frames] | no frames]

Source Code for Module Bio.GA.Mutation.Simple

 1  """Perform Simple mutations on an organism's genome. 
 2  """ 
 3  # standard modules 
 4  import random 
 5   
6 -class SinglePositionMutation(object):
7 """Perform a conversion mutation, but only at a single point in the genome. 8 9 This does not randomize the genome as much as ConversionMutation, since 10 only one change is allowed per genome at the specified mutation rate. 11 """
12 - def __init__(self, mutation_rate = 0.001):
13 """Initialize a mutator. 14 15 Arguments: 16 17 o mutation_rate - The chance of a mutation happening once in the 18 genome. 19 """ 20 self._mutation_rate = mutation_rate 21 # a random number generator to test if we have a mutation 22 self._mutation_rand = random.Random() 23 # a random number generator to switch to a new alphabet letter 24 self._switch_rand = random.Random() 25 # a random number generator to find the mutation position 26 self._pos_rand = random.Random()
27
28 - def mutate(self, organism):
29 """Mutate the organisms genome. 30 """ 31 mutated_org = organism.copy() 32 gene_choices = mutated_org.genome.alphabet.letters 33 34 mutation_chance = self._mutation_rand.random() 35 if mutation_chance <= self._mutation_rate: 36 # pick a gene position to mutate at 37 mutation_pos = \ 38 self._pos_rand.choice(range(len(mutated_org.genome))) 39 40 # get a new letter to replace the position at 41 new_letter = self._switch_rand.choice(gene_choices) 42 43 mutated_org.genome[mutation_pos] = new_letter 44 45 return mutated_org
46
47 -class ConversionMutation(object):
48 """Potentially mutate any item to another in the alphabet. 49 50 This just performs switching mutation -- changing one gene of a genome 51 to any other potential gene, at some defined frequency. If the organism 52 is determined to mutate, then the alphabet item it is equally likely 53 to switch to any other letter in the alphabet. 54 """
55 - def __init__(self, mutation_rate = 0.001):
56 """Inititialize a mutator. 57 58 Arguments: 59 60 o mutation_rate -- The chance of a mutation happening at any 61 position in the genome. 62 """ 63 self._mutation_rate = mutation_rate 64 # a random number generator to test if we have a mutation 65 self._mutation_rand = random.Random() 66 # a random number generator to switch to a new alphabet letter 67 self._switch_rand = random.Random()
68
69 - def mutate(self, organism):
70 """Mutate the organisms genome. 71 """ 72 mutated_org = organism.copy() 73 74 gene_choices = mutated_org.genome.alphabet.letters 75 76 # potentially mutate any gene in the genome 77 for gene_index in range(len(mutated_org.genome)): 78 mutation_chance = self._mutation_rand.random() 79 # if we have a mutation 80 if mutation_chance <= self._mutation_rate: 81 # get a new letter 82 new_letter = self._switch_rand.choice(gene_choices) 83 mutated_org.genome[gene_index] = new_letter 84 85 return mutated_org
86