def test_grasp(): _, graph = generate_graph(100, 0.5) solution = grasp(graph, use_path_relinking=False) print(solution.colors_count, solution.node_order) solution = grasp(graph, use_path_relinking=True) print(solution.colors_count, solution.node_order)
def main(): global BEST nodes, temp = rgt.read("../graphs/graph_random_5.txt") signal.signal(signal.SIGALRM, handler) all_edge = [] plot_all_edge = [] plot_solution = [] counter = 0 for t in temp: c, a, b = t.split(" ") e = Edge.Edge(a, b, c) all_edge.append(e) gr_start = timeit.default_timer() grasp_tree, grasp_cost, mincost = gra.grasp(nodes, temp) gr_stop = timeit.default_timer() print('Tree cost graph: ' + str(grasp_cost) + ' | time_GRASP: ' + str(gr_stop - gr_start) + '\n' + 'Dijkstra cost: ' + str(mincost)) print('\n--- GRASP ---\n') print_array(grasp_tree) print('') time = 0 j = 0 start = timeit.default_timer() signal.setitimer(signal.ITIMER_REAL, 100, 50) grasp_tree, bb = heu_cut(grasp_tree, all_edge, nodes) stop = timeit.default_timer() BEST = bb time = stop - start print('Cost_grasp: ' + str(mincost) + ' -------> cost_LS: ' + str(bb) + ' | time_LS: ' + str(time)) best_cost = bb for i in range(15): start = timeit.default_timer() grasp_tree, bb = heu_cut(grasp_tree, all_edge, nodes) stop = timeit.default_timer() time = time + (stop - start) print('Cost_grasp: ' + str(mincost) + ' -------> cost_LS: ' + str(bb) + ' | time_LS: ' + str(time)) if (j != 4): if (bb > best_cost or bb == best_cost): j += 1 best_cost = bb elif (bb < best_cost): best_cost = bb BEST = best_cost j = 0 else: break print('\n--- LS ---\n') print_array(grasp_tree) for e in all_edge: v1, v2 = (e.v1, e.v2) plot_all_edge.append((v1, v2)) for e in grasp_tree: v1, v2 = (e.v1, e.v2) plot_solution.append((v1, v2))
def solve_for_multiple(): percentages = [0.1, 0.3, 0.5] for p in percentages: # print("Percetage of total capacitance:" , p) t = time.time() print( grasp(Solution, [lambda x: x * p, f_p, g], Neighbourhood, max_it=2)) times.append(time.time() - t)
def main(): # Read all instances and store it in an array of TSPFile objects tsp_files = compute_tsp_instances() # For each instance apply some heuristic based on christofides algorithm for tsp_file in tsp_files: # Set of expensive edges visited pairs_visited = [False] * tsp_file.dimension for i in range(tsp_file.dimension): pairs_visited[i] = [False] * tsp_file.dimension # Set of root nodes visited roots_visited = [False] * tsp_file.dimension # Capture the initial time start_time = time.time() # Get the cycle by christofides's algorithms euler_cycle = christofides(tsp_file) # Apply a Variable Neighborhood Descent metaheuristic to improve the current solution euler_cycle = variable_neighborhood_descent(tsp_file, euler_cycle, 100, pairs_visited, roots_visited) # Apply a Tabu Search metaheuristic to improve the current solution memory_size = tsp_file.dimension tabu_search_algorithm = TabuSearch(memory_size, tsp_file, euler_cycle) euler_cycle = tabu_search_algorithm.tabu_search() # # Apply a Greedy Randomized Adaptative Search Procedure Meteheuristic to improve current solution grasp_instance = grasp(tsp_file, euler_cycle) euler_cycle = grasp_instance.grasp() # Apply a Iterated Local Search Meteheuristic to improve current solution. # The perturbation function works 2 minutes in an attempt to improve current solution. # It apply a cut with a fixed length in current solution and apply a nearest neighborhood # heuristic in the nodes inside that cut. ils_instance = ils(tsp_file, euler_cycle) euler_cycle = ils_instance.ils() # Capture the final time elapsed_time = time.time() - start_time # Present the final solution for the user show_final_solution(tsp_file, euler_cycle, elapsed_time)
def menuMetaHeuristics(dimension, distances): util.line() print("Meta-heurísticas:") util.line("-") print("1 - Multi-start") print("2 - GRASP") print("3 - Simulated Annealing") print("4 - Busca Tabu") print("5 - VNS") print("6 - Iterated Local Search") print("7 - Algoritmos genéticos") print("8 - Colônia de Formigas") print("9 - Scatter Search") print("0 - Voltar") choice = int(input("Opção: ")) util.line() solution = [] cost = sys.maxsize if choice == 1: # Multi-start iterMax = int( input( "Defina o número máximo de iterações sem melhora (critério de parada): " )) solution, cost = multistart.multiStart(dimension, distances, iterMax) print("Solução: ", solution) print("Custo: ", cost) elif choice == 2: # GRASP graspMax = int( input("Defina o número máximo de iterações (GRASPmax): ")) alpha = float(input("Informe um valor para alpha [0; 1]: ")) solution, cost = grasp.grasp(dimension, distances, graspMax, alpha) print("Solução: ", solution) print("Custo: ", cost) else: print("Metodo ainda não implementado.") return solution, cost
def hybrid_ga(nodes, vehicles, gen=5, l=3, p_mut=0.4, people=60): sols, complete_nodes, complete_vehicles = grasp( nodes, vehicles, k=people) # Initial solutions j = 0 selected_sols = sols while j < gen: selected_sols, selected_nodes, selected_vehicles = tournament( selected_sols, complete_vehicles, complete_nodes) # Selection by tournament while len(selected_sols) < people: index_sol = random.randint(0, len(selected_sols) - 1) for k in range(l): child, node, vehicle = one_point_crossover( selected_sols[index_sol], selected_nodes[index_sol], selected_vehicles[index_sol]) if child is not None: z_child = of(vehicle, node, child) if random.random() < p_mut: # Mutation child, vehicle, node = mutation(child, vehicle, node) selected_sols.append(child) selected_nodes.append(node) selected_vehicles.append(vehicle) break j += 1 j = 0 best_z = np.Inf best_sol = [] index = [i for i in range(len(selected_sols))] selected_sols_aux = list(zip(index, selected_sols)) selected_sols_aux = random.sample(selected_sols_aux, 10) for t in selected_sols_aux: sol = t[1] i = t[0] sol, z = vnd(sol, selected_nodes[i], selected_vehicles[i], best_z) # Local search if z < best_z: best_z = z best_sol = sol j += 1 return best_sol, best_z
def main(): instances = [] instances.append("Instances/frb30-15-1.clq") instances.append("Instances/frb30-15-2.clq") instances.append("Instances/frb30-15-3.clq") instances.append("Instances/frb30-15-4.clq") instances.append("Instances/frb30-15-5.clq") ''' instances.append("Instances/frb45-21-1.clq") instances.append("Instances/frb45-21-2.clq") instances.append("Instances/frb45-21-3.clq") instances.append("Instances/frb45-21-4.clq") instances.append("Instances/frb45-21-5.clq") ''' for instance in instances: vertices, edges = readFile(instance) graph = grasp.createMatrixGraph(vertices, edges) graph = grasp.getGraphComplement(graph) edges = grasp.getComplementEdges(graph) begin = time.time() clique = grasp.grasp(20, vertices, edges) end = time.time() excTime = end - begin file = open( "Output/" + instance.replace("Instances/", "").replace(".clq", "") + ".txt", "w") file.write("FILE: " + instance.replace("Instances/", "") + "\n") file.write("MAX CLIQUE: " + str(len(clique)) + "\n") file.write("EXECUTED TIME: " + str(excTime) + "s" + "\n") print "Maximum clique: " + str(len(clique)) print "Clique vertices: ", clique print "Executed in: " + str(excTime) + " secs"
def run_test_grasp(verbose): opt_value = [] # Lista para os valores encontrados opt_time = [] # Lista para os tempos encontrados i = 0 for problem in problems: # Executando o algoritmo state, size, value, time = grasp(max_size=problem[0], values=problem[1], max_iter=hiperparam[0], num_best=hiperparam[1], max_time=300) # Print caso queira acompanhar if verbose: print('Problem', problem_name[i], 'finished with (opt_value, opt_size, time) equals', (value, size, time)) # Salvando os melhores valores opt_value.append(value) opt_time.append(time) i = i + 1 mean_value = np.mean(opt_value) std_value = np.std(opt_value) mean_time = np.mean(opt_time) std_time = np.std(opt_time) # Print caso queira acompanhar if verbose: print('The mean and std for the values found were:', mean_value, '+-', std_value) print('The mean and std for the times found were:', mean_time, '+-', std_time) return opt_value, opt_time, [mean_value, std_value, mean_time, std_time]
def run_experiment(input_filename, alpha=0.8, max_iterations=1000, max_time_in_seconds=None): with open(input_filename) as file_handle: data = json.loads(file_handle.read()) data["stop_after_some_time"] = False if max_time_in_seconds is None: print( f"Input filename={input_filename}, alpha={alpha}, max_iter = {max_iterations}" ) best_solution, best_cost_solution, time_computing, iters = grasp( problem_cost_function, alpha, greedy_cost_function, max_iterations, data) visualize_solution(data, best_solution) print(f"Best cost of solution is {best_cost_solution}") print(f"Time computing: {time_computing}s") print(f"Iterations: {iters}") else: data["quit_computing"] = False threading.Timer(max_time_in_seconds, lambda x: quit_computing(data)).start() print( f"Input filename={input_filename}, alpha={alpha}, max_time = {max_time_in_seconds} seconds" ) best_solution, best_cost_solution, time_computing, iters = grasp_by_max_time( problem_cost_function, alpha, greedy_cost_function, max_time_in_seconds, data) visualize_solution(data, best_solution) print(f"Best cost of solution is {best_cost_solution}") print(f"Time computing: {time_computing}s") print(f"Iterations: {iters}")
def run_experiment(input_filename, alpha=0.8, max_iterations=1000, max_time_in_seconds=None): with open(input_filename) as file_handle: data = json.loads(file_handle.read()) if max_time_in_seconds is None: print( f"Input filename={input_filename}, alpha={alpha}, max_iter = {max_iterations}" ) best_solution, best_cost_solution, time_computing, iters = grasp( problem_cost_function, alpha, greedy_cost_function, max_iterations, data) visualize_solution(data, best_solution) print(f"Best cost of solution is {best_cost_solution}") print(f"Time computing: {time_computing}s") print(f"Iterations: {iters}") write_results(data, best_cost_solution, iters, time_computing, input_filename, alpha) else: print( f"Input filename={input_filename}, alpha={alpha}, max_time = {max_time_in_seconds} seconds" ) best_solution, best_cost_solution, time_computing, iters = grasp_by_max_time( problem_cost_function, alpha, greedy_cost_function, max_time_in_seconds, data) visualize_solution(data, best_solution) print(f"Best cost of solution is {best_cost_solution}") print(f"Time computing: {time_computing}s") print(f"Iterations: {iters}") write_results(data, best_cost_solution, iters, time_computing, input_filename, alpha)
def hybrid_ga_vnd(nodes, vehicles, gen=5, l=3, p_mut=0.4, people=60): sols, complete_nodes, complete_vehicles = grasp( nodes, vehicles, k=people) # Initial solutions j = 0 selected_sols = sols while j < gen: selected_sols, selected_nodes, selected_vehicles = tournament( selected_sols, complete_vehicles, complete_nodes) # Selection by tournament while len(selected_sols) < people: index_sol = random.randint(0, len(selected_sols) - 1) for k in range(l): child, node, vehicle = one_point_crossover( selected_sols[index_sol], selected_nodes[index_sol], selected_vehicles[index_sol]) if child is not None: z_child = of(vehicle, node, child) if random.random() < p_mut: # Mutation child, vehicle, node = mutation(child, vehicle, node) child, z_child = vnd(child, node, vehicle, z_child) # Local search selected_sols.append(child) selected_nodes.append(node) selected_vehicles.append(vehicle) break j += 1 j = 0 best_z = np.Inf best_sol = [] for sol in selected_sols: z = of(selected_vehicles[j], selected_nodes[j], sol) if z < best_z: best_z = z best_sol = sol j += 1 return best_sol, best_z
step_fnc = best_improvement elif step_fnc_str == 'first_improvement': step_fnc = first_improvement elif step_fnc_str == 'random': step_fnc = random if step_fnc == None: logging.error('Local search step function should be: best_improvement, first_improvement or random') exit(-1) solution = construct_deterministic(edgelist, sorted_edgelist, len(edgelist), k, L, M) solution = local_search(solution, step_fnc, neighborhood_factory, local_iterations, delta_eval) elif heuristic == "grasp": alpha = 0.1 random_constructor = construct_randomized_greedy_from_given_inputs(edgelist, sorted_edgelist, len(edgelist), k, L, alpha) grasp_local_search = local_search_partially_applied(best_improvement, neighborhood_factory, local_iterations, delta_eval) solution = grasp(random_constructor, grasp_local_search, grasp_iterations) elif heuristic == "vnd": # vnd_neighborhood_fac is reset, so the exact type is unimportant vnd_neighborhood_fac = NeighborhoodFactory(edgelist) solution = construct_deterministic(edgelist, sorted_edgelist, len(edgelist), k, L, M) solution = vnd(solution, vnd_neighborhood_fac, delta_eval) elif heuristic == "gvns": if sys.argv[2] == "sbm" or sys.argv[2] == "ShortBlockMove" or sys.argv[2] == 'r' or sys.argv[2] == "Reversal": print("That neighborhood is not currently supported") exit() # vnd_neighborhood_fac is reset, so the exact type is unimportant vnd_neighborhood_fac = NeighborhoodFactory(edgelist) solution = construct_deterministic(edgelist, sorted_edgelist, len(edgelist), k, L, M)
# This files are in the src folder from grasp import grasp from figure import plotly_figure_1 data = pd.read_csv('heuristic/ubicaciones.csv') evalu = loadtxt('heuristic/evalu.txt') evalu = evalu.tolist() # Sección de introducción st.title("Optimización de Territorios Usando Heurística GRASP") st.write(""" Bienvenid@ a este ejemplo que ejecuta un modelo Grasp. """) # Sección de datos st.write(""" A continuación los datos utilizados. """) st.dataframe(data.head()) # Especificación de datos st.sidebar.markdown(""" # Especificamos los Dias de Entrega: """) n_days = st.sidebar.slider("Número de Días de Entrega", 3, 6, 4, 1) asig = grasp(data, evalu, n_days) # Sección de datos st.write(""" Veamos los clusters de clientes divididos por Día de Entrega. """) fig = plotly_figure_1(data, asig) st.plotly_chart(fig)
) # lista de alunos no formato exigido para imprimir o relatório total_removed_materials = dict( ) # key: material removido, value: quantidades de vezes total_added_materials = dict( ) # key: material removido, value: quantidades de vezes key: material adicionado, value: quantidades de vezes removed_materials_concepts = defaultdict( set) # key: material removido, value: todos conceitos retirados added_materials_concepts = defaultdict( set) # key: material adicionado, value: todos conceitos adicionados for student in initialSolution.students_list: if (student.fitnessConcepts != 0.0): problem = DiscreteOpt(student) materials_concepts, fitness = grasp(problem, max_Iterations=100, alfa=0.8, seed=0) with open(os.path.join(dir, 'iteration_log.txt'), 'a') as f: print(f'------ Aluno: {student.student_id}', file=f) modified_materials = list() for index, material_zip in enumerate( zip(student.materials_concepts, materials_concepts)): old_material = material_zip[0] new_material = material_zip[1] removed_concepts = list() added_concepts = list() if not np.array_equal(old_material, new_material):
# This files are in the src folder from grasp import grasp from figure import plotly_figure_1 data = pd.read_csv('heuristic/ubicaciones.csv') evalu = loadtxt('heuristic/evalu.csv', delimiter=',') evalu = evalu.tolist() # Sección de introducción st.title("Optimización de Territorios Usando Heurística GRASP") st.write(""" Bienvenid@ a este ejemplo que ejecuta un modelo Grasp. """) # Sección de datos st.write(""" A continuación los datos utilizados. """) st.dataframe(data.head()) # Especificación de datos st.sidebar.markdown(""" Especificamos los Dias de Entrega: """) n_days = st.sidebar.slider("Número de Días de Entrega", 3.0, 4.0, 6.0, 1.0) asig = grasp(data, evalu, int(n_days)) # Sección de datos st.write(""" Veamos los clusters de clientes divididos por Día de Entrega. """) fig = plotly_figure_1(data, asig) st.plotly_chart(fig)