I'm having a problem with pygad. My goal is to minimize the volume of a structure using the Ansys program. The Ansys code should read an input file, where I'm trying to write the values of the genes (project variables) for each evaluation of the fitness function, however, the code doesn't finish.
import pygad
import numpy as np
import subprocess
import time
volu = []
d = []
dmax = 25
gene_space = [range(1,100), range(1,100)]
print(gene_space)
def fitness_function(solution, k):
"""é aqui que está o problema. preciso arrumar uma forma de utilizar os genes gerados pelo algorítmo"""
pop = ga_instance.population
with open("C:\\Temp\\exemplo\\VariavelViga.txt", 'w') as f:
print('B =', '%0.0f' %pop[k, 0], file=f)
print('H =', '%0.0f' %pop[k, 1], file=f)
cmd = ["C:\Program Files\ANSYS Inc\\v150\ANSYS\\bin\winx64\ANSYS150.exe", '-b' , '-i' , 'C:\Temp\\exemplo\ExemploViga.txt' , '-o' , 'C:\Temp\exemplo\ExemploViga.out']
subprocess.call(cmd, shell=True)
objetivo = np.loadtxt("C:\\Temp\\exemplo\\ObjetivoViga.txt")
volu.append(objetivo[0])
d.append(objetivo[1])
if pop[k, 0] - pop[k, 1] < 0 and pop[k, 1] - 20*pop[k, 0] < 0 and d[k] - dmax <0:
fitness = 1/objetivo [0]
else:
fitness = -100
return fitness
ga_instance = pygad.GA(num_generations=15,
num_parents_mating=7,
fitness_func=fitness_function,
sol_per_pop=100,
num_genes=2,
init_range_low=1,
init_range_high=100,
parent_selection_type="sss",
keep_parents=5,
crossover_type="single_point",
mutation_type="random",
gene_space=gene_space,
gene_type=int,
mutation_percent_genes= 10)
sol, sol_fitness, sol_idx = ga_instance.best_solution()
print("Parameters of the best solution : {solution}".format(solution=sol))
ga_instance.plot_fitness()
However, after a while, I get the following error:
The plot_fitness() (i.e. plot_result()) method can only be called after completing at least 1 generation but (0) is completed.
I believe the problem is when I try to access the gene values for printing in my input file to Ansys (VariavelViga.txt).
After creating an instance of the
pygad.GA
class, you should call therun()
method to start the evolution.The
plot_fitness()
method can only be executed after therun()
method is executed.Thanks for using PyGAD!