Advertisement
Guest User

ga

a guest
Jun 21st, 2022
28
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.91 KB | None | 0 0
  1. import random
  2.  
  3.  
  4. def generate_population(size, x_boundaries, y_boundaries):
  5.     lower_x_boundary, upper_x_boundary = x_boundaries
  6.     lower_y_boundary, upper_y_boundary = y_boundaries
  7.  
  8.     population = []
  9.     for i in range(size):
  10.         individual = {
  11.             'x': random.uniform(lower_x_boundary, upper_x_boundary),
  12.             'y': random.uniform(lower_y_boundary, upper_y_boundary),
  13.         }
  14.         population.append(individual)
  15.  
  16.     return population
  17.  
  18. def store_fitness(individual):
  19.     x = [dct['x'] for dct in individual]
  20.     y = [dct1['y'] for dct1 in individual]
  21.    
  22.     i = 0
  23.     total = [0]*10
  24.     for i in range(9):
  25.         total[i] = abs((-(100*(x[i]*x[i] - y[i])*(x[i]*x[i] - y[i]) + (1 - x[i])*(1-x[i]))))
  26.     return total
  27.  
  28. def fitness(individual):
  29.     x = individual['x']
  30.     y = individual['y']
  31.    
  32.     return abs((-(100 * (x * x - y) * (x * x - y) + (1 - x) * (1 - x))))
  33.  
  34. def sort_population_by_fitness(population):
  35.     return sorted(population, key=fitness)
  36.  
  37. def crossover(choice_a, choice_b):
  38.     xa = choice_a['x']
  39.     ya = choice_a['y']
  40.    
  41.     xb = choice_b['x']
  42.     yb = choice_b['y']
  43.    
  44.    
  45.     return {'x': (xa + xb) / 2, 'y': ( ya + yb) / 2}
  46.  
  47. def mutate(new_individual):
  48.     x = new_individual['x']
  49.     y = new_individual['y']
  50.  
  51.     #flags para estouro
  52.     flagx = 1
  53.     flagy = 1
  54.    
  55.     #realiza a mutação
  56.     new_x = x * (1 + random.uniform(-0.06, 0.06))
  57.     new_y = y * ( 1 + random.uniform(-0.06, 0.06))
  58.    
  59.     #Verifica se teve estouro X
  60.     while flagx == 1:
  61.         if (new_x > 2.0) or (new_x < -2.0):
  62.             new_x = x*(1+random.uniform(-0.06, 0.06))
  63.             flagx = 1
  64.         else:
  65.             flagx = 0
  66.     #Verifica se teve estouro Y
  67.     while flagy == 1:
  68.         if(new_y > 2) or (new_y < -2):
  69.             new_x = y * (1 + random.uniform(-0.06, 0.06))
  70.             flagy = 1
  71.         else:
  72.             flagy = 0
  73.    
  74.     return {'x': new_x, 'y': new_y}
  75.  
  76.  
  77. def choice_by_roulette(sorted_population, fitness_sum):
  78.     #sorteia valor
  79.     drawn = random.uniform(0, 1)
  80.     #valor acumalado dos sorteios
  81.     accumulated = 0
  82.    
  83.     for individual in sorted_population:
  84.         #fitnessx recebe o fitness do individuo
  85.         fitnessX = fitness(individual)
  86.         #calculo da probabilidade
  87.         probability = fitnessX / fitness_sum
  88.         #acumula o valor
  89.         accumulated += probability
  90.        
  91.         #reliza o sorteio case valor esteja no abaixo do acumulado
  92.         if drawn <= accumulated:
  93.             return individual
  94.        
  95. def make_next_gen(population):
  96.     next_gen = []
  97.     #ordenar a população
  98.     sum_fitness = sum(fitness(individual)for individual in population)
  99.  
  100.     choice_1 = choice_by_roulette(population, sum_fitness)
  101.     choice_2 = choice_by_roulette(population, sum_fitness)
  102.    
  103.     #verificação se as primeiras seleções sao iguais
  104.     if choice_1 == choice_2:
  105.         while choice_2 == choice_2:
  106.             choice_2 = choice_by_roulette(population, sum_fitness)
  107.    
  108.     #Armazena a primeira escolha
  109.     old_choice_1 = choice_1
  110.     old_choice_2 = choice_2
  111.    
  112.     #realiza o primeiro cruzamento
  113.     new_individual = crossover(choice_1, choice_2)
  114.     #4 porcento de chance de mutação
  115.     drawn = random.randint(1,10)
  116.     if (drawn == 1) or (drawn == 2) or (drawn == 3) or (drawn == 4):
  117.         new_individual = mutate(new_individual)
  118.     #adiciona o primeiro individuo a lista dos novos individuos
  119.     next_gen.append(new_individual)
  120.    
  121.     for i in range(8):
  122.         choice_1 = choice_by_roulette(population, sum_fitness)
  123.         #impedir que realize a mesma selução
  124.         while(choice_1 == old_choice_1) or (choice_1 == old_choice_2):
  125.             choice_1 = choice_by_roulette(population, sum_fitness)
  126.        
  127.         choice_2 = choice_by_roulette(population, sum_fitness)
  128.         #impedir que realize a mesma seleção
  129.         while((choice_2 == old_choice_1) or (choice_2 == old_choice_2) or (choice_2 == choice_1)):
  130.             choice_2 = choice_by_roulette(population, sum_fitness)
  131.        
  132.         #atualiza as escolhas anteriores
  133.         old_choice_1 = choice_1
  134.         old_choice_2 = choice_2
  135.        
  136.         #realiza o cruzamento
  137.         new_individual = crossover(choice_1, choice_2)
  138.         #4 porcento de chance de mutação
  139.         drawn = random.randint(1,10)
  140.         if (drawn == 1) or (drawn == 2) or (drawn == 3) or (drawn == 4):
  141.             new_individual = mutate(new_individual)
  142.          #adiciona o primeiro individuo a lista dos novos individuos    
  143.         next_gen.append(new_individual)
  144.    
  145.     return next_gen
  146.        
  147.    
  148.        
  149. #Primeiro gera a população
  150. population = generate_population(size=10, x_boundaries=(-2, 2), y_boundaries=(-2, 2))
  151.  
  152. #Armazena o fitness da população em ordem crescente
  153. #idx 0 == menor fitness = melhor
  154. fitness_pop = store_fitness(population)
  155. #ordena os fitness
  156. fitness_pop = sorted(fitness_pop)
  157. #ordena a população pelo fitness
  158. population = sort_population_by_fitness(population)
  159.  
  160. #Para o eletismo, armazena o melhor individuo e o melhor fitness do individuo
  161. best_individual = population[0]
  162. best_fitness = fitness_pop[0]
  163.  
  164. population = make_next_gen(population)
  165.  
  166. generations = 10
  167. i = 0
  168.  
  169. while i != generations:
  170.     for individual in population:
  171.         print(individual, fitness(individual))
  172.    
  173.     #recebe a nova população
  174.     population = make_next_gen(population)
  175.     #ordena população pra garantir ne vai que
  176.     population = sort_population_by_fitness(population)
  177.     #recebe o fitnes de toda a população
  178.     fitness_pop = store_fitness(population)
  179.     #ordena os fitness ja ordenados pra garantir vai que
  180.     fitness_pop = sorted(fitness_pop)
  181.     #compara melhor individuo antigo com pior individuo novo
  182.    
  183.     new_worst_individual = population[9]
  184.     new_worst_fitness = fitness_pop[9]
  185.     if(best_fitness > new_worst_fitness):
  186.         population[9] = best_fitness
  187.    
  188.     i += 1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement