def simple_grasp_run(args):
    global seed
    problem, alpha, k, max_it, no_upt, start_incr, max_time, solve = args
    print('GRASP Started: Problem: ', problem.instance_name)
    grasp = GRASP(problem, seed, None)
    parameters: dict = {
        "alpha": alpha,
        "k": k,
        "max_it": max_it,
        "no_upt": no_upt,
        "start_incr": start_incr,
        "max_time": max_time,
        "start_solve": solve
    }
    start_time = time.time()
    grasp_tour, step, last_update = grasp.run(parameters)
    end_time = time.time()
    grasp_cost = problem.evaluate(grasp_tour)
    print('GRASP Done: Problem: ', problem.instance_name)
    return grasp_cost, end_time - start_time, grasp_tour, step, last_update
Exemple #2
0
    results = np.zeros((len(s_arr), len(m_arr), len(var_arr), num_trials))

    for i, s in enumerate(s_arr):
        for j, m in enumerate(m_arr):
            print(j)
            for k, sigma in enumerate(var_arr):
                for l in range(num_trials):
                    indices = np.random.choice(n, s, replace=False)
                    theta = np.zeros((n, 1))
                    theta[indices, :] = np.random.randn(s, 1)
                    theta = theta / np.linalg.norm(2)
                    A = np.random.rand(m, n)
                    y = A @ theta + sigma * np.random.randn(m, 1)
                    abs_tol = math.sqrt(4 * n) * sigma * np.linalg.norm(theta)
                    theta_recon = GRASP(A, y, s, abs_tol)
                    # print(rmse(theta, theta_recon))
                    results[i, j, k, l] = rmse(theta, theta_recon)

    results_median = np.median(results, axis=-1)
    for i, s in enumerate(s_arr):
        plt.figure()
        plt.title("Sparsity level: " + str(s))
        im = plt.imshow(results_median[i, :, :])
        ax = plt.gca()
        ax.set_xticks(np.arange(len(var_arr)))
        ax.set_yticks(np.arange(len(m_arr)))
        # ... and label them with the respective list entries.
        ax.set_xticklabels(var_arr * 100)
        ax.set_yticklabels(m_arr)
        ax.set_xlabel("Relative Intensity of Noise")
if __name__ == "__main__":
    data_path = "./data/"

    sigma = 0.01
    img_array = cv2.imread(data_path + "clown.bmp", 0)
    plt.figure()
    plt.title("Original Image")
    plt.imshow(img_array, cmap='gray')
    plt.show()
    assert img_array.shape[0] == img_array.shape[1]
    n = img_array.shape[0]
    Phi = getDCTBasis(n)
    m = 300

    theta = Phi.T @ img_array  # Id DCT of columns
    theta_recon = np.zeros((n, n))

    for i in range(n):
        print(i)
        col = np.expand_dims(theta[:, i], axis=1)
        A = np.random.rand(m, n) @ Phi
        y = A @ col + sigma * np.linalg.norm(col) * np.random.randn(m, 1)
        abs_tol = math.sqrt(4 * n) * sigma * np.linalg.norm(col)
        col_recon = GRASP(A, y, 100, abs_tol)
        theta_recon[:, i] = col_recon.squeeze()
    img_recon = Phi @ theta_recon  # 1D IDCT of cols
    plt.figure()
    plt.title("Reconstructed Image")
    plt.imshow(img_recon, cmap='gray')
    plt.show()
    print("Image reconstruction error: ", rmse(theta, theta_recon))
