Esempio n. 1
0
def solve_it(input_data):
    # Modify this code to run your optimization algorithm

    # parse the input
    lines = input_data.split('\n')

    nodeCount = int(lines[0])

    points = []
    for i in range(1, nodeCount + 1):
        line = lines[i]
        parts = line.split()
        points.append(Point(float(parts[0]), float(parts[1])))

    # build a trivial solution
    # visit the nodes in the order they appear in the file
    nodes = range(0, nodeCount)
    iter = 70
    size = 3
    dict_of_neighbours = ts.generate_neighbours(points)
    first_solution, distance_of_first_solution = ts.generate_first_solution(
        nodes, dict_of_neighbours)
    solution, cost = ts.tabu_search(first_solution,
                                    distance_of_first_solution,
                                    dict_of_neighbours,
                                    iter,
                                    size,
                                    n_opt=1)

    # calculate the length of the tour
    obj = length(points[solution[-1]], points[solution[0]])
    for index in range(0, nodeCount - 1):
        obj += length(points[solution[index]], points[solution[index + 1]])

    # prepare the solution in the specified output format
    output_data = '%.2f' % obj + ' ' + str(0) + '\n'
    output_data += ' '.join(map(str, solution))

    return output_data
Esempio n. 2
0
    def test_tabu_search(self):
        best_sol, best_cost = tabu_search(FIRST_SOLUTION, DISTANCE,
                                          NEIGHBOURS_DICT, 4, 3)

        self.assertEquals(['a', 'd', 'b', 'e', 'c', 'a'], best_sol)
        self.assertEquals(87, best_cost)
Esempio n. 3
0
import time

# 读取算例
instance = m_instance.Problem_Instance("text.txt")

# 对tabu、sa生成初始解
solution1 = m_instance.Problem_solution(instance)
solution2 = m_instance.Problem_solution(instance)
# print(solution1)
# print(id(solution1))
# print(solution2)
# print(id(solution2))

# 用各算法求解最大割问题
time0 = time.clock()
tabu_solution = ts.tabu_search(solution1, instance, 0.05, 1000)
time1 = time.clock()
sa_solution = sa.simulated_annealing(solution2, instance)
time2 = time.clock()
ga_solution = ga.genetic_algorithm(instance)
time3 = time.clock()

# 计算算法求解时间
elapse1 = time1 - time0
elapse2 = time2 - time1
elapse3 = time3 - time2

# 绘制各算法对应图象
plot('tabu6.txt')
plot('sa.txt')
plot('ga.txt')
Esempio n. 4
0
    def test_tabu_search(self):
        best_sol, best_cost = tabu_search(FIRST_SOLUTION, DISTANCE, NEIGHBOURS_DICT, 4, 3)

        self.assertEquals(['a', 'd', 'b', 'e', 'c', 'a'], best_sol)
        self.assertEquals(87, best_cost)
Esempio n. 5
0
def simulate(times=10000):
    #Problem bochachevsky
    import test_problems
    wins_tabu = 0
    wins_ant = 0
    draw = 0
    problem = test_problems.bohachevsky()

    eval_tabu = 0
    eval_ant = 0

    results_tabu = 0
    results_ant = 0

    for i in range(0, times):
        r_ant = ant_colony_optimization(problem)
        results_ant += r_ant[1]
        eval_ant += problem.cantEvaluations

        r_tabu = tabu_search(problem)
        results_tabu += r_tabu[1]
        eval_tabu += problem.cantEvaluations

        if r_tabu[1] > r_ant[1]:
            wins_ant += 1
        elif r_tabu[1] == r_ant[1]:
            draw += 1
        else:
            wins_tabu += 1

    print("Bochachevsky Tabu %d Ant %d Draw %d" % (wins_tabu, wins_ant, draw))
    print("Promedio cantidad evaluaciones Tabu: ", eval_tabu / times)
    print("Promedio cantidad evaluaciones Ant: ", eval_ant / times)
    print("Promedio resultados Tabu: ", results_tabu / times)
    print("Promedio resultados Ant: ", results_ant / times)

    wins_tabu = 0
    wins_ant = 0
    draw = 0

    eval_tabu = 0
    eval_ant = 0

    results_ant = 0
    results_tabu = 0

    problem = test_problems.schwefel(2)
    for i in range(0, times):
        r_ant = ant_colony_optimization(problem)
        eval_ant += problem.cantEvaluations
        results_ant += r_ant[1]

        r_tabu = tabu_search(problem)
        eval_tabu += problem.cantEvaluations
        results_tabu += r_tabu[1]

        if r_tabu[1] > r_ant[1]:
            wins_ant += 1
        elif r_tabu[1] == r_ant[1]:
            draw += 1
        else:
            wins_tabu += 1
    print("Scwefel Tabu %d Ant %d Draw %d" % (wins_tabu, wins_ant, draw))
    print("Promedio cantidad evaluaciones Tabu: ", eval_tabu / times)
    print("Promedio cantidad evaluaciones Ant: ", eval_ant / times)
    print("Promedio resultados Tabu: ", results_tabu / times)
    print("Promedio resultados Ant: ", results_ant / times)

    wins_tabu = 0
    wins_ant = 0
    draw = 0

    eval_tabu = 0
    eval_ant = 0

    results_ant = 0
    results_tabu = 0

    for i in range(0, times):
        grafo = generateGraph(20)
        problem = test_problems.traveling_salesman_problem(grafo)

        r_ant = ant_colony_optimization(
            problem,
            surroundings_function=salesman_surroundings,
            randomFunction=salesman_random(grafo))
        eval_ant += problem.cantEvaluations
        results_ant += r_ant[1]

        r_tabu = tabu_search(problem,
                             surroundings_function=salesman_surroundings,
                             randomFuction=salesman_random(grafo))
        eval_tabu += problem.cantEvaluations
        results_tabu += r_tabu[1]

        if r_tabu[1] > r_ant[1]:
            wins_ant += 1
        elif r_tabu[1] == r_ant[1]:
            draw += 1
        else:
            wins_tabu += 1
    print("Traveling salesman Tabu %d Ant %d Draw %d" %
          (wins_tabu, wins_ant, draw))
    print("Promedio cantidad evaluaciones Tabu: ", eval_tabu / times)
    print("Promedio cantidad evaluaciones Ant: ", eval_ant / times)
    print("Promedio resultados Tabu: ", results_tabu / times)
    print("Promedio resultados Ant: ", results_ant / times)
