Package Bio :: Package GA :: Package Crossover :: Module Uniform
[hide private]
[frames] | no frames]

Source Code for Module Bio.GA.Crossover.Uniform

 1  # This code is part of the Biopython distribution and governed by its 
 2  # license.  Please see the LICENSE file that should have been included 
 3  # as part of this package. 
 4  # 
 5   
 6  """Perform uniform crossovers between the genomes of two organisms. 
 7   
 8   
 9  genome 1 --       A B C D E F G 
10                    .   . .   . 
11  genome 2 --       a b c d e f g 
12   
13  After crossover: 
14   
15  new genome 1 --  a B c d E f G 
16  new genome 2 --  A b C D e F g 
17   
18  Uniform Crossover is a standard crossover technique for 
19  rapid mutation-behavior. 
20  """ 
21  # standard modules 
22  import random 
23   
24   
25 -class UniformCrossover(object):
26 """Perform single point crossover between genomes at some defined rates. 27 28 This performs a single crossover between two genomes at some 29 defined frequency. The location of the crossover is chosen randomly 30 if the crossover meets the probability to occur. 31 """
32 - def __init__(self, crossover_prob = .1, uniform_prob = 0.7):
33 """Initialize to do uniform crossover at the specified probability and frequency. 34 """ 35 self._crossover_prob = crossover_prob 36 self._uniform_prob = uniform_prob 37 return
38
39 - def do_crossover(self, org_1, org_2):
40 """Potentially do a crossover between the two organisms. 41 """ 42 new_org_1 = org_1.copy() 43 new_org_2 = org_2.copy() 44 45 # determine if we have a crossover 46 crossover_chance = random.random() 47 if crossover_chance <= self._crossover_prob: 48 minlen = min(len(new_org_1.genome), len(new_org_2.genome)) 49 for i in range( minlen ): 50 uniform_chance = random.random() 51 if uniform_chance <= self._uniform_prob: 52 # cycle element 53 temp = new_org_1.genome[i] 54 new_org_1.genome[i] = new_org_2.genome[i] 55 new_org_2.genome[i] = temp 56 57 return new_org_1, new_org_2
58