def main(): MIN=0 MAX=0 gaParam={'popSize':500,'nrGen':200} propParam = citire2("file.gml") for i in range(propParam['n']): print(propParam['matrix'][i]) print(propParam['degrees']) print(propParam['edges']) propParam['function']=modularity ga = GA(gaParam,propParam) ga.initialisation() ga.evaluation() best = ga.bestChromosome() fitnees = best.fitness for i in range(gaParam['nrGen']): bestSolution = ga.bestChromosome() #print(bestSolution) if bestSolution.fitness > fitnees: best = bestSolution fitnees = best.fitness # if i%2 == 0: # ga.oneGeneration() # else: print(bestSolution.fitness) ga.oneGenerationElitism() dict=[[]] x=best.repres v=[0]*propParam['n'] k=1 for i in range(propParam['n']): if v[x[i]]==0: v[x[i]]=k k+=1 ii=i+1 dict.append([ii]) else: b=v[x[i]] ii=i+1 dict[b].append(ii) print(k-1) for i in range(k): print(dict[i])
def run(): while True: print("1. RUN: \n") print("0. Exit\n") cmd = input() if cmd == "1": print("fisierul: \n") filename = input() if (filename != ""): print("marimea populatiei = \n") populationSize = int(input()) print("numarul de generatii = \n") numGenerations = int(input()) graph = readNet3(filename) ga = GA(populationSize, graph) ga.initialization() counterr = 0 gen = counterr + 1 best = ga.bestChromosome() counterr +=1 print("generation " + str(gen) + " " + str(best.repres) + " fitness " + str(best.fitness)) while (counterr < numGenerations): ga.oneGeneration() best = ga.bestChromosome() gen = counterr + 1 print("generation " + str(gen) + " " + str(best.repres) + " fitness "+str(best.fitness)) counterr += 1 else: break
def main(): filename = FILENAMES['berlin'] network = None if filename == FILENAMES['berlin']: network = readBerlin('./resources/' + filename) else: network = readFile('./resources/' + filename) gaParam = { 'popSize': 10, 'noGen': 1000, 'network': network } problParam = { 'function': pathFunction, 'noNodes': network['noNodes'] } ga = GA(gaParam, problParam) ga.initialisation() ga.evaluation() bestFitness = [] for i in range(gaParam['noGen'] - 1): ga.oneGenerationElitism() bestFitness.append(ga.bestChromosome().fitness) bestChromosome = ga.bestChromosome() print(bestChromosome) plt.plot(bestFitness) plt.ylabel('Best fitness') plt.xlabel('Generation') plt.show()
def main(): #fileName = 'dolphins.gml' #fileName = 'football.gml' fileName = 'karate.gml' #fileName = 'krebs.gml' #fileName = 'ex1.gml' #fileName = 'ex2.gml' param, problParam = initParams(fileName) ga = GA(param, problParam) ga.initialisation() ga.evaluation() ga.oneGeneration() globalBest = ga.bestChromosome() generation = 0 while not generation > param['noGen']: ga.oneGeneration() bestChromosome = ga.bestChromosome() if bestChromosome.fitness > globalBest.fitness: globalBest = bestChromosome printData(generation, bestChromosome) generation += 1 print('\nGlobal Best') print(globalBest) print('Fitness: ' + str(globalBest.fitness))
def desen(ret): seed(1) # plot the function to be optimised noDim = 1 xref = [[generateNewValue(0, ret['noNodes'] - 1) for _ in range(noDim)] for _ in range(0, 1000)] xref.sort() yref = [fcEval(xi) for xi in xref] plt.ion() plt.plot(xref, yref, 'b-') plt.xlabel('x values') plt.ylabel('y = f(x) values') plt.show() # initialise de GA parameters # gaParam = {'popSize' : 10, 'noGen' : 3, 'pc' : 0.8, 'pm' : 0.1} # problem parameters # problParam = {'min' : MIN, 'max' : MAX, 'function' : fcEval, 'noDim' : noDim, 'noBits' : 8} # store the best/average solution of each iteration (for a final plot used to anlyse the GA's convergence) allBestFitnesses = [] allAvgFitnesses = [] generations = [] ga = GA(gaParam, problParam) ga.initialisation() ga.evaluation() for g in range(gaParam['noGen']): #plotting preparation allPotentialSolutionsX = [c.repres for c in ga.population] allPotentialSolutionsY = [c.fitness for c in ga.population] bestSolX = ga.bestChromosome().repres bestSolY = ga.bestChromosome().fitness allBestFitnesses.append(bestSolY) allAvgFitnesses.append( sum(allPotentialSolutionsY) / len(allPotentialSolutionsY)) generations.append(g) plotAFunction(xref, yref, allPotentialSolutionsX, allPotentialSolutionsY, bestSolX, [bestSolY], 'generation: ' + str(g)) #logic alg ga.oneGeneration() # ga.oneGenerationElitism() # ga.oneGenerationSteadyState() bestChromo = ga.bestChromosome() print('Best solution in generation ' + str(g) + ' is: x = ' + str(bestChromo.repres) + ' f(x) = ' + str(bestChromo.fitness)) plt.ioff() best, = plt.plot(generations, allBestFitnesses, 'ro', label='best') mean, = plt.plot(generations, allAvgFitnesses, 'bo', label='mean') plt.legend([best, (best, mean)], ['Best', 'Mean']) plt.show()
def runGenerations(probParam=None, generationParam=None): #star genetic algorithm ga = GA(generationParam, probParam) ga.initialisation() ga.evaluation() #path x = [] y = [] #run generations g = -1 while (g < generationParam['noGen']): g += 1 y.append(g) #nr of gen x.append(ga.bestChromosome().fitness) #ga.oneGenerationRand() ga.oneGenerationElitism() #cea mai buna #ga.oneGenerationSteadyState() #slab #print best fitness of current generation print("Generatia curenta: " + str(g) + "; " + "Best fitness: " + str( ga.bestChromosome().fitness)) #str(ga.bestChromosome().fitness)) #print other parameters cost = int(ga.bestChromosome().fitness) path = ga.bestChromosome().repres strpath = '' path.insert(0, 0) for i in range(len(path)): strpath += str(path[i] + 1) if i != len(path) - 1: strpath += ',' print("Lungimea traseului: " + str(len(path))) print("Traseu: " + strpath) print("Cost: " + str(cost)) # import matplotlib.pyplot as plt # x axs values # x = [1, 2, 3] # corresponding y axis values # y = [2, 4, 1] # plotting the points plt.plot(x, y) # naming the x axis plt.xlabel('fitness') # naming the y axis plt.ylabel('nr generatiei') # giving a title to my graph plt.title('My first graph!') # function to show the plot plt.show()
def main(): ga = GA(gaParam, problParam) ga.initialisation() ga.evaluation() ga.oneGeneration() bestChromo=ga.bestChromosome() print('Solutia cea mai buna este: ' + str(afisare(bestChromo.repres)) + ' cost = ' + str(bestChromo.fitness))
def main(): gaParam, problParam = initParams(FILENAMES['dolphins']) ga = GA(gaParam, problParam) ga.initialisation() ga.evaluation() currentGeneration = 0 bestFitnessArr = [] while currentGeneration <= gaParam['noGen']: ga.oneGeneration() bestChromosome = ga.bestChromosome() print('=== [Gen ' + str(currentGeneration) + '] ===') print(bestChromosome) print('Fitness: ' + str(bestChromosome.fitness)) print('Number of communities: ' + str(getNumberOfCommunities(problParam, bestChromosome.repres))) print('') bestFitnessArr.append(bestChromosome.fitness) currentGeneration += 1 plt.plot(bestFitnessArr) plt.ylabel('Best fitness') plt.xlabel('Generation') plt.show()
def main(): #graph = readGraph("inputFiles/easy_01_4.txt") #print(graph) #gaParam = {'popSize': 100, 'noGen': 100, 'pc': 0.8, 'pm': 0.1} #problParam = {'noNodes': len(graph),'graph':graph, 'function': fitness_func} data = readFromFile("inputFiles/hard_02_52.txt") gaParam = {'popSize': 100, 'noGen': 5000} ga = GA(gaParam, data) ga.initialisation() ga.evaluation() bestChromosomes = [] bestFitness = 99999999 bestChromosomeRepres = None for g in range(gaParam['noGen']): ga.oneGenerationElitism() bestChromo = ga.bestChromosome() if (bestChromo.fitness < bestFitness): bestChromosomeRepres = bestChromo.repres bestFitness = bestChromo.fitness bestChromosomes.append(bestChromo) print('Generation ' + str(g) + '/\n best chromosome: ' + str(bestChromo.repres) + '/\n -> fitness: ' + str(bestChromo.fitness)) print('\n ---------\nBest overall solution: ' + str(bestChromosomeRepres) + ' \n fitness = ' + str(bestFitness))
def main(): reader = Reader() reader._init_("mediumF.txt") net = reader.readNetwork() gaParam = {"popSize": 500, "noGen": 500} problParam = { 'function': roadValue, 'noNodes': net['noNodes'], 'net': net['mat'] } ga = GA(gaParam, problParam) ga.initialisation() ga.evaluation() stop = False g = -1 solutions = [] while not stop and g < gaParam['noGen']: g += 1 ga.oneGenerationElitism() bestChromo = ga.bestChromosome() solutions.append(bestChromo) print('Best solution in generation ' + str(g) + ' is: x = ' + str(bestChromo.repres) + ' f(x) = ' + str(bestChromo.fitness)) heapify(solutions) print(str(solutions[0]))
def main(): graph = read_graph("exemplu.txt") print(graph) # initialise de GA parameters gaParam = {'popSize': 5, 'noGen': 3000, 'pc': 0.8, 'pm': 0.1} # problem parameters problParam = {'noNodes': len(graph), 'graph': graph, 'function': evalPath} ga = GA(gaParam, problParam) ga.initialisation() ga.evaluation() bestChromosomes = [] bestFitness = [] for g in range(gaParam['noGen']): # logic alg #ga.oneGeneration() ga.oneGenerationElitism() #ga.oneGenerationSteadyState() bestChromo = ga.bestChromosome() bestChromosomes.append(bestChromo) bestFitness.append(bestChromo.fitness) print('Best solution in generation ' + str(g) + ' is: f(x) = ' + str(1 / bestChromo.fitness)) x = [] y = [] for i in range(len(bestFitness)): x.append(i) y.append(bestFitness[i]) plt.plot(x, y) plt.show()
def main(): crtDir = os.getcwd() filePath = os.path.join(crtDir, 'hardE.txt') #network = readNetwork1(filePath) network = readNetwork2(filePath) gaParam = {'popSize': 100, 'noGen': 100} problParam = {'network': network, 'function': routeFitness} ga = GA(gaParam, problParam) ga.initialisation() ga.evaluation() best = [] for g in range(gaParam['noGen']): #ga.oneGenerationElitism() ga.oneGenerationSteadyState() bestChromo = ga.bestChromosome() print('Generatia de platina ' + str(g) + ' este: x = ' + str(bestChromo.repres) + '\nf(x) = ' + str(bestChromo.fitness) + '\nDistanta = ' + str(bestChromo.distance)) best.append(bestChromo.distance) plt.plot(best) plt.ylabel('Lungime minima') plt.xlabel('Generatie') plt.show()
def main(): global fileName_input, N fileName_input = "fricker.txt" fileName_output = fileName_input[:-4] + "_solutie.txt" N = None N, cityList=read() # N, cityList=readCiudat() print(cityList) popSize = 100 noGen = 1000 mutationRate = 0.01 eliteSize = 20 ga = GA(popSize, eliteSize, cityList, mutationRate) ga.initialise() ga.evaluate() maximFitness = -1 f = open(fileName_output, 'w') global currentChromosome for g in range(noGen): currentChromosome = ga.bestChromosome() if currentChromosome.fitness > maximFitness: maximFitness = currentChromosome.fitness # bestChromo = currentChromosome f.write('Best solution in generation ' + str(g) + ' is: x = ' + str(currentChromosome.repres) + ' f(x) = ' + str(currentChromosome.fitness)) f.write('\n') ga.oneGeneration() f.write(str(N)) f.write('\n') index = 0 for i in range(0, len(currentChromosome.repres)): if currentChromosome.repres[i] == 0: index = i i = index f.write(str(currentChromosome.repres[i] + 1) + ' ') i += 1 while i != index: if i == len(currentChromosome.repres): i = 0 else: f.write(str(currentChromosome.repres[i] + 1) + ' ') i += 1 f.write('\n') route = currentChromosome.repres distance = 0 for i in range(0, len(route)): fromCity = route[i] toCity = None if i + 1 < len(route): toCity = route[i + 1] else: toCity = route[0] distance += cityList[fromCity][toCity] f.write(str(distance)) f.write('\n') f.close()
def run_test(file_name, generation_type, pop_size, no_gen): G = readFile("inputFiles/" + file_name + ".txt") params = { 'noNodes': G.number_of_nodes(), 'mat': G, 'degrees': [x[1] for x in G.degree()], 'noEdges': G.number_of_edges(), 'popSize': pop_size, 'function': modularity, 'noGen': no_gen, 'chromosome': Chromosome, 'maxCommunities': G.number_of_nodes() } ga = GA(params) ga.initialisation() ga.evaluation() best_chromosome = ga.bestChromosome() last_fitness = 0 same_fitness = 1 i = 0 while True: best_chromosome = ga.bestChromosome() if last_fitness == best_chromosome.fitness: if same_fitness == 500: break else: same_fitness += 1 else: same_fitness = 1 last_fitness = best_chromosome.fitness print('Best chromosome of generation:' + str(i + 1) + ' has a fitness of ' + str(best_chromosome.fitness)) if generation_type == 'normal': ga.oneGeneration() elif generation_type == 'elitism': ga.oneGenerationElitism() elif generation_type == 'steady': ga.oneGenerationSteadyState() i += 1 writeSolutionToFile(file_name, best_chromosome)
def main(*init): to_list = [] ga = GA(gaParam, problParam) ga.initialisation() best = ga.bestChromosome() best_all = [] for i in range(gaParam["noGen"]): ga.oneGenerationElitism() best = ga.bestChromosome() if (i + 1) % int(gaParam["noGen"] / 10) == 0: to_list.append([i + 1, best.fitness, best.repres]) #print(len(set(best.repres)), best.fitness) best_all.append(best) #print(len(set(best.repres)), best) return best_all, to_list
def main(): net = readGraph("hard_01_tsp.txt") gaParam = {'popSize': 10, 'noGen': 1000, 'pc': 0.8, 'pm': 0.1} problParam = {'net': net, 'function': fitness, 'noNodes': net['noNodes']} ga = GA(gaParam, problParam) ga.initialisation() ga.evaluation() ga.oneGenerationElitism() final = ga.bestChromosome() print(final)
def main(): n, matrix = citire() gaParam = {'popSize': 400, 'nrGen': 400, 'k': 150} propParam = {'matrix': matrix, 'n': n, 'function': fitness_function} ga = GA(gaParam, propParam) ga.initialisation() ga.evaluation() best = ga.bestChromosome() fitnees = best.fitness x = [] y = [] for i in range(gaParam['nrGen']): bestSolution = ga.bestChromosome() # print(bestSolution) x.append(i) y.append(bestSolution.fitness) if bestSolution.fitness < fitnees: best = bestSolution fitnees = best.fitness # if i%2 == 0: # ga.oneGeneration() # else: print(bestSolution) ga.oneGenerationElitism() print(best) print(fitnees) plt.plot(x, y) plt.xlabel('generatie') plt.ylabel('fitness') plt.show()
def main(): #fileName = 'easy1.txt' #fileName = 'medium.txt' fileName = 'hard_02.txt' param, problParam = initParams(fileName) ga = GA(param, problParam) ga.initialisation() ga.evaluation() for i in range(param['noGen'] - 1): ga.oneGenerationElitism() print(ga.bestChromosome())
def main(): crtDir = os.getcwd() filePath = os.path.join(crtDir, 'mediumF.txt') fileName = filePath.split("\\")[-1] if fileName == "hardE.txt" or fileName == "berlin52.txt": net = reading.readNet2(filePath) else: net = reading.readNet(filePath) print(net) MIN = 0 MAX = net['noNodes'] # initialise de GA parameters gaParam = {'popSize': 100, 'noGen': 150} # problem parameters problParam = {'min': MIN, 'max': MAX, 'function': fitnessOfChromosome, 'network': net, 'noNodes': MAX, 'noBits': 8, 'mat': net['mat']} ga = GA(gaParam, problParam) ga.initialisation() ga.evaluation() print("Population: " + str(ga.population.__repr__())) for generation in range(gaParam['noGen']): # ga.oneGeneration() # ga.oneGenerationElitism() # ga.oneGenerationSteadyState() ga.oneGenerationSteadyState1() bestChromo = ga.bestChromosome() print('Best solution in generation ' + str(generation) + ' is: x = ' + str( bestChromo.repres) + ' with fitness = ' + str(bestChromo.fitness)) bestChromo = ga.bestChromosome() print('Best solution is: x = ' + str(bestChromo.repres) + '\nwith fitness = ' + str(bestChromo.fitness))
def main(): filename = FILENAMES['easy'] network = readFile('./resources/' + filename) gaParam = {'popSize': 10, 'noGen': 1000, 'network': network} problParam = {'function': pathFunction, 'noNodes': network['noNodes']} ga = GA(gaParam, problParam) ga.initialisation() ga.evaluation() for i in range(gaParam['noGen'] - 1): ga.oneGenerationElitism() bestChromosome = ga.bestChromosome() print(bestChromosome)
def main(): ga = GA(gaParam, problParam) ga.initialisation() ga.evaluation() stop = False g = -1 while (not stop and g < gaParam['noGen']): g += 1 ga.oneGeneration() bestChromo = ga.bestChromosome() print('Solutia cea mai buna in generatia ' + str(g) + ' este: ' + str(afisare(bestChromo.repres)) + ' f(x) = ' + str( bestChromo.fitness) + ' ' + 'Numar comunitati:' + str(len(afisare(bestChromo.repres))))
def main(): net = read_file("easy_03_tsp.txt") # net = read_file("medium_01_tsp.txt") # net = read_file("hard_01_tsp.txt") gaParam = {'popSize':100, 'noGen' : 500, 'pc' : 1.8, 'pm' : 1.1} problParam = {'net': net, 'function': function, 'noNodes':net['noNodes']} ga = GA(gaParam, problParam) ga.initialisation() ga.evaluation() for i in range(0, gaParam['noGen']): ga.oneGenerationElitism() print(ga.bestChromosome())
def main(): marimePopulatie = 100; nrGeneratii = 300; citire = Citire("hardE.txt") # graf = citire.citire() graf = citire.citireBerlin() ga = GA(marimePopulatie, graf) ga.initialisation() stop = False g = -1 # nr de generatii while not stop and g < 300: g = g + 1 ga.oneGeneration() bestChromo = ga.bestChromosome() print('Best solution in generation ' + str(g) + ' is: x = ' + str(bestChromo.repres) + ' f(x) = ' + str(bestChromo.fitness))
def main(): net = read_file("Exemplul3.txt") gaParam = {'popSize': 10, 'noGen': 1000, 'pc': 0.8, 'pm': 0.1} problParam = { 'net': net, 'function': fitnessFct, 'noNodes': net['noNodes'] } ga = GA(gaParam, problParam) ga.initialisation() ga.evaluation() #for i in range(1, gaParam['noGen']): ga.oneGenerationElitism() final = ga.bestChromosome() print(final)
def main(): n, matrix = read_data() # initialise de GA parameters gaParam = {'popSize': 50, 'noGen': 100, 'k': 5} # problem parameters problParam = {'matrix': matrix, 'noNodes': n, 'function': function} ga = GA(gaParam, problParam) ga.initialisation() ga.evaluation() for g in range(gaParam['noGen']): # logic alg # ga.oneGenerationElitism() ga.oneGenerationSteadyState() bestChromo = ga.bestChromosome() print('Best solution in generation ' + str(g) + ' is: x = ' + str(bestChromo.repres) + ' f(x) = ' + str(bestChromo.fitness))
def main(): n, tsp = reader.read("data/easy_02_tsp.txt") ga_param = {'popSize': factorial(n), 'noGen': 1} problem_param = {'noNodes': n, 'cities': tsp, 'function': route_length} ga = GA(ga_param, problem_param) ga.initialisation() ga.evaluation() solution = None for g in range(ga_param['noGen']): ga.oneGeneration() bestChromosome = ga.bestChromosome() print('Best solution in generation ' + str(g + 1) + ' is: ' + str(bestChromosome)) solution = bestChromosome writer.write(n, solution.representation, route_length(solution.representation, tsp), 'output.txt')
def main(): network = readNet("input1.txt") gaParameters = {"populationSize": 10, "numberOfGenerations": 1000} problemParameters = { 'function': fcEval, 'numberOfNodes': network["numberOfNodes"], 'matrix': network["matrix"], 'startNode': network["startNode"], 'endNode': network["endNode"] } globalBestChromosome = Chromosome(problemParameters) ga = GA(gaParameters, problemParameters) print("ga done") ga.initialisation() print("initialisation done") ga.evaluation() print("evaluation done") generation = 0 while (generation < gaParameters["numberOfGenerations"]): generation += 1 #ga.oneGeneration() ga.oneGenerationElitism() #ga.oneGenerationSteadyState() bestChromosom = ga.bestChromosome() if bestChromosom.fitness < globalBestChromosome.fitness: globalBestChromosome = bestChromosom print("------ gen: " + str(generation) + "--------") print('Local Best fit = ' + str(bestChromosom.fitness)) print('Local worst fit: ', ga.worstChromosome()[0].fitness) print('Global Best fit: ', globalBestChromosome.fitness) print() path = globalBestChromosome.repres path = [x + 1 for x in path] print(path)
def main(): ga = GA(gaParam, problParam) ga.initialisation() ga.evaluation() i = 1 while (i <= gaParam['noGen']): ga.oneGeneration() bestChromo = ga.bestChromosome() print('Cea mai buna solutie in generatia: ' + str(i) + ' cu fitnessul f(x) = ' + str(bestChromo.fitness) + ' ' + 'numarul comunitatilor fiind:' + str(len(printData(bestChromo.repres)))) i += 1 print(bestChromo.repres) afisare_comunitati(gaParam['network'], bestChromo)
def main(): ga = GA(gaParam, problParam) ga.initialisation( ) # fac o initializare, generez 300 de cromozomi si ii adaug in populatie ga.evaluation() for g in range(gaParam['noGen']): ga.oneGenerationElitism() bestChromo = ga.bestChromosome() #print(bestChromo.repres) a = [] for x in bestChromo.repres: a.append(x + 1) print(a) print(bestChromo.fitness)
def main(): ga = GA(gaParam, problParam) ga.initialisation( ) # fac o initializare, generez 300 de cromozomi si ii adaug in populatie ga.evaluation( ) # evaluez fitness-ul, sa vad cat de buni sunt cu functia modularity for g in range(gaParam['noGen']): ga.oneGeneration() bestChromo = ga.bestChromosome() print('In generatia ' + str(g) + ' cel mai bun cromozom: ' + str(afisare(bestChromo.repres)) + ' f(x) = ' + str(bestChromo.fitness) + ' ' + 'nr. comunitati:' + str(len(afisare(bestChromo.repres)))) afisare_comunitati(gaParam['network'], bestChromo) afisare_graf(gaParam['network'])