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

Source Code for Module Bio.GA.Crossover.General

 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  """General functionality for crossover that doesn't apply. 
 7   
 8  This collects Crossover stuff that doesn't deal with any specific 
 9  type of crossover. 
10  """ 
11  # standard library 
12  import random 
13   
14  # local stuff 
15  from Bio.GA.Organism import Organism 
16   
17   
18 -class SafeFitnessCrossover(object):
19 """Perform crossovers, but do not allow decreases in organism fitness. 20 21 This doesn't actually do any crossover work, but instead relies on 22 another class to do the crossover and just checks that newly created 23 organisms do not have less fitness. This is useful for cases where 24 crossovers can 25 """
26 - def __init__(self, actual_crossover, accept_less = 0.0):
27 """Initialize to do safe crossovers. 28 29 Arguments: 30 31 o actual_crossover - A Crossover class which actually implements 32 crossover functionality. 33 34 o accept_less - A probability to accept crossovers which 35 generate less fitness. This allows you to accept some 36 crossovers which reduce fitness, but not all of them. 37 """ 38 self._crossover = actual_crossover 39 self._accept_less_percent = accept_less 40 self._accept_less_rand = random.Random()
41
42 - def do_crossover(self, org_1, org_2):
43 """Perform a safe crossover between the two organism. 44 """ 45 new_org_1, new_org_2 = self._crossover.do_crossover(org_1, org_2) 46 47 return_orgs = [] 48 49 for start_org, new_org in ((org_1, new_org_1), 50 (org_2, new_org_2)): 51 new_org.recalculate_fitness() 52 53 # if the starting organism has a better fitness, 54 # keep it, minding the acceptance of less favorable change policy 55 if start_org.fitness > new_org.fitness: 56 accept_change = self._accept_less_rand.random() 57 if accept_change <= self._accept_less_percent: 58 return_orgs.append(new_org) 59 else: 60 return_orgs.append(start_org) 61 else: 62 return_orgs.append(new_org) 63 64 assert len(return_orgs) == 2, "Should have two organisms to return." 65 66 return return_orgs
67