예제 #1
0
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
예제 #2
0
def evolution(ersteGeneration, ziel, abc, selecGewicht=[1.0, 1.0, 1.0], mutaAnteil=0.1):
    neueGen = ersteGeneration
    laufIndex = 0.0
    while True:
        tempSelec = selektion(neueGen, ziel, selecGewicht)
        tempGen = crossover(tempSelec, len(ersteGeneration))
        neueGen = mutation(tempGen, abc, mutaAnteil)
        laufIndex += 1
        print laufIndex
        if laufIndex > 1000000:
            print "Ueberlauf!!"
            break
        if neueGen[0] == ziel:
            return laufIndex
예제 #3
0
파일: run_p1.py 프로젝트: dWang0/CS4341
def run_p1(input_sring,TIME=30,GENERATION_SIZE=10,GENERATION_REMOVE=1):
    # GENERATION_SIZE = 4
    # GENERATION_REMOVE = 1
    # MAX_GENERATION = 30



    response = readcsv(input_sring)
    # print response
    goal = response.pop(0)
    # print goal,response

    f_gen = first_gen(response,GENERATION_SIZE, goal)
    # print f_gen

    best_pop = None
    future_gen = []
    future_gen.extend(f_gen)

    tstart = time()
    DIFF = time() - tstart
    NUM_GEN = 0
    while (DIFF) < TIME:
        NUM_GEN = NUM_GEN + 1
        future_gen = eval_pop(future_gen,goal)
        # print("Your future gen is: ",future_gen)

        num_picked = GENERATION_SIZE-GENERATION_REMOVE              ## Get the number of populations to take
        future_gen = pickPeople(future_gen, num_picked)             ## Set the genration to the 'num_picked' populations, with the removed pop replaced with the top pop
        # print ("Your You picked: ",future_gen)

        future_gen = crossover(future_gen, None)
        # print("Your crossover gen is: ",future_gen)

        future_gen = mutation(future_gen, response, goal, 0)
        # print ("Your mutated gen is: ",future_gen)

        future_gen = eval_pop(future_gen,goal)
        # print ("Your Re-Evaluated gen is: ",future_gen)

        best_pop,index = getBestPop(future_gen)
        if best_pop.getRatings() == 100:
            DIFF = time() - tstart
            break
        DIFF = time() - tstart

    print "You have finished, here is your population: "
    print best_pop
    print "It took "+str(NUM_GEN)+ " generations."
    print "And required "+str(DIFF)+" seconds."
예제 #4
0
    def mutation_production(self, networks, mutation_number, population_size):
        """
        Makes new individuals from individuals in the current population by mutating them
        Note: it does not affect current individuals but actually creates new ones

        :param networks:(list of NeuralNetwork) Neural nets to randomly become mutants
        :param mutation_number:(int) number of mutants needed
        :param population_size:(int) Size of whole neural nets population
        :return:(list of NeuralNetwork) New individuals (mutants)

        Todo: Use pseudo parallelization to speed up
        """
        mutants = []
        for i in range(mutation_number):
            mut = mutation(networks[randint(0, population_size - 1)], self.mutation_method)      # mutant making
            mutants.append(mut)                                               # append mutant
        return mutants
예제 #5
0
    def start(self):
        """
        Main function operating the Genetic Algorithm

        Steps at each generation:
        1- Parents selection
        2- Offsprings production
        3- Mutated individuals production
        4- Evaluation of whole population (old population + offsprings + mutated individuals)
        5- Additional mutations on random individuals (seems to improve learning)
        6- Keeping only population_size individuals, throwing bad performers

        Todo: Consider different sequences of steps, make it modular or user built
        """
        networks = self.networks
        population_size = self.population_size
        crossover_number = int(self.crossover_rate*self.population_size)   # calculate number of children to be produced
        mutation_number = int(self.mutation_rate*self.population_size)     # calculate number of mutation to be done

        gen = 0                                         # current generation
        for _ in range(self.generation_number):
            start_time = time.time()
            gen += 1

            parents = self.parent_selection(networks, crossover_number, population_size)       # parent selection
            children = self.children_production(crossover_number, parents)                     # children making
            mutations = self.mutation_production(networks, mutation_number, population_size)   # mutations making

            networks = networks + children + mutations                      # old population and new individuals
            self.evaluation(networks)                                       # evaluation of neural nets
            networks.sort(key=lambda Network: Network.score, reverse=True)  # ranking neural nets
            networks[0].save(name="gen_"+str(gen))                          # saving best of current generation

            for _ in range(int(0.2*len(networks))):              # More random mutations because it helps
                rand = randint(10, len(networks)-1)
                networks[rand] = mutation(networks[rand], self.mutation_method)

            networks = networks[:population_size]       # Keeping only best individuals
            end_time = time.time()
            iteration_time = end_time-start_time
            self.print_generation(networks, gen, iteration_time)
