# -*- coding: utf-8 -*- """ Created on Wed Nov 8 14:03:34 2023 @autor: Prof. Heitor S. Lopes ALGORITMO GENÉTICO SIMPLES PARA ENCONTRAR O MÍNIMO DA FUNÇÃO DE SCHWEFEL EM DUAS DIMENSÕES """ import math import numpy as np from numpy import * import random #DEFINIÇÃO DA FUNÇÃO DE SCHWEFEL BI-DIMENSIONAL def schwefel(x1,x2): return 418.9829*2 - x1 * sin( sqrt( abs( x1 )))-x2*sin(sqrt(abs(x2))) def schwefel_function(x, y): # Constants used in the Schwefel function a = 418.9829 dim = 2 # Calculate the absolute values of x and y abs_x = abs(x) abs_y = abs(y) # Calculate the function value term1 = -x * math.sin(math.sqrt(abs_x)) term2 = -y * math.sin(math.sqrt(abs_y)) result = a * dim + (term1 + term2) return result # PARÂMETROS DO ALGORITMO GENÉTICO population_size = 50 mutation_rate = 0.1 num_generations = 100 #INICIALIZA A POPULAÇÃO ALEATORIAMENTE COM DISTRIBUIÇÃO UNIFORME population = [(random.uniform(-500, 500), random.uniform(-500, 500)) for _ in range(population_size)] #PROGRAMA PRINCIPAL for generation in range(num_generations): #AVALIA O FITNESS DE CADA INDIVÍDUO DA POPULAÇÃO fitness_scores = [schwefel_function(x, y) for x, y in population] #SELECIONA OS 50% MELHORES DA POPULAÇÃO COM BASE NO FITNESS sorted_population = [x for _, x in sorted(zip(fitness_scores, population))] selected_population = sorted_population[:population_size // 2] print("\n Generation= ",generation, " Best individual:", selected_population[0], " Fitness:", fitness_scores[0]) #CRIA UMA NOVA POPULAÇÃO ATRAVÉS DA SELEÇÃO E OPERADORES GENÉTICOS new_population = [] while len(new_population) < population_size: parent1, parent2 = random.choices(selected_population, k=2) crossover_point = random.randint(1, 2) child = ( parent1[0] if random.random() < 0.5 else parent2[0], parent1[1] if random.random() < 0.5 else parent2[1] ) if random.random() < mutation_rate: child = (child[0] + random.uniform(-10, 10), child[1] + random.uniform(-10, 10)) new_population.append(child) population = new_population #BUSCA A MELHOR SOLUÇÃO NA ÚLTIMA POPULAÇÃO GERADA best_solution = min(population, key=lambda x: schwefel_function(x[0], x[1])) best_fitness = schwefel_function(best_solution[0], best_solution[1]) print(f"Best solution: x = {best_solution[0]}, y = {best_solution[1]}, Fitness = {best_fitness}")