def accept(ini_solution, ini_solution_fmed, new_solution, t, data): pre = ini_solution_fmed post = opt_fmed(new_solution, data) p = np.exp((-(post - pre) / t)) if post < pre: return new_solution, post elif np.random.random() < p: return new_solution, post else: return ini_solution, pre
def local_best_first_search(solution, solution_fmed, data, time_limit): """ Búsqueda local del primer mejor. """ t_end = time.time() + time_limit best_solution = solution best_fmed = solution_fmed while time.time() < t_end: target_fmed = best_fmed for neighbour in generate_neighbours(best_solution): neighbour_fmed = opt_fmed(neighbour, data) if neighbour_fmed < best_fmed: best_solution, best_fmed = neighbour, neighbour_fmed if target_fmed == best_fmed: break return best_solution, best_fmed
def local_best_search(solution, solution_fmed, data, time_limit): """ Búsqueda local del mejor. """ best_fmed = solution_fmed best_solution = solution t_end = time.time() + time_limit while time.time() < t_end: for neighbour in generate_neighbours(best_solution): if time.time() < t_end: neighbour_fmed = opt_fmed(neighbour, data) if neighbour_fmed <= best_fmed: best_solution, best_fmed = neighbour, neighbour_fmed else: return best_solution, best_fmed return best_solution, best_fmed
def simulated_annealing(tries, t_ini_factor, alpha, solution, time_, data): # Bucle de 60 segundos t_end = time.time() + time_ - 0.1 solution_fmed = opt_fmed(solution, data) #t = solution_fmed * t_ini_factor t = t_ini_factor while time.time() < t_end: for i in range(tries): # Tries before getting t down vecino = get_neighbour(solution) solution, solution_fmed = accept(solution, solution_fmed, vecino, t, data) step = t * alpha / 100 # Baja la temperatura un alpha% if t - step > 0.1: t -= step return solution, solution_fmed
Reordena una matriz de costes (f) para comparar mi solución con las de los casos de prueba. """ ordered_mat = np.zeros_like(cost_matrix) i = 0 for step in sol: ordered_mat[step] = cost_matrix[i] i += 1 return ordered_mat # timeit.timeit('read_file("ProblemasFlowShopPermutacional/Doc11.txt")', setup="from __main__ import read_file", number=100000) sol_doc1_mat = np.loadtxt("Tests/SolDoc1_Mat.txt", usecols=range(5), dtype=int) sol_doc1_vec = np.loadtxt("Tests/SolDoc1_Vec.txt", usecols=range(11), dtype=int) sol_doc2_mat = np.loadtxt("Tests/SolDoc2_Mat.txt", usecols=range(4), dtype=int) sol_doc2_vec = np.loadtxt("Tests/SolDoc2_Vec.txt", usecols=range(13), dtype=int) sol_doc1_vec = [a-1 for a in sol_doc1_vec] sol_doc2_vec = [a-1 for a in sol_doc2_vec] doc1 = read_file("Datasets/Doc1.txt") doc2 = read_file("Datasets/Doc2.txt") print(reorder(opt_fmed(sol_doc1_vec, doc1)[1], sol_doc1_vec) == sol_doc1_mat) print(reorder(opt_fmed(sol_doc2_vec, doc2)[1], sol_doc2_vec) == sol_doc2_mat) print(reorder(opt_fmed(sol_doc1_vec, doc1)[1], sol_doc1_vec)) print(sol_doc1_mat) print(reorder(opt_fmed(sol_doc2_vec, doc2)[1], sol_doc2_vec)) print(sol_doc2_mat)