Пример #1
0
def main(size, popsize):
    """
    Make a horse happy by guiding it to a path on the chessboard in such a way that it
    moves to every single square once and only once. The little horsie can jump obviously
    only in the classic L shape (the chess’ horse move).

    Generate random permutations of chess board squares
    Find best individual
    Show statistics

    :param size: Size of the chess board
    :param popsize: Size of population
    """
    print("Running")
    tuples = []
    popl = []
    for i in range(size):
        for j in range(size):
            tuples.append((i, j))
    for i in range(popsize):
        random.shuffle(tuples)
        individ = Individual(size, deepcopy(tuples))
        popl.append(deepcopy(individ))
    finpop = population(popsize, popl, size)
    algo = Algorithm(size, finpop)

    evaluation, fitness, iter = algo.run()
    #statistics
    plt.plot(range(iter), fitness, label='BestFitness vs iteration')

    plt.xlabel('Iteration')
    plt.ylabel('BestFitness')
    plt.title("BestFitness evolution")
    plt.legend()
    plt.show()
Пример #2
0
def main():
    prb = problem()
    cit = prb.params
    n = cit[0]
    table = cit[1]
    t = cit[2]
    noIteratii = cit[3]
    dimPopulation = cit[4]
    pM = cit[5]

    pop = []
    cont = 0
    '''
    Create the population.
    '''
    while cont < dimPopulation:
        cont += 1
        indiv = []
        for i in range(0, n):
            indiv.append(0)
        leng = randint(1, n)
        cleng = leng
        while leng > 0:
            i = randint(0, n - 1)
            if indiv[i] == 0:
                indiv[i] = 1
                leng -= 1
        ind = individ(indiv, cleng, table, t)
        pop.append(ind)

    p = population(dimPopulation, pop)
    '''
    Running the algorithm
    '''
    alg = algorithm()
    for i in range(0, noIteratii):
        p = alg.iteration(table, p, t, pM)
    p.validate(n)
    '''
    Getting the best result.
    '''
    result = sorted(p.getPopulation(),
                    key=lambda x: x.getLength(),
                    reverse=False)
    print(len(result))
    for i in range(0, 1):
        print(result[i].getList(), result[i].getLength(),
              result[i].fitness(table, t))
    '''
    Plot.
    '''
    pl = [p.getLength() for p in result]
    plot(pl)
    return [result[0].fitness(table, t), result]
Пример #3
0
def rastrigins_minimization(population_size, max_generations,
                            k_tournament_participants, crossover_probability,
                            mutation_probability, n_genes_mutated):

    print(colored('\nInitial Population...\n', attrs=['bold']))

    initial_population = population(population_size)
    population_fitness = fitness(initial_population)

    avg = []
    best = []

    avg_fitness = avg_performance(population_fitness)
    best_fitness = best_performance(population_fitness)

    avg.append(avg_fitness)
    best.append(best_fitness)

    generations = 0

    while (generations <
           max_generations) and (minimum_found(population_fitness) is False):
        print(colored(f'\nGeneration {generations+1}...\n', attrs=['bold']))

        new_population = []

        for i in range(0, population_size):
            parents_selected = selection(population_fitness,
                                         k_tournament_participants)

            if crossover_probability >= cloning_probability():
                child = single_point_crossover(parents_selected)
            else:
                child = cloning_best_parent(parents_selected)

            if mutation_chance(mutation_probability):
                mutation(child, n_genes_mutated)

            new_population.append(child[:])

        population_fitness = fitness(new_population)
        generations += 1

        avg_fitness = avg_performance(population_fitness)
        best_fitness = best_performance(population_fitness)

        avg.append(avg_fitness)
        best.append(best_fitness)

    return minimum(population_fitness), generations, avg, best
