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

Source Code for Module Bio.GA.Mutation.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 mutations.""" 
 7  # standard library 
 8  import random 
 9   
10  # local stuff 
11  from Bio.GA.Organism import Organism 
12   
13   
14 -class SafeFitnessMutation(object):
15 """Perform mutations, but do not allow decreases in organism fitness. 16 17 This doesn't actually do any mutation work, but just checks that 18 newly create organisms do not have lower fitnesses. 19 """ 20
21 - def __init__(self, actual_mutation, accept_less=0.0):
22 """Initialize to do safe mutations. 23 24 Arguments: 25 - actual_mutation - A Mutation class which actually implements 26 mutation. functionality. 27 - accept_less - A probability to accept mutations which 28 generate lower fitness. This allows you to accept some 29 crossovers which reduce fitness, but not all of them. 30 31 """ 32 self._mutation = actual_mutation 33 self._accept_less_percent = accept_less 34 self._accept_less_rand = random.Random()
35
36 - def mutate(self, org):
37 """Perform safe mutation of the specified organism.""" 38 new_org = self._mutation.mutate(org) 39 new_org.recalculate_fitness() 40 41 if org.fitness > new_org.fitness: 42 accept_less_chance = self._accept_less_rand.random() 43 if accept_less_chance <= self._accept_less_percent: 44 return new_org 45 else: 46 return org 47 else: 48 return new_org
49