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  __docformat__ = "restructuredtext en" 
25   
26   
27 -class UniformCrossover(object):
28 """Perform single point crossover between genomes at some defined rates. 29 30 This performs a single crossover between two genomes at some 31 defined frequency. The location of the crossover is chosen randomly 32 if the crossover meets the probability to occur. 33 """
34 - def __init__(self, crossover_prob=.1, uniform_prob=0.7):
35 """Initialize to do uniform crossover at the specified probability and frequency. 36 """ 37 self._crossover_prob = crossover_prob 38 self._uniform_prob = uniform_prob 39 return
40
41 - def do_crossover(self, org_1, org_2):
42 """Potentially do a crossover between the two organisms. 43 """ 44 new_org_1 = org_1.copy() 45 new_org_2 = org_2.copy() 46 47 # determine if we have a crossover 48 crossover_chance = random.random() 49 if crossover_chance <= self._crossover_prob: 50 minlen = min(len(new_org_1.genome), len(new_org_2.genome)) 51 for i in range(minlen): 52 uniform_chance = random.random() 53 if uniform_chance <= self._uniform_prob: 54 # cycle element 55 temp = new_org_1.genome[i] 56 new_org_1.genome[i] = new_org_2.genome[i] 57 new_org_2.genome[i] = temp 58 59 return new_org_1, new_org_2
60