Exemple #4
0
        problem.distance_matrix[line, line] = 0

    random_tour = problem.random_solve(seed)
    print('random tour:', random_tour)
    print('random tour cost:', problem.evaluate(random_tour))

    local_search = LocalSearch(problem)
    local_search_tour = local_search.search(random_tour, 1)
    print('local_search tour:', local_search_tour)
    print('local_search tour cost:', problem.evaluate(local_search_tour))

    greed_tour = GreedSearch.search(problem)
    print('greed tour:', greed_tour)
    print('greed tour cost:', problem.evaluate(greed_tour)) 

    vns = VariableNeighborhoodSearch(problem, None, seed)
    vns_tour, step, last_update = vns.run(3, 100, 10, max_exec_time_per_run_in_seconds, greed_tour)
    print('vns tour cost:', problem.evaluate(vns_tour))
    print('total steps', step)
    print('last update', last_update)

    grasp = GRASP(problem, None, seed)
    grasp_tour, step, last_update = grasp.run(0.0, 2, 100, 50, 5, max_exec_time_per_run_in_seconds, greed_tour)
    print('grasp tour cost:', problem.evaluate(grasp_tour))
    print('total steps', step)
    print('last update', last_update)

    genetic = Genetic(problem, seed)
    genetic_tour, step = genetic.run(2, 0.8, 0.1, 50, 100, max_exec_time_per_run_in_seconds, greed_tour)
    print('genetic tour cost:', problem.evaluate(genetic_tour))
    print('total steps', step)
        )
        print("O número máximo de execuções que podem rodar em paralelo")
        print("O nome do arquivo de saida com os resultados")
        sys.exit(1)

    with open(sys.argv[1]) as f:
        config = json.load(f)
    with open(sys.argv[3]) as f:
        parameters = json.load(f)

    if sys.argv[2] == "genetic":
        alg = Genetic(None, None)
    elif sys.argv[2] == "vns":
        alg = VariableNeighborhoodSearch(None, None, None)
    elif sys.argv[2] == "grasp":
        alg = GRASP(None, None, None)
    else:
        print(
            "O nome do algoritmo informado é inválido, escolhar entre: 'genetic', 'vns' e 'grasp'"
        )
        sys.exit(1)

    n_cores = int(sys.argv[4])
    result_file_name = sys.argv[5]

    Problem.files_path = '30 selected instances/'

    problems = [Problem(x) for x in config["instances"]]

    grid = GridSearch(n_cores, alg, problems,
                      [GreedSearch.search(p) for p in problems],
Exemple #6
0
        s = []
        inicial_r = FLSol(i)
        if (inicial_r.M > 100):
            continue
        print(i.nome)
        print("N:", inicial_r.N, " M:", inicial_r.M)

        hc = HC()
        vnd = VND()
        rms = RMS()
        ils = ILS()
        vns = VNS()
        sa = SA()
        gls = GLS()
        ag = AG()
        grasp = GRASP()

        # Ponto inicial guloso
        inicial_g = FLSol(i)
        tempo = time.perf_counter()
        inicial_g.build_greedy()
        sb = cp.deepcopy(inicial_g)
        tempo = time.perf_counter() - tempo
        s.append(["PTG", sb.avaliacao(), tempo])

        # # Ponto inicial Randomico
        tempo = time.perf_counter()
        inicial_r.build_random()
        tempo = time.perf_counter() - tempo
        sb = cp.deepcopy(inicial_r)
        s.append(["PTR", sb.avaliacao(), tempo])
Exemple #7
0
import sys

sys.path.append('../src')

from QuadraticKnapsack01Strategy import QuadraticKnapsack01Strategy
import QKPInstanceReader as QKPreader
from GRASP import GRASP

instance = QKPreader.read('../Data/test/example_input.txt', 0.8)
g = GRASP(strategy=instance)
out = g.run(maxIterations=1000, bestSolutionOF=1609)
print(out)
Exemple #8
0
    'jeu_300_50_5.txt': 727820,
    'jeu_300_50_6.txt': 734053,
    'jeu_300_50_7.txt': 43595,
    'jeu_300_50_8.txt': 767977,
    'jeu_300_50_9.txt': 761351,
    'jeu_300_50_10.txt': 996070
}

matching = '100_25'
iterations = 10
alpha = 0.8

print(len(sys.argv))

if len(sys.argv) > 1:
    matching = sys.argv[1]
if len(sys.argv) > 2:
    iterations = int(sys.argv[2])
if len(sys.argv) > 3:
    aplha = float(sys.argv[3])

instances = os.listdir(input_dir)
for instance in instances:
    if matching in instance:
        qpk_instance = QKPreader.read(input_dir + '/' + instance, alpha)
        g = GRASP(strategy=qpk_instance)
        out = g.run(maxIterations=iterations,
                    bestSolutionOF=bestSolutionsOF[instance])
        print(instance + ', ' + str(out[1]) + ', ' + str(out[2]) + ', ' +
              str(bestSolutionsOF[instance]))