def main(): #Assign initial parameter num_queens = int(input("Enter the number of queens : ") or "5") population_size = int(input("Enter the population size : ") or "12") pool_size = int(input("Enter the mating pool size : ") or "6") mutation_rate = float(input("Enter the mutation rate : ") or "0.2") num_generation = int( input("Enter the total number of Generations : ") or "20") #Generate & print initial population population = intial_population(population_size, num_queens) print('population') print_population(population) print_matrix(population, num_queens) #Generate & print next population for index in range(num_generation): #genetic operations mating_pool = selection(population, pool_size) next_gen = assign_fitness( crossover(mating_pool, num_queens, pool_size, population_size)) mutation_status = mutation(population, num_queens, population_size, mutation_rate) #Output to console print("Generation number :", index + 1) print('\nmating pool') print_population(mating_pool) print("Mutation status {}".format(mutation_status)) print('\nnext gen') print_population(next_gen) print_matrix(next_gen, num_queens) #convergence check if convergence(next_gen): break population = next_gen
def nextGeneration(currentGen, eliteSize, mutationRate, distMatrix, popSize): popRanked = rankRoutes(currentGen, distMatrix) selectionResults = selection(popRanked, eliteSize) matingpool = matingPool(currentGen, selectionResults[:popSize]) children = breedPopulation(matingpool, eliteSize) nextGeneration = mutatePopulation(children, mutationRate, eliteSize) return nextGeneration
def __init__(self, f, x0, ranges=[], fmt='f', fitness=Fitness, selection=RouletteWheel, crossover=TwoPoint, mutation=BitToBit, elitist=True): ''' Initializes the population and the algorithm. On the initialization of the population, a lot of parameters can be set. Those will deeply affect the results. The parameters are: :Parameters: f A multivariable function to be evaluated. The nature of the parameters in the objective function will depend of the way you want the genetic algorithm to process. It can be a standard function that receives a one-dimensional array of values and computes the value of the function. In this case, the values will be passed as a tuple, instead of an array. This is so that integer, floats and other types of values can be passed and processed. In this case, the values will depend of the format string (see below) If you don't supply a format, your objective function will receive a ``Chromosome`` instance, and it is the responsability of the function to decode the array of bits in any way. Notice that, while it is more flexible, it is certainly more difficult to deal with. Your function should process the bits and compute the return value which, in any case, should be a scalar. Please, note that genetic algorithms maximize functions, so project your objective function accordingly. If you want to minimize a function, return its negated value. x0 A population of first estimates. This is a list, array or tuple of one-dimension arrays, each one corresponding to an estimate of the position of the minimum. The population size of the algorithm will be the same as the number of estimates in this list. Each component of the vectors in this list are one of the variables in the function to be optimized. ranges Since messing with the bits can change substantially the values obtained can diverge a lot from the maximum point. To avoid this, you can specify a range for each of the variables. ``range`` defaults to ``[ ]``, this means that no range checkin will be done. If given, then every variable will be checked. There are two ways to specify the ranges. It might be a tuple of two values, ``(x0, x1)``, where ``x0`` is the start of the interval, and ``x1`` its end. Obviously, ``x0`` should be smaller than ``x1``. If ``range`` is given in this way, then this range will be used for every variable. It can be specified as a list of tuples with the same format as given above. In that case, the list must have one range for every variable specified in the format and the ranges must appear in the same order as there. That is, every variable must have a range associated to it. fmt A ``struct``-format string. The ``struct`` module is a standard Python module that packs and unpacks informations in bits. These are used to inform the algorithm what types of data are to be used. For example, if you are maximizing a function of three real variables, the format should be something like ``"fff"``. Any type supported by the ``struct`` module can be used. The GA will decode the bit array according to this format and send it as is to your fitness function -- your function *must* know what to do with them. Alternatively, the format can be an integer. In that case, the GA will not try to decode the bit sequence. Instead, the bits are passed without modification to the objective function, which must deal with them. Notice that, if this is used this way, the ``ranges`` property (see below) makes no sense, so it is set to ``None``. Also, no sanity checks will be performed. It defaults to `"f"`, that is, a single floating point variable. fitness A fitness method to be applied over the objective function. This parameter must be a ``Fitness`` instance or subclass. It will be applied over the objective function to compute the fitness of every individual in the population. Please, see the documentation on the ``Fitness`` class. selection This specifies the selection method. You can use one given in the ``selection`` sub-module, or you can implement your own. In any case, the ``selection`` parameter must be an instance of ``Selection`` or of a subclass. Please, see the documentation on the ``selection`` module for more information. Defaults to ``RouletteWheel``. If made ``None``, then selection will not be present in the GA. crossover This specifies the crossover method. You can use one given in the ``crossover`` sub-module, or you can implement your own. In any case, the ``crossover`` parameter must be an instance of ``Crossover`` or of a subclass. Please, see the documentation on the ``crossover`` module for more information. Defaults to ``TwoPoint``. If made ``None``, then crossover will not be present in the GA. mutation This specifies the mutation method. You can use one given in the ``mutation`` sub-module, or you can implement your own. In any case, the ``mutation`` parameter must be an instance of ``Mutation`` or of a subclass. Please, see the documentation on the ``mutation`` module for more information. Defaults to ``BitToBit``. If made ``None``, then mutation will not be present in the GA. elitist Defines if the population is elitist or not. An elitist population will never discard the fittest individual when a new generation is computed. Defaults to ``True``. ''' list.__init__(self, []) self.__fx = [] for x in x0: x = array(x).ravel() c = Chromosome(fmt) c.encode(tuple(x)) self.append(c) self.__fx.append(f(x)) self.__f = f self.__csize = self[0].size self.elitist = elitist '''If ``True``, then the population is elitist.''' if type(fmt) == int: self.ranges = None elif ranges is None: self.ranges = zip(amin(self, axis=0), amax(self, axis=1)) else: ranges = list(ranges) if len(ranges) == 1: self.ranges = array(ranges * len(x0[0])) else: self.ranges = array(ranges) '''Holds the ranges for every variable. Although it is a writable property, care should be taken in changing parameters before ending the convergence.''' # Sanitizes the first estimate. It is not expected that the values # received as first estimates are outside the ranges, but a check is # made anyway. If any estimate is outside the bounds, a new random # vector is choosen. if self.ranges is not None: self.sanity() # Verifies the validity of the fitness method try: issubclass(fitness, Fitness) fitness = fitness() except TypeError: pass if not isinstance(fitness, Fitness): raise TypeError, 'not a valid fitness function' else: self.__fit = fitness self.__fitness = self.__fit(self.__fx) # Verifies the validity of the selection method try: issubclass(selection, Selection) selection = selection() except TypeError: pass if not isinstance(selection, Selection): raise TypeError, 'not a valid selection method' else: self.__select = selection # Verifies the validity of the crossover method try: issubclass(crossover, Crossover) crossover = crossover() except TypeError: pass if not isinstance(crossover, Crossover) and crossover is not None: raise TypeError, 'not a valid crossover method' else: self.__crossover = crossover # Verifies the validity of the mutation method try: issubclass(mutation, Mutation) mutation = mutation() except TypeError: pass if not isinstance(mutation, Mutation) and mutation is not None: raise TypeError, 'not a valid mutation method' else: self.__mutate = mutation
def __init__(self, fitness, fmt, ranges=[ ], size=50, selection=RouletteWheel, crossover=TwoPoint, mutation=BitToBit, elitist=True): ''' Initializes the population and the algorithm. On the initialization of the population, a lot of parameters can be set. Those will deeply affect the results. The parameters are: :Parameters: fitness A fitness function to serve as an objective function. In general, a GA is used for maximizing a function. This parameter can be a standard Python function or a ``Fitness`` instance. In the first case, the GA will convert the function in a ``Fitness`` instance and call it internally when needed. The function should receive a tuple or vector of data according to the given ``Chromosome`` format (see below) and return a numeric value. In the second case, you can use any of the fitness methods of the ``fitness`` sub-module, or create your own. If you want to use your own fitness method (for experimentation or simulation, for example), it must be an instance of a ``Fitness`` or of a subclass, or an exception will be raised. Please consult the documentation on the ``fitness`` sub-module. fmt A ``struct``-format string. The ``struct`` module is a standard Python module that packs and unpacks informations in bits. These are used to inform the algorithm what types of data are to be used. For example, if you are maximizing a function of three real variables, the format should be something like ``"fff"``. Any type supported by the ``struct`` module can be used. The GA will decode the bit array according to this format and send it as is to your fitness function -- your function *must* know what to do with them. Alternatively, the format can be an integer. In that case, the GA will not try to decode the bit sequence. Instead, the bits are passed without modification to the objective function, which must deal with them. Notice that, if this is used this way, the ``ranges`` property (see below) makes no sense, so it is set to ``None``. Also, no sanity checks will be performed. ranges Since messing with the bits can change substantially the values obtained can diverge a lot from the maximum point. To avoid this, you can specify a range for each of the variables. ``range`` defaults to ``[ ]``, this means that no range checkin will be done. If given, then every variable will be checked. There are two ways to specify the ranges. It might be a tuple of two values, ``(x0, x1)``, where ``x0`` is the start of the interval, and ``x1`` its end. Obviously, ``x0`` should be smaller than ``x1``. If ``range`` is given in this way, then this range will be used for every variable. If can be specified as a list of tuples with the same format as given above. In that case, the list must have one range for every variable specified in the format and the ranges must appear in the same order as there. That is, every variable must have a range associated to it. size This is the size of the population. It defaults to 50. selection This specifies the selection method. You can use one given in the ``selection`` sub-module, or you can implement your own. In any case, the ``selection`` parameter must be an instance of ``Selection`` or of a subclass. Please, see the documentation on the ``selection`` module for more information. Defaults to ``RouletteWheel``. If made ``None``, then selection will not be present in the GA. crossover This specifies the crossover method. You can use one given in the ``crossover`` sub-module, or you can implement your own. In any case, the ``crossover`` parameter must be an instance of ``Crossover`` or of a subclass. Please, see the documentation on the ``crossover`` module for more information. Defaults to ``TwoPoint``. If made ``None``, then crossover will not be present in the GA. mutation This specifies the mutation method. You can use one given in the ``mutation`` sub-module, or you can implement your own. In any case, the ``mutation`` parameter must be an instance of ``Mutation`` or of a subclass. Please, see the documentation on the ``mutation`` module for more information. Defaults to ``BitToBit``. If made ``None``, then mutation will not be present in the GA. elitist Defines if the population is elitist or not. An elitist population will never discard the fittest individual when a new generation is computed. Defaults to ``True``. ''' list.__init__(self, [ ]) for i in xrange(size): self.append(Chromosome(fmt)) if self[0].format is None: self.__nargs = 1 self.ranges = None else: self.__nargs = len(self[0].decode()) if not ranges: self.ranges = None elif len(ranges) == 1: self.ranges = array(ranges * self.__nargs) else: self.ranges = array(ranges) '''Holds the ranges for every variable. Although it is a writable property, care should be taken in changing parameters before ending the convergence.''' self.__csize = self[0].size self.elitist = elitist '''If ``True``, then the population is elitist.''' self.fitness = zeros((len(self),), dtype=float) '''Vector containing the computed fitness value for every individual.''' # Sanitizes the generated values randomly created for the chromosomes. if self.ranges is not None: self.sanity() # Verifies the validity of the fitness method if isinstance(fitness, types.FunctionType): fitness = Fitness(fitness) if not isinstance(fitness, Fitness): raise TypeError, 'not a valid fitness function' else: self.__fit = fitness self.__fit(self) # Verifies the validity of the selection method try: issubclass(selection, Selection) selection = selection() except TypeError: pass if not isinstance(selection, Selection): raise TypeError, 'not a valid selection method' else: self.__select = selection # Verifies the validity of the crossover method try: issubclass(crossover, Crossover) crossover = crossover() except TypeError: pass if not isinstance(crossover, Crossover) and crossover is not None: raise TypeError, 'not a valid crossover method' else: self.__crossover = crossover # Verifies the validity of the mutation method try: issubclass(mutation, Mutation) mutation = mutation() except TypeError: pass if not isinstance(mutation, Mutation) and mutation is not None: raise TypeError, 'not a valid mutation method' else: self.__mutate = mutation
def __init__(self, f, x0, ranges=[ ], fmt='f', fitness=Fitness, selection=RouletteWheel, crossover=TwoPoint, mutation=BitToBit, elitist=True): ''' Initializes the population and the algorithm. On the initialization of the population, a lot of parameters can be set. Those will deeply affect the results. The parameters are: :Parameters: f A multivariable function to be evaluated. The nature of the parameters in the objective function will depend of the way you want the genetic algorithm to process. It can be a standard function that receives a one-dimensional array of values and computes the value of the function. In this case, the values will be passed as a tuple, instead of an array. This is so that integer, floats and other types of values can be passed and processed. In this case, the values will depend of the format string (see below) If you don't supply a format, your objective function will receive a ``Chromosome`` instance, and it is the responsability of the function to decode the array of bits in any way. Notice that, while it is more flexible, it is certainly more difficult to deal with. Your function should process the bits and compute the return value which, in any case, should be a scalar. Please, note that genetic algorithms maximize functions, so project your objective function accordingly. If you want to minimize a function, return its negated value. x0 A population of first estimates. This is a list, array or tuple of one-dimension arrays, each one corresponding to an estimate of the position of the minimum. The population size of the algorithm will be the same as the number of estimates in this list. Each component of the vectors in this list are one of the variables in the function to be optimized. ranges Since messing with the bits can change substantially the values obtained can diverge a lot from the maximum point. To avoid this, you can specify a range for each of the variables. ``range`` defaults to ``[ ]``, this means that no range checkin will be done. If given, then every variable will be checked. There are two ways to specify the ranges. It might be a tuple of two values, ``(x0, x1)``, where ``x0`` is the start of the interval, and ``x1`` its end. Obviously, ``x0`` should be smaller than ``x1``. If ``range`` is given in this way, then this range will be used for every variable. It can be specified as a list of tuples with the same format as given above. In that case, the list must have one range for every variable specified in the format and the ranges must appear in the same order as there. That is, every variable must have a range associated to it. fmt A ``struct``-format string. The ``struct`` module is a standard Python module that packs and unpacks informations in bits. These are used to inform the algorithm what types of data are to be used. For example, if you are maximizing a function of three real variables, the format should be something like ``"fff"``. Any type supported by the ``struct`` module can be used. The GA will decode the bit array according to this format and send it as is to your fitness function -- your function *must* know what to do with them. Alternatively, the format can be an integer. In that case, the GA will not try to decode the bit sequence. Instead, the bits are passed without modification to the objective function, which must deal with them. Notice that, if this is used this way, the ``ranges`` property (see below) makes no sense, so it is set to ``None``. Also, no sanity checks will be performed. It defaults to `"f"`, that is, a single floating point variable. fitness A fitness method to be applied over the objective function. This parameter must be a ``Fitness`` instance or subclass. It will be applied over the objective function to compute the fitness of every individual in the population. Please, see the documentation on the ``Fitness`` class. selection This specifies the selection method. You can use one given in the ``selection`` sub-module, or you can implement your own. In any case, the ``selection`` parameter must be an instance of ``Selection`` or of a subclass. Please, see the documentation on the ``selection`` module for more information. Defaults to ``RouletteWheel``. If made ``None``, then selection will not be present in the GA. crossover This specifies the crossover method. You can use one given in the ``crossover`` sub-module, or you can implement your own. In any case, the ``crossover`` parameter must be an instance of ``Crossover`` or of a subclass. Please, see the documentation on the ``crossover`` module for more information. Defaults to ``TwoPoint``. If made ``None``, then crossover will not be present in the GA. mutation This specifies the mutation method. You can use one given in the ``mutation`` sub-module, or you can implement your own. In any case, the ``mutation`` parameter must be an instance of ``Mutation`` or of a subclass. Please, see the documentation on the ``mutation`` module for more information. Defaults to ``BitToBit``. If made ``None``, then mutation will not be present in the GA. elitist Defines if the population is elitist or not. An elitist population will never discard the fittest individual when a new generation is computed. Defaults to ``True``. ''' list.__init__(self, [ ]) self.__fx = [ ] for x in x0: x = array(x).ravel() c = Chromosome(fmt) c.encode(tuple(x)) self.append(c) self.__fx.append(f(x)) self.__f = f self.__csize = self[0].size self.elitist = elitist '''If ``True``, then the population is elitist.''' if type(fmt) == int: self.ranges = None elif ranges is None: self.ranges = zip(amin(self, axis=0), amax(self, axis=1)) else: ranges = list(ranges) if len(ranges) == 1: self.ranges = array(ranges * len(x0[0])) else: self.ranges = array(ranges) '''Holds the ranges for every variable. Although it is a writable property, care should be taken in changing parameters before ending the convergence.''' # Sanitizes the first estimate. It is not expected that the values # received as first estimates are outside the ranges, but a check is # made anyway. If any estimate is outside the bounds, a new random # vector is choosen. if self.ranges is not None: self.sanity() # Verifies the validity of the fitness method try: issubclass(fitness, Fitness) fitness = fitness() except TypeError: pass if not isinstance(fitness, Fitness): raise TypeError, 'not a valid fitness function' else: self.__fit = fitness self.__fitness = self.__fit(self.__fx) # Verifies the validity of the selection method try: issubclass(selection, Selection) selection = selection() except TypeError: pass if not isinstance(selection, Selection): raise TypeError, 'not a valid selection method' else: self.__select = selection # Verifies the validity of the crossover method try: issubclass(crossover, Crossover) crossover = crossover() except TypeError: pass if not isinstance(crossover, Crossover) and crossover is not None: raise TypeError, 'not a valid crossover method' else: self.__crossover = crossover # Verifies the validity of the mutation method try: issubclass(mutation, Mutation) mutation = mutation() except TypeError: pass if not isinstance(mutation, Mutation) and mutation is not None: raise TypeError, 'not a valid mutation method' else: self.__mutate = mutation
from selection import * from crossover import * import matplotlib.pyplot as plt g = grid(10) if len(sys.argv) == 2: pop = getPopulation(g, filename=sys.argv[1]) else: pop = getPopulation(g) numGen = 100 totalPopSize = 100 for i in range(numGen): selected = selection(pop, 80) children = breed(selected,g) pop = pop + children pop = list(set(pop)) assert len(pop) >= totalPopSize print("Population Size after breed = ", len(pop)) pop.sort(key=lambda x:x.aep, reverse=True) pop = pop[:totalPopSize] print("Generation ", i+1, "Max AEP = ", pop[0].aep, "Min AEP = ", pop[-1].aep) with open("population.txt", "w") as f: i = 1 for ind in pop: f.write("Wind Farm " + str(i) + "\t AEP = " + str(ind.aep) + "\n") for point in ind.locs: f.write(str(point.x) + "," + str(point.y) + "\n")