Exemplo n.º 1
0
    def test_lecture_list(self):
        a = [3, 50, 60, 63, 11, 4, 5, 85, 70, 99, 61, 101, 62, 19, 22, 10, 30, 1, 100, 9, 82, 21, 40, 71, 20, 80, 81,
             79];
        b = copy.deepcopy(a)
        b.sort()

        i = 1
        while i < len(a) - 1:
            print('Iteration: ', i, 'Selection alg :', selection(a, i), 'Sorted list: ', b[i - 1])
            self.assertEqual(selection(a, i), b[i - 1])
            i = i + 1
Exemplo n.º 2
0
    def test_example_list(self):
        a = random.sample(range(1, 100), 90)

        b = copy.deepcopy(a)
        b.sort()

        i = 1
        while i < len(a) - 1:
            print('Iteration: ', i, 'Selection alg :', selection(a, i), 'Sorted list: ', b[i - 1])
            self.assertEqual(selection(a, i), b[i - 1])
            i = i + 1
Exemplo n.º 3
0
def simulate_EA(route, start_pop_size, dest_mat, mutate_prob, num_obj_iter, linear_coef=1.5, parents_div=2,
                ticket_cost=5, fuel_cost=2, start_cost=10):
    parents = create_first_pop(route, start_pop_size)
    while obj_fun.num_of_obj < num_obj_iter:
        counter = 0
        parents = selection(parents, dest_mat, route, linear_coef, parents_div,
                                  ticket_cost, fuel_cost, start_cost)
        global best_parent_stats
        best_parent_stats.append(obj_fun.obj_fun(selection_best_end(parents, dest_mat, route, ticket_cost, fuel_cost, start_cost)[0],
                                                 dest_mat, route, ticket_cost, fuel_cost, start_cost))

        children = []
        while counter < start_pop_size:
            operation_kind = np.random.rand()
            if operation_kind < mutate_prob:
                children.append(mutate1(parents[np.random.randint(len(parents))], route))
                counter += 1
            elif operation_kind >= mutate_prob and counter < start_pop_size-1:
                crossed_temp_sol = []
                crossed_temp_sol = crossover_oper(parents[np.random.randint(len(parents))], parents[np.random.randint(len(parents))], route)

                for sol in crossed_temp_sol:
                    children.append(sol)
                counter += 2
        parents = children
        best_parent_stats.append(
            obj_fun.obj_fun(selection_best_end(parents, dest_mat, route, ticket_cost, fuel_cost, start_cost)[0],
                            dest_mat, route, ticket_cost, fuel_cost, start_cost))
    return selection_best_end(parents, dest_mat, route, ticket_cost, fuel_cost, start_cost)
Exemplo n.º 4
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
Exemplo n.º 5
0
def findMoFa(pop, fit_value, chrom_length, max_value):
    """
    寻找最精英的父母(常用轮盘选择出父母基因)
    :param pop:种群
    :param fit_value:种群适应度
    :return: 父,母基因
    """
    # maxValue = max(fit_value)
    # faValue = min(fit_value)
    # moIndex = fit_value.index(maxValue)
    # mo = pop[moIndex]
    # fa = pop[fit_value.index(faValue)]
    # for i in range(len(fit_value)):
    #     if i != moIndex and fit_value[i] > faValue:
    #         faValue = fit_value[i]
    # fa = pop[fit_value.index(faValue)]
    mofa, fit = selection(pop, fit_value, 2, chrom_length, max_value)
    mo, fa = mofa
    return mo, fa
Exemplo n.º 6
0
def main():
    """"""

    imName = raw_input('Enter Image Name ')
    im = Image.open(imName)
    base = im.size

    subs, subsVAL = subdivide(im)

    subdivisions = []
    for sub in subs:
        subdivisions.append(average(sub))

    subSorted = list(subdivisions)
    # Alan Zucconi Lumonosity Color Sort
    # Sort subdivisions based on luminosity
    def lum(r, g, b):
        return math.sqrt((.241 * r) + (.691 * g) + (.068 * b))
    subSorted.sort(key=lambda rgb: lum(*rgb))

    colSelect = selection(subSorted)

    x, y = base
    a = x / 8
    b = y / 8

    nIM = Image.new('RGBA', (x + (2 * a), y + (b * 3)), color=(246, 240, 236, 0))
    nIM.paste(im, (a, b, a + x, b + y))

    draw = ImageDraw.Draw(nIM)

    x0 = a
    y0 = y + a
    y1 = y0 + a
    iter = x / len(colSelect)

    for k in range(len(colSelect)):
        draw.rectangle([x0, y0, x0 + iter, y1], colSelect[k])
        x0 += iter

    del draw
    nIM.show()