Пример #4
0
    def calculateNewPopulation(self, mates, pm, pc):
        max_d1 = self.max_d1
        min_d1 = self.min_d1
        max_d2 = self.max_d2
        min_d2 = self.min_d2
        dx = self.dx

        # mates is a list of 2d vectors
        length = len(mates)

        # initialize the new 2d vectors' list
        new_design_vectors = [None] * length

        parent1_found = False
        parent2_found = False
        parent1_position = 0
        parent2_position = 0

        for k in range(len(mates)):
            prob_crossover_sucess = random.uniform(0, 1)
            # if the probability of crossover is achieved, select parent1 and parent2
            # and save them as well as their positions
            if prob_crossover_sucess <= pc:
                if not parent1_found:
                    parent1 = mates[k]
                    parent1_position = k
                    parent1_found = True
                elif not parent2_found:
                    parent2 = mates[k]
                    parent2_position = k
                    parent2_found = True
            new_design_vectors[k] = mates[k]

            # below is a series of concatenations and splits for the crossover to
            # be calculated, given that the two parents are found
            if parent1_found and parent2_found:
                bin_array1 = np.concatenate(
                    (parent1[0].value_bin, parent1[1].value_bin), axis=None)
                bin_array2 = np.concatenate(
                    (parent2[0].value_bin, parent2[1].value_bin), axis=None)

                offspring1, offspring2 = self.crossover(bin_array1, bin_array2)

                # divide the new binary arrays into two equally sized arrays
                bin_array_1_offspring_1, bin_array_2_offspring_1 = np.split(
                    offspring1, 2)
                bin_array_1_offspring_2, bin_array_2_offspring_2 = np.split(
                    offspring2, 2)

                # set the new design vectors in a list
                # offspring 1:
                dv1_offspring1 = designVec(min_d1, max_d1, dx)
                dv1_offspring1.setValue(bin_array_1_offspring_1, min_d1,
                                        max_d1, dx)

                dv2_offspring1 = designVec(min_d2, max_d2, dx)
                dv2_offspring1.setValue(bin_array_2_offspring_1, min_d2,
                                        max_d2, dx)

                # offspring 2:
                dv1_offspring2 = designVec(min_d1, max_d1, dx)
                dv1_offspring2.setValue(bin_array_1_offspring_2, min_d1,
                                        max_d1, dx)

                dv2_offspring2 = designVec(min_d2, max_d2, dx)
                dv2_offspring2.setValue(bin_array_2_offspring_2, min_d2,
                                        max_d2, dx)

                # create the new 2d vector for each offspring
                offspring2d_1 = (dv1_offspring1, dv2_offspring1)
                offspring2d_2 = (dv1_offspring2, dv2_offspring2)

                # pass the new offspring vector inside the new list
                new_design_vectors[parent1_position] = offspring2d_1
                new_design_vectors[parent2_position] = offspring2d_2

                # set the booleans back to false
                parent1_found = False
                parent2_found = False

        # calculate the mutation for each vector
        for k in range(len(new_design_vectors)):
            vector2d = new_design_vectors[k]

            bin_value = np.concatenate(
                (vector2d[0].value_bin, vector2d[1].value_bin), axis=None)
            bin_value = self.singlePointMutation(bin_value, pm)
            # split the result into 2 equal size arrays
            bin_value1, bin_value2 = np.split(bin_value, 2)

            # create 2 new design vectors with the new values
            dv1 = designVec(min_d1, max_d1, dx)
            dv1.setValue(bin_value1, min_d1, max_d1, dx)

            dv2 = designVec(min_d2, max_d2, dx)
            dv2.setValue(bin_value2, min_d2, max_d2, dx)

            # create a new 2d vector as a tuple
            vector2d = (dv1, dv2)

            # pass the new vactor to the list of the new design vectors
            new_design_vectors[k] = vector2d

        # create a new population from the new design vector list
        new_population = population(self.n, min_d1, max_d1, min_d2, max_d2, dx)
        new_population.setAllDesignVectors(new_design_vectors)
        return new_population
Пример #5
0
from Population import population
from Operations import operations

population_size = 100
x_min = -5
x_max = 5
y_min = -5
y_max = 5
Dx = 0.00001
max_iterations = 400
standard_deviation = 0.01
pc = 0.95
pm = 0.05

pop1 = population(population_size, x_min, x_max, y_min, y_max, Dx)
pop1.printPopulation()
op = operations(pop1)
print("---------------------POPULATION 1: ---------------------")
op.print()
i = 0
# check the standard deviation as a convergence criterion
convergence = op.check_convergence_for_all(standard_deviation)
while i < max_iterations and convergence == False:
    new_pop = op.calculateNewPopulation(op.mates, pm, pc)
    op = operations(new_pop)
    txt = "---------------------POPULATION {pop_no:d}: ---------------------".format(
        pop_no=i + 2)
    print(txt)
    op.print()
    i += 1
    convergence = op.check_convergence_for_all(standard_deviation)