Back to index

python-biopython  1.60
General.py
Go to the documentation of this file.
00001 """General functionality for mutations.
00002 """
00003 # standard library
00004 import random
00005 
00006 # local stuff
00007 from Bio.GA.Organism import Organism
00008 
00009 class SafeFitnessMutation(object):
00010     """Perform mutations, but do not allow decreases in organism fitness.
00011 
00012     This doesn't actually do any mutation work, but just checks that
00013     newly create organisms do not have lower fitnesses. 
00014     """
00015     def __init__(self, actual_mutation, accept_less = 0.0):
00016         """Initialize to do safe mutations
00017 
00018         Arguments:
00019 
00020         o actual_mutation - A Mutation class which actually implements
00021         mutation. functionality.
00022 
00023         o accept_less - A probability to accept mutations which
00024         generate lower fitness. This allows you to accept some
00025         crossovers which reduce fitness, but not all of them.
00026         """
00027         self._mutation = actual_mutation
00028         self._accept_less_percent = accept_less
00029         self._accept_less_rand = random.Random()
00030 
00031     def mutate(self, org):
00032         """Perform safe mutation of the specified organism.
00033         """
00034         new_org = self._mutation.mutate(org)
00035         new_org.recalculate_fitness()
00036 
00037         if org.fitness > new_org.fitness:
00038             accept_less_chance = self._accept_less_rand.random()
00039             if accept_less_chance <= self._accept_less_percent:
00040                 return new_org
00041             else:
00042                 return org
00043         else:
00044             return new_org