Esempio n. 6
0
import tabu_search as ts
import max_cut_instance as m_instance
import copy
from plot_data import tabu_plots

# 测试不同禁忌长度下的禁忌搜索算法
instance = m_instance.Problem_Instance("text.txt")
solution1 = m_instance.Problem_solution(instance)
solution2 = copy.deepcopy(solution1)
solution3 = copy.deepcopy(solution1)
solution4 = copy.deepcopy(solution1)
solution5 = copy.deepcopy(solution1)
tabu_solution = ts.tabu_search(solution1, instance, 0.04, 1000)
tabu_solution = ts.tabu_search(solution2, instance, 0.08, 1000)
tabu_solution = ts.tabu_search(solution3, instance, 0.16, 1000)
tabu_solution = ts.tabu_search(solution4, instance, 0.24, 1000)
tabu_solution = ts.tabu_search(solution5, instance, 0.32, 1000)
tabu_plots(['tabu{}.txt'.format(i) for i in [5, 10, 20, 30, 40]])
Esempio n. 7
0
import time
import totalno_pretrazivanje as total
import tsp
import myheldkarp
import csv
import tabu_search
import matplotlib.pyplot as plt

dist = [[0, 20, 42, 25, 45, 54], [20, 0, 30, 34, 32, 43],
        [42, 30, 0, 10, 23, 43], [25, 34, 10, 0, 23, 45],
        [20, 20, 42, 25, 0, 12], [60, 20, 42, 25, 43, 0]]

a = tabu_search.tabu_search(tabu_search.Cijene, range(1,
                                                      len(dist) + 1), 300,
                            0.0001, 0.5, 10, dist)
print("Rjesenje problema za G1: ", a[0], " cijena: ", a[1])

#a = datetime.datetime.now()
#total.pretrazivanje(dist)
#b = datetime.datetime.now()
#print (b-a)
#
#a = time.clock()
#total.pretrazivanje(dist)
#b = time.clock()
#print (b-a)
#with open('vrijeme.csv', mode='w')
# as vrijeme:
#    vrijeme = csv.writer(vrijeme, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
#    vrijeme.writerow(['Alg', 'Vrijeme', 'Broj gradova'])
rekurz = []
Esempio n. 8
0
    parser.add_argument('-csv', type=bool, default=False, help='save result to csv file')

    args = parser.parse_args()
    if args.parameter == 'neighbourhood_size':

        # Testing how neighbourhood size affects the result
        neighbourhood_size_list = [i*args.multiplier for i in range(args.first_value, args.last_value)]

        neighbourhood_size_y_lim = list()
        algorithm_time = list()
        for neighbourhood_size in neighbourhood_size_list:

            start_time = time.time()
            best_solution, best_time, best_materials_state, time_change_list = tabu_search(solution=first_solution,
                                                                                           neighbourhood=neighbourhood,
                                                                                           iterations=1000,
                                                                                           tabu_list_size=5,
                                                                                           neighbourhood_size=neighbourhood_size)
            stop_time = time.time()
            algorithm_time.append(stop_time-start_time)
            print("iterations number:", neighbourhood_size, "time:", best_time, "solution:", best_solution)
            neighbourhood_size_y_lim.append(int(best_time))

        plt.plot(neighbourhood_size_list, neighbourhood_size_y_lim, color='black')
        plt.title("time dependence on the size of neighbourhood")
        plt.ylabel("time [s]")
        plt.xlabel("neighbourhood size")
        plt.show()

        # plt.plot(neighbourhood_size_list, algorithm_time, color='green')
        # plt.title("time of algorithm dependence on the size of neighbourhood")
Esempio n. 9
0
def solveTabuSearch(*args):
    outputSolution(tabu_search(photos))
    return 0
Esempio n. 10
0
    # parser.add_argument('-csv', type=bool, default=False, help='save result to csv file')

    parser.add_argument('materials_plot',
                        type=int,
                        help='plot materials chart')
    parser.add_argument('time_plot', type=int, help='plot materials chart')
    parser.add_argument('buildings_plot',
                        type=int,
                        help='plot buildings chart')
    parser.add_argument('random', type=int, help='')

    args = parser.parse_args()

    best_solution, best_time, best_materials_state, time_change_list = tabu_search(
        solution=first_solution,
        neighbourhood=neighbourhood,
        iterations=args.iterations,
        tabu_list_size=args.tabu_list_size,
        neighbourhood_size=args.neighbourhood_size)

    if args.materials_plot == 1:
        plt.plot(range(0, len(best_materials_state[0])),
                 best_materials_state[0])
        plt.title('Aktualna ilość drewna')
        plt.ylabel("Ilość drewna")
        plt.xlabel("Numer decyzji")
        plt.show()
        plt.plot(range(0, len(best_materials_state[1])),
                 best_materials_state[1])
        plt.title('Aktualna ilość cegieł')
        plt.ylabel("Ilość cegieł")
        plt.xlabel("Numer decyzji")