results = []  # 每代最优解集
fit_value = []  # 个体适应度
fit_mean = []  # 平均适应度

pop = geneEncoding(pop_size, chrom_length)  # 初始化二进制种群基因编码

for i in range(iterations):
    # print('NO. ', i + 1)
    fit_value = calobjValue(pop, chrom_length, max_value)  # 适应度计算
    # print('初始', fit_value)
    # fit_value = calfitValue(obj_value)  # 筛选淘汰
    best_indiviual, best_fit = best(pop, fit_value)  # 最优解集
    best_indiviual_ten = decoding(best_indiviual, chrom_length,
                                  max_value)  # 最优解集进制转换
    results.append([best_indiviual_ten, best_fit])
    pop, fit_value = selection(pop, fit_value, pop_size, chrom_length,
                               max_value)
    # print('选择', fit_value)
    pop, fit_value = crossover(pop, pc, fit_value, chrom_length, max_value)
    # print('交叉', fit_value)
    pop, fit_value = mutation(pop, pm, chrom_length, max_value)
    # print('变异', fit_value)

print(results[iterations - 1][1])

X = []
Y = []
for i in range(iterations):
    X.append(i)
    Y.append(results[i][1])

plt.plot(X, Y)
Exemplo n.º 8
0
Ld = float(Ud) * (-1)
start = time.time()
# Initial 
populationDataOriginal = np.zeros((int(population), int(dim)))
for eachpopulationData_colum in range(int(population)):
    for eachpopulationData_row in range(int(dim)):
        r = rand.random()
        populationDataOriginal[eachpopulationData_colum][eachpopulationData_row] = ((float(Ud) - Ld) * r) + Ld
populationData = populationDataOriginal.copy() # copy populationDataOriginal to populationData
best = 99999
for eachiteration in range(int(iteration)):
	# Mutation
	mutationData = mutation(populationData, float(F))

	# Crossover
	crossoverData = crossover(populationDataOriginal, mutationData, float(CR))

	# Selection
	selectionData = selection(populationDataOriginal, crossoverData, int(dim))			
	count = []
	for i in range(np.size(selectionData, 0)):
		count.append(fitness(selectionData[i][:], int(dim)))
		if count[i] < best:
			best = count[i]
	print(eachiteration, best)
	# reset
	populationDataOriginal = selectionData.copy()
	populationData = selectionData.copy()
end = time.time()
print(end-start)
Exemplo n.º 9
0
from Bubble import bubble
import random
from Merge import mergeSort
from QuickSort import quickSort
from Selection import selection
import matplotlib.pyplot as plt

x = input("Enter what sorting you want to visualize: ")
n = int(input("Enter size of array: "))
A = random.sample(range(1, n + 1), n)

if x == 'b':
    bubble(A)
elif x == 'm':
    mergeSort(A, 0, n - 1)
elif x == 'q':
    quickSort(A, 0, n - 1)
elif x == 's':
    selection(A)

plt.bar(list(range(0, len(A))), A)
plt.pause(0.1)
plt.close()
Exemplo n.º 10
0
from Selection import selection
from printArray import printArray

array = [45, 22, 43]

print("Before Sorting:", end = "")
printArray(array)

selection(array)

print(end = "\n")
print("After Sorting: ", end = "")
printArray(array)
Exemplo n.º 11
0
     (patch_size - shared_size) * (nb_etapes_ligne - 1) + patch_size, 2),
    dtype=np.uint8)

list_j = list(
    (patch_size - shared_size) * k for k in range(1, nb_etapes_ligne))
list_i = list((patch_size - shared_size) * k for k in range(nb_etapes_colonne))
""" On initialise output en haut à gauche """
output[:patch_size, :patch_size] = input[:patch_size, :patch_size]
origin_from_input[:patch_size, :patch_size] = np.array([[
    (i, j) for j in range(patch_size)
] for i in range(patch_size)])
""" Et on est parti ! """
for i in list_i:
    if i != 0:
        position = (i, 0)
        x, y = selection(input, output, origin_from_input, position,
                         patch_size, shared_size, M)
        coupe(input, output, origin_from_input, x, y, position, shared_size,
              patch_size)
    for j in list_j:
        position = (i, j)
        x, y = selection(input, output, origin_from_input, position,
                         patch_size, shared_size, M)
        coupe(input, output, origin_from_input, x, y, position, shared_size,
              patch_size)

image = np.uint8(output)

nouvelle_imgpil = Image.fromarray(image)
nouvelle_imgpil.save(sortie)