예제 #6
0
    a = random.randrange(1, max_val)
    #print("values of a and b are {} {}".format(a,b))
    a = binary(a, globals.no_of_labels)
    b = binary(b, globals.no_of_labels)
    #print(a,b)
    a = str(a)
    b = str(b)
    #print(a,b)
    s = crossover(globals.graph, a, b)
    s = str(encode(s))
    """print("encode s {}".format(s))
  print("devesh")
  print(s)
  print("mut starts")"""
    #print("after crossover {}".format(s))
    t = mutation(globals.graph, s)
    """print("after mutation {}".format(t))
  print("mut ends")"""
    x = fitness(t)
    s2 = t
    if len(solution) > len(s2):
        solution = s2
        fitness_val = len(s2)
        b = s2
    b = s2

    b = encode(b)
    #print("b is {}".format(b))
    b = bin_to_dec(b)
    a = bin_to_dec(a)
    print("values after {} iteration is {} and {} with fitness= {}".format(
예제 #7
0
파일: run_p2.py 프로젝트: dWang0/CS4341
def run_p2(input_sring,TIME=20,GENERATION_SIZE=10,GENERATION_REMOVE=1):
    # GENERATION_SIZE = 4
    # GENERATION_REMOVE = 1
    # MAX_GENERATION = 30



    response = readcsv_float(input_sring)
    # print response
    goal = response.pop(0)
    # print goal,response

    f_gen = poptwofg(response,GENERATION_SIZE)
    # print f_gen

    best_pop = None
    future_gen = []
    future_gen.extend(f_gen)

    tstart = time()
    NUM_GEN = 0
    DIFF = time()-tstart
    while (DIFF) < TIME:
        NUM_GEN = NUM_GEN + 1
        future_gen = eval_pop(future_gen,goal,pop_eval_two)
        # print"Your future gen is: "
        # for pop in future_gen:
        #     print pop

        num_picked = GENERATION_SIZE-GENERATION_REMOVE              ## Get the number of populations to take
        future_gen = pickPeople(future_gen, num_picked)             ## Set the genration to the 'num_picked' populations, with the removed pop replaced with the top pop
        # print "Your You picked: "
        # for pop in future_gen:
        #     print pop


        future_gen = crosspop2(future_gen, set(response))
        # print"Your crossover gen is: "
        # for pop in future_gen:
        #     print pop

        future_gen = mutation(future_gen,response,goal,None)
        # print"Your fixed crossover gen is: "
        # for pop in future_gen:
        #     print pop

        future_gen = eval_pop(future_gen,goal,pop_eval_two)
        # print"Your eval fixed crossover gen is: "
        # for pop in future_gen:
        #     print pop



        best_pop,index = getBestPop(future_gen)
        DIFF = time()-tstart

    print "You have finished, here is your population: "
    print best_pop
    best_pop.score()
    print "It took "+str(NUM_GEN)+ "generations."
    print "And it required "+str(DIFF)+" seconds"
from mutation import *
import random

test_arch = Arch.random_arch()
for i, n in enumerate(test_arch.arch):
    print(i)
    print(n)
    print('\n----\n')
print('------------------------')
mutations = [Mutation.hidenStateMutate, Mutation.opMutate]
mutation = random.choice(mutations)
mutation(test_arch)
print('after mutation')
print('--------------------------\n')
for i, n in enumerate(test_arch.arch):
    print(i)
    print(n)
    print('\n----\n')

# # model = Model(test_arch)
#
# fitness = train_and_eval(model)
# print(fitness)
예제 #9
0
    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
예제 #10
0
    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
예제 #11
0
    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
예제 #12
0
def nsga2_main(opt):
    #------------INITIALIZE------------------------------------------------
    opt["pop"] = lhsamp_model.lhsamp_model(opt["N"], opt)
    #LHS Sampling

    #------------EVALUATE--------------------------------------------------
    [opt["popObj"],
     opt["popCons"]] = evaluate_pop.evaluate_pop(opt, opt["pop"])
    opt["popCV"] = evaluateCV.evaluateCV(opt["popCons"])
    opt["archiveObj"] = opt["popObj"]
    #to save all objectives
    opt["archive"] = opt["pop"]
    opt["archiveCV"] = opt["popCV"]

    #-------------------PLOT INITIAL SOLUTIONS-----------------------------
    plot_population(opt, opt["popObj"])

    if os.path.isfile(opt["histfilename"]):
        os.remove(opt["histfilename"])

    # if exist(opt["histfilename"], 'file')==2:
    #     delete(opt["histfilename"]);

    #--------------- OPTIMIZATION -----------------------------------------
    funcEval = opt["N"]

    while funcEval < opt["totalFuncEval"]:  # Generation # 1 to

        M1 = np.tile(funcEval, opt["N"], 1)
        M2 = opt["pop"]
        M3 = opt["popObj"]
        M4 = (-1) * opt["popCV"]
        M = np.concatenate(M1, M2, M3, M4, axis=1)

        #dlmwrite(opt.histfilename, M, '-append', 'delimiter',' ','precision','%.10f');%history of run
        opt = mating_selection(opt)
        #--------Mating Parent Selection-------
        opt = crossover(opt)
        #-------------------Crossover-----------------
        opt = mutation(opt)
        #--------------------Mutation------------------

        #---------------EVALUATION-----------------------------------------
        [opt["popChildObj"],
         opt["popChildCons"]] = evaluate_pop(opt, opt["popChild"])
        opt["popCV"] = evaluateCV(opt["popCons"])
        opt["popChildCV"] = evaluateCV(opt["popChildCons"])

        #---------------MERGE PARENT AND CHILDREN--------------------------
        opt["totalpopObj"] = np.concatenate(opt["popChildObj"], opt["popObj"])
        opt.totalpop = np.concatenate(opt["popChild"], opt["pop"])
        opt.totalpopCV = np.concatenate(opt["popChildCV"], opt["popCV"])
        opt.totalpopCons = np.concatenate(opt["popChildCons"], opt["popCons"])

        #-----------------SURVIVAL SELECTION-------------------------------
        opt = survival_selection(opt)
        funcEval = funcEval + opt.N

        opt.popCV = evaluateCV(opt["popCons"])
        opt.archive = np.concatenate(opt["archive"], opt["pop"])
        opt.archiveObj = np.concatenate(opt["archiveObj"], opt["popObj"])
        opt.archiveCV = np.concatenate(opt["archiveCV"], opt["popCV"])

        #-------------------PLOT NEW SOLUTIONS-----------------------------

        if funcEval % 1000 == 0:
            print(funcEval)
            plot_population(opt, opt["popObj"])
        #[opt.FeasibleIndex, opt.ParetoIndex] = calculate_feasible_paretofront(opt, opt.archive, opt.archiveObj, opt.archiveCV);

    M1 = np.concatenate(funcEval, opt["N"], 1, axis=1)
    M2 = opt.pop
    M3 = opt.popObj
    M4 = (-1) * opt.popCV
    M = np.concatenate(M1, M2, M3, M4, axis=1)

    with open('opt["histfilename"]', 'w') as f:
        f.write(M)
    # dlmwrite(opt.histfilename, M, '-append', 'delimiter',' ','precision','%.10f');#history of run

    return opt