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  Example:: 
 9   
10      | genome 1 --       A B C D E F G 
11      |                   .   . .   . 
12      | genome 2 --       a b c d e f g 
13      | 
14      | After crossover: 
15      | 
16      | new genome 1 --  a B c d E f G 
17      | new genome 2 --  A b C D e F g 
18   
19  Uniform Crossover is a standard crossover technique for 
20  rapid mutation-behavior. 
21  """ 
22  # standard modules 
23  import random 
24   
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
34 - def __init__(self, crossover_prob=.1, uniform_prob=0.7):
35 """Initialize to do uniform crossover at the specified probability and frequency.""" 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 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