예제 #1
0
def vnd_method(initial_solution,
               methods,
               has_animation=False,
               title="VND Method"):
    """Search a new solution for TSP with VND method

    Arguments:
        initial_solution {list} -- initial solution
        methods {list} -- list with the sequence of the methods to be used

    Keyword Arguments:
        has_animation {bool} -- if will the animate the search (default: {False})
        title {str} -- title of the animation (default: {"Best Improvement Method"})

    Returns:
        list -- the founded solution
    """
    current_solution = copy(
        initial_solution)  # Copy initial solution as current solution
    # Caculate the cost of the solution
    min_cost = calculate_cost(initial_solution)
    k = 0
    methods_dict = {'swap': swap_method, '2opt': two_opt_method}

    while k < len(methods):

        # Search the best solution in the neighborhood
        is_first = True if 'fi' in methods[k] else False
        selected_method = ""

        if 'swap' in methods[k]:
            selected_method = 'swap'
        elif '2opt' in methods[k]:
            selected_method = '2opt'

        best_candidate = methods_dict[selected_method](
            current_solution,
            is_first=is_first,
            has_animation=has_animation,
            title=title)
        # Calculate the candidate's cost
        candidate_cost = calculate_cost(best_candidate)

        # Check if the candidate's cost is the lowest
        if candidate_cost < min_cost:
            # Define the candidate solution as the current solution
            current_solution = best_candidate
            min_cost = candidate_cost  # Define the candidate's cost as the lowest
            k = 0  # Reboot the count
        else:
            k += 1  # Add 1 if not improve

    return current_solution
예제 #2
0
def grasp_method(initial_solution,
                 vnd_methods,
                 instance,
                 interations=5,
                 has_animation=False,
                 title="VNS Method"):
    """Search a new solution for TSP with VND method

    Arguments:
        initial_solution {list} -- initial solution
        methods {list} -- list with the sequence of the methods to be used

    Keyword Arguments:
        has_animation {bool} -- if will the animate the search (default: {False})
        title {str} -- title of the animation (default: {"Best Improvement Method"})

    Returns:
        list -- the founded solution
    """
    current_solution = copy(
        initial_solution)  # Copy initial solution as current solution
    # Caculate the cost of the solution
    min_cost = calculate_cost(initial_solution)
    k = 0
    size = len(current_solution)
    construction = ConstructionHeuristic()

    while k < interations:
        i = random.randint(0, size - 1)

        initial_candidate = construction.construct_nearest(instance, i)

        candidate_solution = vnd_method(initial_candidate, vnd_methods,
                                        has_animation, title)

        # Calculate the candidate's cost
        candidate_cost = calculate_cost(candidate_solution)

        # Check if the candidate's cost is the lowest
        if candidate_cost < min_cost:
            # Define the candidate solution as the current solution
            current_solution = candidate_solution
            min_cost = candidate_cost  # Define the candidate's cost as the lowest
            k = 0  # Reboot the count
        else:
            k += 1  # Add 1 if not improve

    return current_solution
예제 #3
0
def vnd_method(solucao_inicial, metodos, menor_custo):
    
    solucao_atual = copy(
        solucao_inicial)       # Copia a solução inicial
   
    k = 0
    methods_dict = {'swap': swap_method, '2opt': two_opt_method, '1opt': one_opt_method}

    while k < len(metodos):
        # Procura a melhor solução usando os algorítmos de vizinhança
        metodo_selecionado = ""

        if k == 0:
            metodo_selecionado = 'swap'
        elif k == 1:
            metodo_selecionado = '2opt'
        elif k == 2:
            metodo_selecionado = '1opt'

        melhor_candidato = methods_dict[metodo_selecionado](solucao_atual)
        # Calcula o custo da nova solução encontrada
        custo_candidato = calculate_cost(melhor_candidato)

        # Verifica se a solução encontrada é melhor, se for, repete o while
        #com k=0, caso contrário, ele soma k+1 e testa o proximo
        #método de vizinhança até k=3 e sai do laço com a resposta ótima
        if custo_candidato < menor_custo:
            solucao_atual = melhor_candidato
            menor_custo = custo_candidato       
            k = 0       # Reinicia a contagem
        else:
            k += 1      # Próximo algorítmo

    return solucao_atual
예제 #4
0
def two_opt_method(initial_solution,
                   is_first=False,
                   has_animation=False,
                   title="2-OPT Method"):
    """Search a new solution for TSP with 2-OPT method

    Arguments:
        initial_solution {list} -- initial solution

    Keyword Arguments:
        is_first {bool} -- if will use the First Improvement (default: {False})
        has_animation {bool} -- if will the animate the search (default: {False})
        title {str} -- title of the animation (default: {"Best Improvement Method"})

    Returns:
        list -- the founded solution
    """
    current_solution = copy(
        initial_solution)  # Copy initial solution as current solution
    # Caculate the cost of the solution
    min_cost = calculate_cost(initial_solution)
    size_points = len(initial_solution)  # Get the number of points
    has_improvement = True  # Check if has improvement
    has_points = current_solution[0].point != None

    while has_improvement:
        has_improvement = False

        for i in range(size_points - 1):
            for j in range(i + 1, size_points):

                # Swap
                candidate_cost = min_cost + \
                    calculate_swap_cost(current_solution, i, j, True)

                # Check if the candidate's cost is the lowest
                if candidate_cost < min_cost:
                    has_improvement = True
                    min_cost = candidate_cost  # Change the lowest cost
                    # Change the best solution
                    current_solution = swap_2opt(current_solution, i, j)

                    if is_first:
                        break

            if has_animation:
                plot_animated(current_solution,
                              title=title,
                              has_points=has_points,
                              show_key=(not has_points))

            if is_first and has_improvement:
                break

    return current_solution
예제 #5
0
파일: run.py 프로젝트: Vnicius/ed-tsp
def main_table(args):
    reader = InstanceReader()
    instance = reader.get_instance(args.instance)
    construction = ConstructionHeuristic()
    initial_solution = []
    times = []
    costs = []
    instance_name = path.split(args.instance)[-1].split('.')[0]

    if args.method == 'all':
        for _ in range(10):

            if args.construction == 'nearest':
                t = time()
                initial_solution = construction.construct_nearest(instance)
            elif args.construction == 'random':
                t = time()
                initial_solution = construction.construct_random(instance)

            times.append(time() - t)
            costs.append(calculate_cost(initial_solution))
    else:
        if args.construction == 'nearest':
            initial_solution = construction.construct_nearest(instance)
        elif args.construction == 'random':
            initial_solution = construction.construct_random(instance)

    if args.method in ['swap', 'all']:

        title = 'Swap Improvement Method'

        for i in range(10):
            t = time()

            swap = swap_method(initial_solution,
                               is_first=(args.improvement == 'first'),
                               has_animation=args.animate,
                               title=title)

            times.append(time() - t)
            costs.append(calculate_cost(swap))

    if args.method in ['2opt']:

        title = '2-OPT Method'

        for i in range(10):
            t = time()

            two_opt_solution = two_opt_method(
                initial_solution,
                is_first=(args.improvement == 'first'),
                has_animation=args.animate,
                title=title)

            times.append(time() - t)
            costs.append(calculate_cost(two_opt_solution))

    if args.method in ['vnd']:

        title = 'VND Method'

        for i in range(10):
            t = time()

            vnd_solution = vnd_method(initial_solution,
                                      args.vnd_methods,
                                      has_animation=args.animate,
                                      title=title)

            times.append(time() - t)
            costs.append(calculate_cost(vnd_solution))

    if args.method in [
            'vns',
    ]:

        title = 'VNS Method'

        for i in range(10):
            t = time()

            vns_solution = vns_method(initial_solution,
                                      args.vnd_methods,
                                      interations=args.number_interations,
                                      has_animation=args.animate,
                                      title=title)

            times.append(time() - t)
            costs.append(calculate_cost(vns_solution))

    if args.method in ['grasp']:

        title = 'GRASP Method'

        for i in range(10):
            t = time()

            grasp_solution = grasp_method(initial_solution,
                                          args.vnd_methods,
                                          instance,
                                          interations=args.number_interations,
                                          has_animation=args.animate,
                                          title=title)

            times.append(time() - t)
            costs.append(calculate_cost(grasp_solution))

    print(
        f'{instance_name}, {args.optimal}, {np.around(np.mean(costs), 5)}, {np.min(costs)}, {np.around(np.mean(times), decimals=5)}, {np.around(best_gap(costs, args.optimal), 5)}'
    )
예제 #6
0
파일: run.py 프로젝트: Vnicius/ed-tsp
def main(args):
    reader = InstanceReader()
    instance = reader.get_instance(args.instance)
    construction = ConstructionHeuristic()
    initial_solution = []

    if args.construction == 'nearest':
        initial_solution = construction.construct_nearest(instance)
    elif args.construction == 'random':
        initial_solution = construction.construct_random(instance)

    print("INITIAL: ", solution_to_string(initial_solution))
    print("INITIAL COST: ", calculate_cost(initial_solution))

    if args.method in ['swap', 'all']:

        title = 'Best Improvement Method'
        swap = swap_method(initial_solution,
                           is_first=(args.improvement == 'first'),
                           has_animation=args.animate,
                           title=title)
        print()
        print("SWAP METHOD: ", solution_to_string(swap))
        print("SWAP METHOD COST: ", calculate_cost(swap))

        if args.plot:
            plot_solution(swap, title)

    if args.method in ['2opt', 'all']:

        title = '2-OPT Method'
        two_opt_solution = two_opt_method(
            initial_solution,
            is_first=(args.improvement == 'first'),
            has_animation=args.animate,
            title=title)
        print()
        print("2-OPT METHOD: ", solution_to_string(two_opt_solution))
        print("2-OPT METHOD COST: ", calculate_cost(two_opt_solution))

        if args.plot:
            plot_solution(two_opt_solution, title)

    if args.method in ['vnd', 'all']:

        title = 'VND Method'
        vnd_solution = vnd_method(initial_solution,
                                  args.vnd_methods,
                                  has_animation=args.animate,
                                  title=title)
        print()
        print("VND METHOD: ", solution_to_string(vnd_solution))
        print("VND METHOD COST:", calculate_cost(vnd_solution))

        if args.plot:
            plot_solution(vnd_solution, title)

    if args.method in ['vns', 'all']:

        title = 'VNS Method'
        vns_solution = vns_method(initial_solution,
                                  args.vnd_methods,
                                  interations=args.number_interations,
                                  has_animation=args.animate,
                                  title=title)
        print()
        print("VNS METHOD: ", solution_to_string(vns_solution))
        print("VNS METHOD COST:", calculate_cost(vns_solution))

        if args.plot:
            plot_solution(vns_solution, title)

    if args.method in ['grasp', 'all']:

        title = 'GRASP Method'
        grasp_solution = grasp_method(initial_solution,
                                      args.vnd_methods,
                                      instance,
                                      interations=args.number_interations,
                                      has_animation=args.animate,
                                      title=title)
        print()
        print("GRASP METHOD: ", solution_to_string(grasp_solution))
        print("GRASP METHOD COST:", calculate_cost(grasp_solution))

        if args.plot:
            plot_solution(grasp_solution, title)