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

Source Code for Module Bio.GA.Crossover.General

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