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