def main(): # Definicao do problema p = ProblemaRaiz() hc = HillClimbing(max_alt=1000, max_sem_alt=10) hc.executa(p) tb = TabuSearch(max_alt=1000, max_sem_alt=10) tb.executa(p) tbg = TabuSearchGrasp(max_alt=1000, max_sem_alt=10) tbg.executa(p)
def main(): target_string = "Hello World!" population_size = 1400 runs = 10 """ The main method for the application. The Genetic Algorithm uses tournament selection as selection method and k-point or one-point crossover as crossover methods. The Genetic Algorithm constructor takes in the following parameters: @param: target_string The target string @param: population_size Amount of randomly generated strings @param: crossover_rate Crossover Rate in percentage (i.e. 1 = 100%) @param: mutation_rate Mutation Rate in percentage @param: is_k_point_crossover Choose whether to choose k-point crossover as crossover method. If false, one-point crossover is performed @param: tournament_size_percent Percentage of population to participate in tournaments for selection @param: strongest_winner_probability Probability of strongest participant in tournament to win, as well as the second strongest's probability """ ga = GeneticAlgorithm(target_string, population_size, 0.8, 0.05, True, 0.05, 0.65) ga.set_show_each_chromosome(False) ga.set_show_crossover_internals(False) ga.set_show_mutation_internals(False) ga.set_silent( False) # If False it shows the fittest chromosome of each generation ga.run(runs) ga.get_stats() """ The Hill Climbing constructor takes in the following parameters: @param: target_string The target string @param: solutions_size Amount of solutions (strings) to search for a better solution in """ hc = HillClimbing(target_string, population_size) hc.set_show_each_solution(False) hc.set_silent(True) hc.run(runs) hc.get_stats() """ The Random Search constructor takes in the following parameters: @param: target_string The target string @param: solutions_size Amount of solutions (strings) generated randomly each round in which the solution is searched for """ rs = RandomSearch(target_string, population_size) rs.set_show_each_solution(False) rs.set_silent(True) rs.run(runs) rs.get_stats()
def basic_stats(queens, epochs=1): """ Wrapper for HillClimbing.basic to calculate stats based on a given number of epochs. Args: queens (Queens): Queens object used in hill climbing algorithm. epochs (int): Number of epochs to run before calculating averages. """ successes = {'count': np.finfo(float).eps, 'steps' : 0} failures = {'count': np.finfo(float).eps, 'steps' : 0} for e in range(epochs): print("{:=^50d}".format(e+1)) # New random board queens.populate_board(seed=None) successful, steps = HillClimbing.basic(queens) if successful: successes['count'] += 1 successes['steps'] += steps else: failures['count'] += 1 failures['steps'] += steps print("{:=^50s}".format("Stats")) print("Success Stats") print("-Rate: {:.2f}".format(successes['count'] / epochs)) print("-Steps: {:.2f}".format(successes['steps'] / successes['count'])) print("Failure Stats") print("-Rate: {:.2f}".format(failures['count'] / epochs)) print("-Steps: {:.2f}".format(failures['steps'] / failures['count']))
def main(): # initialize the enironment env = gym.make('Acrobot-v0') env.monitor.start('acrobot', force=True, seed=0) # initialize agent agent = HillClimbing(env.action_space, env.observation_space) # set up run parameters episode_count = 200 max_steps = env.spec.timestep_limit reward = 0 done = False # run the episodes for i_episode in range(episode_count): print i_episode, agent.start_episode() ob = env.reset() for t in range(max_steps): #env.render() # get action from the agent action = agent.act(ob, reward, done) ob, reward, done, _ = env.step(action) if done: break agent.end_episode()
def executar(self): self.listaDadosIniciais = Configuracao.gerarDadosIniciais( self.configuracao) resultado = Resultado(self.configuracao.problema) for a in range(4): algoritmo = None if (a == 0): algoritmo = Algoritmo(Configuracao.algoritmos[a], HillClimbing(self.configuracao)) elif (a == 1): algoritmo = Algoritmo(Configuracao.algoritmos[a], HillClimbingRestart(self.configuracao)) elif (a == 2): algoritmo = Algoritmo(Configuracao.algoritmos[a], SimulatedAnnealing(self.configuracao)) else: algoritmo = Algoritmo(Configuracao.algoritmos[a], GeneticAlgorithm(self.configuracao)) for iteracao in range(10): algoritmo.executar(self.listaDadosIniciais[iteracao], iteracao) algoritmo.gerarEstatisticas() Graficos.gerarGraficoFuncaoObjetivo(algoritmo, self.configuracao) resultado.adicionar(algoritmo) inicioComparativo = time.perf_counter() self.finalizar(resultado) terminoComparativo = time.perf_counter() print( f"Geração da tabela/gráfico de comparativo de performance em {terminoComparativo - inicioComparativo:0.4f} segundos" )
def random_restarts_stats(queens, threshold=100, epochs=1): """ Wrapper for HillClimbing.random_restarts to calculate stats based on a given number of epochs. Args: queens (Queens): Queens object used in hill climbing algorithm. threshold (int): Threshold number sideways moves allowed. epochs (int): Number of epochs to run before calculating averages. """ successes = {'count': np.finfo(float).eps, 'steps' : 0, 'restarts': 0} failures = {'count': np.finfo(float).eps, 'steps' : 0, 'restarts': 0} for e in range(epochs): print("{:=^50d}".format(e+1)) # New random board queens.populate_board(seed=None) successful, steps, restarts = HillClimbing.random_restarts( queens=queens, threshold=threshold) if successful: successes['count'] += 1 successes['steps'] += steps successes['restarts'] += restarts else: failures['count'] += 1 failures['steps'] += steps failures['restarts'] += restarts print("{:=^50s}".format("Stats")) print("Success Stats") print("-Rate: {:.2f}".format(successes['count'] / epochs)) print("-Steps: {:.2f}".format(successes['steps'] / successes['count'])) print("-Restarts: {:.2f}".format(successes['restarts'] / successes['count'])) print("Failure Stats") print("-Rate: {:.2f}".format(failures['count'] / epochs)) print("-Steps: {:.2f}".format(failures['steps'] / failures['count'])) print("-Restarts: {:.2f}".format(failures['restarts'] / failures['count']))
def run(): label_find_the_result.config(text="Result:") label_time.config(text="Time:") label_steps.config(text="Steps:") btn_run.config(state=tk.DISABLED) btn_reset.config(state=tk.DISABLED) radio_dfs.config(state=tk.DISABLED) radio_bfs.config(state=tk.DISABLED) radio_bestfs.config(state=tk.DISABLED) radio_hc.config(state=tk.DISABLED) algorithm = alg.get() res = "" steps = 0 time_start = time.time() if algorithm == 1: res = DFS.solve(puzzle_in, window) print("DFS: ", res) elif algorithm == 2: res = BFS.solve(puzzle_in, window) print("BFS: ", res) elif algorithm == 3: res = BestFirstSearch.solve(puzzle_in, window) print("Best First Search: ", res) elif algorithm == 4: res = HillClimbing.solve(puzzle_in, window) print("Hill Climbing: ", res) time_end = time.time() if res is None: solution = "No!" else: solution = "Yes!" steps = len(res) output(solution, time_end - time_start, steps) btn_run.config(state=tk.NORMAL) btn_reset.config(state=tk.NORMAL) radio_dfs.config(state=tk.NORMAL) radio_bfs.config(state=tk.NORMAL) radio_bestfs.config(state=tk.NORMAL) radio_hc.config(state=tk.NORMAL)
def main(): runs = 10 rounds = 5 chromosome_size = 23 population_size = 1000 data_set_name = 'bigfaultmatrix.txt' pwd = os.path.abspath(os.path.dirname(__file__)) data_set_path = os.path.join(pwd, data_set_name) parser = CSVParser(data_set_path) test_case_fault_matrix = parser.parse_data(True) ga = GeneticAlgorithm(test_case_fault_matrix, chromosome_size, population_size, rounds, 0.8, 0.08, 0.05, 0.75) ga.set_show_each_chromosome(False) ga.set_show_fitness_internals(False) ga.set_show_crossover_internals(False) ga.set_show_mutation_internals(False) ga.set_show_duplicate_internals(False) ga.set_silent(True) ga.run(runs) ga_fitness = ga.get_stats() for i in range(0, 2): if i == 0: hc = HillClimbing(test_case_fault_matrix, chromosome_size, population_size, rounds, False) else: hc = HillClimbing(test_case_fault_matrix, chromosome_size, population_size, rounds, True) hc.set_show_each_solution(False) hc.set_show_fitness_internals(False) hc.set_show_swapping_internals(False) hc.set_silent(True) hc.run(runs) if i == 0: hc_internal_fitness = hc.get_stats() else: hc_external_fitness = hc.get_stats() rs = RandomSearch(test_case_fault_matrix, chromosome_size, population_size, rounds) rs.set_show_each_solution(False) rs.set_silent(True) rs.run(runs) rs_fitness = rs.get_stats() rs_data = np.array(rs_fitness) hs_internal = np.array(hc_internal_fitness) hs_external = np.array(hc_external_fitness) ga_data = np.array(ga_fitness) # test_cases_per_test_suite = np.array([5, 10, 20, 23, 30, 50, 100]) # unique_large_apfd = np.array([0.4594736842105263, 0.6063157894736844, 0.6867105263157895, 0.6978260869565216, 0.7128947368421051, 0.7326842105263159, 0.7480263157894737]) # full_large_apfd = np.array([0.44631578947368417, 0.6023684210526316, 0.6846052631578947, 0.6958810068649884, 0.7122807017543858, 0.7320526315789474, 0.7476578947368421]) # plt.plot(test_cases_per_test_suite, unique_large_apfd, '-gD') # plt.xlabel("Test Cases per Test Suite") # plt.ylabel("Mean Fitness (APFD)") # plt.xticks(np.arange(min(test_cases_per_test_suite), max(test_cases_per_test_suite) + 1, 5.0)) # combine these different collections into a list data_to_plot = [rs_data, hs_internal, hs_external, ga_data] # Create a figure instance fig = plt.figure(1, figsize=(9, 6)) # Create an axes instance ax = fig.add_subplot(111) # add patch_artist=True option to ax.boxplot() bp = ax.boxplot(data_to_plot, patch_artist=True) # change outline color, fill color and linewidth of the boxes for box in bp['boxes']: # change outline color box.set(color='#7570b3', linewidth=2) # change fill color box.set(facecolor='#1b9e77') # change color and linewidth of the whiskers for whisker in bp['whiskers']: whisker.set(color='#7570b3', linewidth=2) # change color and linewidth of the caps for cap in bp['caps']: cap.set(color='#7570b3', linewidth=2) # change color and linewidth of the medians for median in bp['medians']: median.set(color='#b2df8a', linewidth=2) # change the style of fliers and their fill for flier in bp['fliers']: flier.set(marker='o', color='#e7298a', alpha=0.5) # Custom x-axis labels ax.set_xticklabels([ 'Random Search', 'HC Internal Swap', 'HC External Swap', 'Genetic Algorithm' ]) # Remove top axes and right axes ticks ax.get_xaxis().tick_bottom() ax.get_yaxis().tick_left() # Save the figure graph_path = os.path.join(pwd, 'graph.pdf') pdf = PdfPages(graph_path) plt.savefig(pdf, format='pdf', bbox_inches='tight') plt.show() pdf.close()
i, j = 6, 6 board[i, j] = 1 i, j = 5, 7 board[i, j] = 1 board.print() try: n = 8 board = Board(n) #_board_setup(board) exp_num = _get_experiment_number() board.rand_init() hill_climbing = HillClimbing(board) path = 'figures/' path += str(exp_num) path += '-experiment' path += '.txt' _save_board_setup(path, hill_climbing) line_plot = [] for h in hill_climbing.execute(): line_plot.append(h) except KeyboardInterrupt: print("W: interrupt received, stopping…") finally:
from iterative_local_search import IterativeLocalSearch # from gls import GuidedLocalSearch if __name__ == '__main__': # parameters for simulation values = [120, 130, 80, 100, 250, 185] costs = [10, 12, 7, 9, 21, 16] number_of_items = [0 for i in range(0, len(values))] capasity = 65 neighbor_distance = 2 # prepare solver dictionary sa = SimulatedAnealing(capasity, values, costs, number_of_items, neighbor_distance, 10000, 0.99) hc = HillClimbing(capasity, values, costs, number_of_items, neighbor_distance) # ta = TabuSearch(...) ils = IterativeLocalSearch(capasity, values, costs, number_of_items, neighbor_distance) # gls = GuidedLocalSearch(...) implemented_algorithms = { 'sa': sa, 'hc': hc, # 'ta': ta 'ils': ils, # 'gls': gls } parser = argparse.ArgumentParser() parser.add_argument('-d', '--debug',
if len(argv) < 9: print( "Wrong number of parameters: size seed -- HillClimbing numberIterations distance {empty/random} {ILS/RLS} {number_perturbation_for_ILS}" ) exit() # Parsing input datatype = [int, int, str, str, int, int, str, str] size, seed, _, _, num_iterations, distance, empty, option = map( lambda x: x[0](x[1]), zip(datatype, argv[1:])) perturbations = 1 if option == "ILS": if len(argv) > 9: perturbations = int(argv[9]) #Initialising object hc = HillClimbing(size, seed, num_iterations, distance, perturbations, empty == "empty") startTime = time() sol, total_number_individuals = None, 0 if option == "ILS": sol, total_number_individuals = hc.ILS() elif option == "RLS": sol, total_number_individuals = hc.RLS() else: print("Unknow Algorithm") exit() elapsed_time = time() - startTime #Printing output print("\n------------ SOLUTION ------------\n") printMaze(getProblemInstance(size, sol[0]))
# Create a portfolio for each of the three investment strategies: hill climbing, # simulated annealing, and user choice, with an initial investment of $10,000 # in each of the ten companies. user_portfolio = Portfolio() hc_portfolio = Portfolio() sa_portfolio = Portfolio() initial_investment = 10000 for i in user_list: new_node = Node(i, dow_jones.get(i), initial_investment) hc_portfolio.add_stock(new_node) sa_portfolio.add_stock(new_node) user_portfolio.add_stock(new_node) # display investment mix as selected by user print("User Portfolio:") user_portfolio.print_contents() # display investment mix selected using hill climbing print("\nHill Climbing Portfolio:") hc_obj = HillClimbing(hc_portfolio) hc_obj.hill_climbing() hc_portfolio = hc_obj.best_portfolio hc_portfolio.print_contents() # display investment mix selected using simulated annealing print("\nSimulated Annealing Portfolio:") sa_obj = SimulatedAnnealing(sa_portfolio) sa_obj.simulated_annealing() sa_portfolio.print_contents()