Last active
April 14, 2020 00:31
-
-
Save AlbericoD/447f04551593d349790ad98c4a12ddbf to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from gaft import GAEngine | |
from gaft.components import BinaryIndividual, Population | |
from gaft.operators import RouletteWheelSelection, UniformCrossover, FlipBitMutation | |
from gaft.plugin_interfaces.analysis import OnTheFlyAnalysis | |
from gaft.analysis.fitness_store import FitnessStore | |
from math import cos, sin | |
import matplotlib.pyplot as plt | |
import numpy as np | |
# Parametros para geração dos individuos | |
individuo_template = BinaryIndividual(ranges=[(0, 10)], eps=0.001) | |
# Parametros para inicializar a população | |
population = Population(indv_template=individuo_template, size=50) | |
# Parametros para inicializar a população | |
population.init() | |
# Parametros para execução dos operadores | |
selection = RouletteWheelSelection() | |
crossover = UniformCrossover(pc=0.5, pe=0.5) | |
mutation = FlipBitMutation(pm=0.1) | |
engine = GAEngine(population=population, | |
selection=selection, crossover=crossover, mutation=mutation, analysis=[FitnessStore]) | |
# função de aptidão | |
@engine.fitness_register | |
def fitness(indv): | |
x, = indv.solution | |
return x + 10*sin(5*x) + 7*cos(4*x) | |
@engine.analysis_register | |
class ConsoleOutPut(OnTheFlyAnalysis): | |
interval = 1 | |
def register_step(self, g, population, engine): | |
best_indv = population.best_indv(engine.fitness) | |
msg = 'Geração: {}, best fitness {:.3f}'.format(g, engine.fmax) | |
engine.logger.info(msg) | |
def finalize(population, engine): | |
best_indv = population.best_indv(engine.fitness) | |
x = best_indv.solution | |
y = engine.ori_fmax | |
msg = 'Solução ótima: ({},{})'.format(x, y) | |
engine.logger.info(msg) | |
def remove_characters(to_remove, line): | |
line.replace(to_remove, "") | |
return line | |
def plotAnalise(): | |
geracao = [] # lista de gerações | |
fitness = [] # lista de aptidão | |
best_fit_file = open("best_fit-1.py", "r") | |
for line in best_fit_file: | |
new_line = line.replace("[", "") | |
new_line = new_line.replace("(", "") | |
new_line = new_line.replace(")", "") | |
new_line = new_line.replace(",", "") | |
new_line = new_line.replace("]", "") | |
lista = new_line.split() | |
geracao.append(int(lista[0])) | |
fitness.append(float(lista[2])) | |
# print(geracao, fitness) | |
figure = plt.figure() | |
ax = figure.add_subplot(111) | |
ax.plot(geracao, fitness) | |
ax.set_xlabel('Gerações') | |
ax.set_ylabel('Fitness') | |
plt.title("Grafico daora") | |
plt.show() | |
plotAnalise() | |
# if '__main__' == __name__: | |
# engine.run(ng=100) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment