|
GeneticAlgorithm
0.5 (beta)
A python framework for rapid GA prototyping
|
00001 import copy 00002 import random 00003 from Core import * 00004 00005 ## @class BinaryChromosomeSegment 00006 # @brief This class implements an integer variable encoded by a fixed number of bits 00007 # @todo: TikZ diagram for this class 00008 # 00009 # This class encodes an integer variable using nBits. 00010 class BinaryChromosomeSegment(BaseChromosomeSegment): 00011 ## @fn __init__(self, nBits, data) 00012 # @param nBits The number of bits for this chromosome segment 00013 # @param data The data contained in this chromosome segment 00014 # @brief Initialization function for the BinaryChromosomeSegment class 00015 # 00016 # Any named arguments passed to the constructor will be stored on a property with the same name 00017 def __init__(self, nBits=1, data=None, **kwargs): 00018 super(BinaryChromosomeSegment, self).__init__(nBits=nBits, data=data, **kwargs) 00019 00020 ## @fn __str__(self) 00021 # @brief This function returns the hexadecimal representation of this object 00022 # @return A string that contains the hexadecimal representation of this object 00023 def __str__(self): 00024 b = bin( self.data ) 00025 return b[:2] + '0' * ( 2+self.nBits-len(b) ) + b[2:] 00026 00027 ## @fn maxValue 00028 # @brief Return the maximum value allowed to this chromosome 00029 # 00030 # The max value is determined using this formula: (1<<self.nBits) -1, which is equivalent to the familiar equation \f$ 2^{nBits} -1\f$ 00031 def maxValue(self): 00032 return (1<<self.nBits)-1 00033 00034 ## @fn randomize(acceptFunction = lambda x: True) 00035 # @brief Set the chromosome value to a random value 00036 def randomize(self): 00037 self.data = random.randint(0, self.maxValue()) 00038 00039 ## @fn __setattr__(self, attr, value) 00040 # @brief This function insures that nBits is an integer and that data value never exceeds maxValue(self) 00041 def __setattr__(self, attr, value): 00042 if attr=='nBits': 00043 v = int(value) 00044 elif attr=='data': 00045 v = int(value) & self.maxValue() 00046 else: 00047 v = value 00048 super(BinaryChromosomeSegment, self).__setattr__(attr, v) 00049 00050 ## @fn crossover 00051 # @brief Cross two chromosomes choosing a single cross point within the limits of self. 00052 # @return A new BinaryChromosomeSegment object that contains the result of combining self and other 00053 def crossover(self, other): 00054 crossPoint = (1<<random.randint(0,self.nBits))-1; 00055 return BinaryChromosomeSegment(nBits=self.nBits, data=((self.data&crossPoint) | (other.data ^ (other.data&(crossPoint))))) 00056 00057 ## @fn mutate(self) 00058 # @brief Perform a single bit mutation within the range of self 00059 def mutate(self): 00060 self.data = self.data ^ (1<<random.randint(0,self.nBits-1)) 00061