def main(): parser = argparse.ArgumentParser( description= "Runs hillclimbing or genetic algorithm to solve a given sudoku puzzle." ) parser.add_argument('algorithm', type=str, help="Either \"hillclimbing\" or \"genetic\".") args = parser.parse_args() algorithm = args.algorithm # grid = [ # [3, None, None, 2 ], # [None, 1, 4, None], # [1, 2, None, 4 ], # [None, None, 2, 1 ] # ] grid = [ [None, None, None, 7, None, None, None, None, None], [1, None, None, None, None, None, None, None, None], [None, None, None, 4, 3, None, 2, None, None], [None, None, None, None, None, None, None, None, 6], [None, None, None, 5, None, 9, None, None, None], [None, None, None, None, None, None, 4, 1, 8], [None, None, None, None, 8, 1, None, None, None], [None, None, 2, None, None, None, None, 5, None], [None, 4, None, None, None, None, 3, None, None], ] if algorithm == "hillclimbing": board = sudoku.Sudoku(grid) print(board) board.generate_new_individual() print("Starting individual:\n{}\n".format(board)) HC = hillclimbing.HillClimb(board, 100000) print("Starting heuristic value: {}".format(HC.found_value)) # selecting hillclimbing final_board, final_value = HC.exec() print("{}\n\nFinal heuristic value: {}".format(final_board, final_value)) elif algorithm == "genetic": # selecting genetic GA = genetic.Genetic(grid, population_size=4, max_generations=1) for i in GA.population: print(str(i[0]), "\n\n") best = GA.exec() print("Best: \n{}\n\nHeuristic value: {}\n".format(best[0], best[1])) else: parser.print_help() exit()
def run(self, crossoverrate, mutationrate, maxgen): for i in range(self.repeat): genetic = gn.Genetic(self.matriz_p, crossoverrate, mutationrate, maxgen) genetic.recursive_genetic(self.generation) self.best_generations.append(genetic.best_generation['index']) if genetic.best_generation['index'] < self.best_gen: self.best_gen = genetic.best_generation['index'] print('best individual: ', genetic.best_individual) self.best_individual_by_generation_in_ten_repeat.append( genetic.best_individual_by_generation) self.mean_individuals_generation_in_ten_repeat.append(genetic.mean) self.plot_generation(i, genetic.mean, genetic.best_individual_by_generation) if len(self.best_all_individual) == 0: self.best_all_individual = genetic.best_individual elif len(genetic.best_individual) != 0: if self.best_all_individual[-1] < genetic.best_individual[-1]: self.best_all_individual = genetic.best_individual print('\n----------------------------------------\n\t\trepeat: ', i + 1, '\n----------------------------------------\n\n') # best_ind... ten_repeat = [ # [ 4, 3, 2] <- repetição 1 melhor individuo (fitness) em cada geração x repetição [posição: geração: 1, 2, 3 ..] # [ 5, 2, 1] <- repetição 2 melhor individuo (fitness) em cada geração x repetição [posição: geração: 1, 2, 3 ..] # .... # [n1, n2, n3] # ] mean_all_repeat = self.uniform( self.mean_individuals_generation_in_ten_repeat, maxgen) best_all_repeat = self.uniform( self.best_individual_by_generation_in_ten_repeat, maxgen) self.plot_generation(i, mean_all_repeat, best_all_repeat, ox=False) mean_all_gen = np.mean(self.best_generations) self.plot_repeat(mean_all_gen) # writer here. subi uma casa e tira a ultima writer = write.writer() del self.best_all_individual[-1] self.best_all_individual = map(lambda x: x + 1, self.best_all_individual) writer.writeArchive(self.best_all_individual, self.outputpath)
def main(): goal = 'to be or not to be' options = types.SimpleNamespace() options.initialPopulation = generateInitialPopulation(len(goal)) options.fitness = calcFitness options.mutate = mutate options.mutationRate = 0.7 options.alphaThreshold = 0.01 gen = genetic.Genetic(options) while (gen.getScore() < 0.8): gen.evolve() print('score = ', gen.getScore()) print('solution = ', gen.getSolution()) print('-----------')
maxY = de.setWeights(data.population) statsDE = de.calc(30) print(de.parents[0][1], de.test(de.parents[0][0])) plt.subplot(1, 3, 1) plt.ylim(0, maxY) plt.semilogx(statsDE) plt.title("Differential Evolution") ##======================= Genetic Algorithm ===================== print( "\n\n##======================= Genetic Algorithm =====================\n\n" ) ga = GA.Genetic(population, data.N, data.K, data.testN) ga.setInputsOutputs(data.inputs, data.outputs) ga.setTestInputsOutputs(data.testInputs, data.testOutputs) ga.setWeights(data.population) statsGA = ga.calc(20) print(ga.parents[0][1], ga.test(ga.parents[0][0])) plt.subplot(1, 3, 2) plt.ylim(0, maxY) plt.semilogx(statsGA) plt.title("Genetic Algorithm") ##================== Particle Swarm Optimization ================ print( "\n\n##================== Particle Swarm Optimization ================\n\n" )
def main(): userInput = input( "Enter 5 or greater for a board of that size, or 0 to randomize the board. " ) gameBoard = board.Board( userInput) # builds a Board() object and assigns it to gameBoard bfs = evaluate.evaluate( gameBoard.boardBuilt, gameBoard.boardSize) # creates the bfs object for the original board hillBoard = hill.Hill( gameBoard) # creates a hill-climbing object with the original board aStar = AStarEval.AStarEval( gameBoard.boardBuilt, gameBoard.boardSize) # create an A* object for the original board gene = genetic.Genetic(gameBoard) print("Score for the board: " + str(bfs.value) + "; time for BFS (ms): " + str(bfs.evalTime)) # prints the score for the original board # create a loop for user input to make selections to view the original board, etc while True: print() userInput = input( "Type '1' for the original board, '2' for number of steps on original board, '3' to implement Hill Climbing, '4' to view the Hill Board, '5' to view steps on Hill Board, " + "'6' to view A* score, 'q' to exit. ") if userInput == '1': draw.drawBoard( gameBoard.boardBuilt, gameBoard.boardSize ) # takes the created board and draws it with turtle, as visual output print("> Original game board displayed. Score: " + str(bfs.value)) elif userInput == '2': draw.drawBoard(bfs.steps, gameBoard.boardSize) # uses the draw module print("> Number of steps to reach a tile displayed.") elif userInput == '3': userInput = int( input( "> How many iterations would you like the hill-climbing to try? " )) while userInput < 0: userInput = input( "> How many iterations would you like the hill-climbing to try? " ) hillBoard.climb(userInput) print("> New board score: " + str(hillBoard.score) + "; time for hill-climb (ms): " + str(hillBoard.evalTime)) elif userInput == '4': draw.drawBoard( hillBoard.puzzle.boardBuilt, gameBoard.boardSize ) # takes the created board and draws it with turtle, as visual output print("> Hill-CLimbing game board displayed. Score: " + str(hillBoard.score)) elif userInput == '5': hillBFS = evaluate.evaluate( hillBoard.puzzle.boardBuilt, hillBoard.puzzle.boardSize ) # creates a new bfs object for the hill-climbing board draw.drawBoard(hillBFS.steps, hillBoard.puzzle.boardSize) print("> Hill-Climbing board number of steps displayed") elif userInput == '6': #draw.drawBoard(aStar.steps, gameBoard.boardSize) print("> A* steps displayed. \nBFS Score, Time: " + str(bfs.value) + ", " + str(bfs.evalTime) + "\nA* Score, Time: " + str(aStar.value) + ", " + str(aStar.evalTime)) elif userInput == '7': userInput = int( input("> How many iterations would you like genetic to try? ")) while userInput < 0: userInput = input( "> How many iterations would you like genetic to try? ") gene.run(bfs, userInput) print(gene.score) elif userInput == 'q': break
#!/usr/bin/env python # -*- coding: utf-8 -*- import math import numpy as np import genetic as gen holdertable = lambda x: -np.abs( np.sin(x[0]) * np.cos(x[1]) * math.exp( np.abs(1 - (np.sqrt(x[0] * x[0] + x[1] * x[1]) / math.pi)))) holdertableminfinder = gen.Genetic(holdertable, 2, 100, -10, 10, True, 0.1, 0.7, True, -200, True) holdertableminfinder.run() holdertableminfinder.showNotables() #holdertableminfinder.showPopulation() holdertableminfinder.plot()
i = 0 j = 0 n = 5 # Make numberPer amount of boards of the four default sizes, create bfs objects for all of them, make hill-climbing objects for all of them, then iterate each object 50 times while i < size: while j < numberPer: boards[i] = board.Board(n) hills[i] = hill.Hill(boards[i]) # create hill-climbing objects hills[i].climb(iterations) # iterate hill-climbing objects bfs[i] = evaluate.evaluate(boards[i].boardBuilt, boards[i].boardSize) # create BFS objects to evaluate original board bfsHill[i] = evaluate.evaluate(hills[i].puzzle.boardBuilt, hills[i].puzzle.boardSize) # create BFS object to evaluate hill-climbing board gene[i] = genetic.Genetic(boards[i]) gene[i].run(bfs[i], iterations) aStar[i] = AStarEval.AStarEval(boards[i].boardBuilt, boards[i].boardSize) # create A* objects to evaluate original board aStarHill[i] = AStarEval.AStarEval(hills[i].puzzle.boardBuilt, hills[i].puzzle.boardSize) # create A* objects to evaluate hill-climbing board sizeArray[i] = n i += 1 j += 1 n += 2 j = 0 bfsScore = [n.value for n in bfs] # array with the bfs scores bfsTime = [n.evalTime for n in bfs] # array with the bfs time evaluation
#!/usr/bin/env python # -*- coding: utf-8 -*- import math import numpy as np import genetic as gen easom = lambda x: -np.cos(x[0]) * np.cos(x[1]) * math.exp(-(math.pow( x[0] - math.pi, 2) + math.pow(x[1] - math.pi, 2))) easomminfinder = gen.Genetic(easom, 2, 100, -100, 100, True, 0.1, 0.7, True, -200, True) easomminfinder.run() easomminfinder.showNotables() #easomminfinder.showPopulation() easomminfinder.plot()
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np import genetic as gen eggholder = lambda x: -(x[1] + 47) * np.sin( np.sqrt(abs(x[1] + (x[0] / 2) + 47))) - x[0] * np.sin( np.sqrt(abs(x[0] - (x[1] + 47)))) eggholderminfinder = gen.Genetic(eggholder, 2, 300, -512, 512, True, 0.2, 0.6, True, -1500, True) eggholderminfinder.run() eggholderminfinder.showNotables() #eggholderminfinder.showPopulation() eggholderminfinder.plot()
def main(argv): arg_d = None arg_m = 0.1 arg_p = 1000 arg_r = "result.json" arg_s = None # Parsowanie opcji try: opts, _ = getopt.getopt(argv, "d:hm:p:r:s:", []) except getopt.GetoptError: print("pszt1.py [-hs] [-m num] [-p num] -d data.json") return 1 # Obsługa opcji for opt, arg in opts: if opt == "-h": print_help() return 0 elif opt == "-d": arg_d = arg elif opt == "-r": arg_r = arg elif opt == "-s": arg_s = arg elif opt == "-m": try: arg_m = float(arg) if arg_m < 0 or arg_m > 1: raise Exception() except Exception: print( "Błąd: prawdopodobieństwo mutacji musi być liczbą z przedziału [0, 1]" ) return 1 elif opt == "-p": try: arg_p = int(arg) if arg_p < 1: raise Exception() except Exception: print("Błąd: rozmiar populacji musi być liczbą naturalną") return 1 # Sprawdzenie, czy został podany plik z danymi if not arg_d: print("Błąd: nie został podany plik z danymi") return 1 # Odczyt pliku z danymi try: gen_data = data.from_json_file(arg_d) except data.DataError as ex: print("Błąd: %s" % (ex.msg, )) return 1 print("Liczba osób: %i" % gen_data.num_of_people) print("Liczba stołów: %i" % gen_data.num_of_tables) print("Rozmiar populacji: %i" % arg_p) print("Prawdopodobieństwo mutacji: %.2f" % arg_m) # Uruchomienie algorytmu scores = [] def callback(generation, avg_score): sys.stdout.write("\rGeneracja %i, średni wynik: %.3f " % (generation, avg_score)) sys.stdout.flush() scores.append((generation, round(avg_score, 4))) algorithm = genetic.Genetic(config.Config(arg_p, arg_m), gen_data) result = algorithm.run(callback) # Zapis wyniku do pliku try: with open(arg_r, "w") as f: json.dump({"stoly": result.tables}, f, indent=4) print("\nWynik zapisano do pliku %s" % (arg_r, )) except IOError as e: print("Błąd: nie udało się zapisać wyniku do pliku %s: %s" % ( arg_r, e.strerror, )) return 1 if arg_s: # Zapis średnich wartości funkcji dopasowania do pliku try: with open(arg_s, "w") as f: file = csv.writer(f, delimiter=";") file.writerow(("generacja", "sredni_wynik")) file.writerows(scores) print( "Średnie wartości funkcji dopasowania zapisano do pliku %s" % (arg_s, )) except IOError as e: print("Błąd: nie udało się zapisać średnich wartości funkcji") print("dopasowania do pliku %s: %s" % ( arg_s, e.strerror, )) return 1 return 0
#!/usr/bin/env python # -*- coding: utf-8 -*- import math import numpy as np import genetic as gen shafter4 = lambda x: 0.5 + (math.pow( np.cos(np.sin(np.abs(x[0] * x[0] + x[1] * x[1]))), 2) - 0.5) / math.pow( (1 + 0.001 * (x[0] * x[0] + x[1] * x[1])), 2) shafter4minfinder = gen.Genetic(shafter4, 2, 100, -100, 100, True, 0.1, 0.7, True, -200, True) shafter4minfinder.run() shafter4minfinder.showNotables() #shafter4minfinder.showPopulation() shafter4minfinder.plot()
'''==========Solving job shop scheduling problem by genetic algorithm in python=======''' # importing required modules import pandas as pd import numpy as np import time import copy import matplotlib.pyplot as plt import chart_studio.plotly as py import plotly.figure_factory as ff import datetime #import genetic as ga import genetic as ga ''' ================= initialization setting ======================''' genetic = ga.Genetic() pt_tmp = pd.read_excel("jssp_dataset.xlsx", sheet_name="Processing Time", index_col=[0]) ms_tmp = pd.read_excel("jssp_dataset.xlsx", sheet_name="Machines Sequence", index_col=[0]) genetic.initParameters(pt_tmp, ms_tmp) '''==================== main code ===============================''' start_time = time.time() '''----- generate initial population -----''' genetic.runGeneticAlgorithm()
import genetic boardSize = 8 populationSize = 10 probability = 10 if __name__ == "__main__": question = genetic.Genetic(boardSize) question.startGA(populationSize,probability)
# print('Best :' , sa.BS, ' Score : ', sa.B) # sa.B = 10000 # print(sa.nodeSeen) # print(sa.nodeExpand) # # print('--------') # sa.search('2') # sa.counter = 0 # print('Best :' , sa.BS, ' Score : ', sa.B) # sa.B = 100000 # # print('--------') # sa.search('3') # print('Best :' , sa.BS, ' Score : ', sa.B) genetic = genetic.Genetic() genetic.problem = c genetic.generate_chromosome() while not genetic.end(): print('Spin : ', genetic.currentGen) genetic.evaluation_fitness() genetic.select_chromosome() genetic.cross_over() genetic.mutation() genetic.answer() c_time = genetic.bestG python_time = genetic.meanG new_time = genetic.worstG
inputs = decision(network_inputs) reward, running = game.run(inputs, is_ai=True) t += 1 if reward > 0: t = 0 score += reward if not running: break if t >= max_frames - 1: score -= MAX_FRAMES_PENALTY / (game.checkpoint + 1) print(score) return score model = genetic.Genetic(model_params["n_indiv"], neural_structure, fit_function) # loaded_gen = genetic.load_gen(".\\gens\\04_02_2020-17_10_0.hdf5", fit_function) # model.generations = [loaded_gen] mutation_start = model_params["mutation_start"] mutation_stop = model_params["mutation_stop"] n_epochs = model_params["n_epochs"] mutation_decay = (mutation_stop - mutation_start) / n_epochs best_score = -1000. n_bests = model_params["n_bests"] # weights_off = [n_bests - (2*i/n_bests) for i in range(n_bests)] weights_off = model_params["weights"] keep_n_bests = model_params["keep_n_bests"] scores = [] def plot_scores(scores, filename):