示例#1
0
def main():
    parser = argparse.ArgumentParser(
        description='Input TSP file and hyperparameters')
    parser.add_argument('--tsp_file', '-f', help='TSP file path')

    args = parser.parse_args()
    tsp_file = args.tsp_file
    processor = TSPProcessor(tsp_file)
    nodes = processor.euc2d_process()
    '''set the simulated annealing algorithm params'''
    temp = 10000
    stopping_temp = 0.00000001
    alpha = 0.999995
    stopping_iter = 10000000
    '''set the dimensions of the grid'''
    size_width = 200
    size_height = 200
    '''set the number of nodes'''
    population_size = 70
    '''generate random list of nodes'''
    # nodes = NodeGenerator(size_width, size_height, population_size).generate()
    '''run simulated annealing algorithm with 2-opt'''
    sa = SimulatedAnnealing(nodes, temp, alpha, stopping_temp, stopping_iter)
    sa.anneal()
    '''animate'''
    save_path = os.path.join(
        os.path.join(os.path.dirname(tsp_file), 'result_gif'),
        os.path.basename(tsp_file) + '.gif')
    sa.animateSolutions(save_path)
    '''show the improvement over time'''
    sa.plotLearning()
示例#2
0
def main():
    '''set the simulated annealing algorithm params'''
    temp = 1000
    stopping_temp = 0.00000001
    alpha = 0.9995
    stopping_iter = 10000000
    '''set the dimensions of the grid'''
    size_width = 50
    size_height = 50
    '''set the number of nodes'''
    population_size = 100
    '''generate random list of nodes'''
    '''nodes = NodeGenerator(size_width, size_height, population_size).generate()'''
    f = open('data.txt')
    xs = []
    ys = []
    for data in f.readlines():
        data = data.strip('\n')
        nums = data.split(" ")
        while '' in nums:
            nums.remove('')
        xs.append(int(nums[0]))
        ys.append(int(nums[1]))
    nodes = np.column_stack((xs, ys))
    f.close()
    '''run simulated annealing algorithm with 2-opt'''
    sa = SimulatedAnnealing(nodes, temp, alpha, stopping_temp, stopping_iter)
    sa.anneal()
    '''animate'''
    sa.animateSolutions()
    '''show the improvement over time'''
    sa.plotLearning()
示例#3
0
def main():
    '''define some global variables'''
    results = []
    '''set the simulated annealing algorithm parameter grid'''
    temp = 50000
    stopping_temp = 0.000000001
    alpha = .999
    stopping_iter = 10000000
    '''generate random list of nodes'''
    nodes = np.array([[20, 20], [60, 20], [100, 40], [120, 80], [160, 20],
                      [200, 40], [180, 60], [180, 100], [140, 140], [200, 160],
                      [180, 200], [140, 180], [100, 160], [80, 180], [60, 200],
                      [20, 160], [40, 120], [100, 120], [60, 80], [20, 40]])

    nodes = np.random.permutation(nodes)
    '''run simulated annealing algorithm with 2-opt'''
    sa = SimulatedAnnealing(nodes, temp, alpha, stopping_temp, stopping_iter)
    start_time = time.time()
    sa.anneal()
    execution_time = time.time() - start_time
    '''general plots'''
    print('Min weight: ', sa.min_weight)
    print('Iterations: ', sa.iteration)
    print('Execution time: ', execution_time)
    '''animate'''
    sa.animateSolutions()
    '''show the improvement over time'''
    sa.plotLearning()
示例#4
0
def main():
    '''set the simulated annealing algorithm params'''
    temp = 1000
    stopping_temp = 0.00000001
    alpha = 0.9995
    stopping_iter = 10000000

    '''set the dimensions of the grid'''
    size_width = 200
    size_height = 200

    '''set the number of nodes'''
    population_size = 70

    '''generate random list of nodes'''
    nodes = NodeGenerator(size_width, size_height, population_size).generate()

    '''run simulated annealing algorithm with 2-opt'''
    sa = SimulatedAnnealing(nodes, temp, alpha, stopping_temp, stopping_iter)
    sa.anneal()

    '''animate'''
    sa.animateSolutions()

    '''show the improvement over time'''
    sa.plotLearning()
示例#5
0
def main():
    '''define some global variables'''
    results = []
    '''set the simulated annealing algorithm parameter grid'''
    temp = list(range(100, 5000, 100))
    stopping_temp = [0.000000001, 0.00000001, 0.0000001, 0.000001, 0.00001]
    alpha = [a / 100 for a in range(1,100)]
    parameter_dict = {
    "temp": temp,
    "stopping_temp": stopping_temp,
    "alpha": alpha
    }
    stopping_iter = 10000000
    parameter_grid = ParameterGrid(parameter_dict)
    parameter_size = len(list(parameter_grid))

    '''generate random list of nodes'''
    nodes = np.array([[20,20],
                        [60,20],
                        [100,40],
                        [120,80],
                        [160,20],
                        [200,40],
                        [180,60],
                        [180,100],
                        [140,140],
                        [200,160],
                        [180,200],
                        [140,180],
                        [100,160],
                        [80,180],
                        [60,200],
                        [20,160],
                        [40,120],
                        [100,120],
                        [60,80],
                        [20,40]])

    nodes = np.random.permutation(nodes)

    '''run simulated annealing algorithm with 2-opt'''
    ordered_temp = []
    ordered_stopping_temp = []
    ordered_alpha = []
    for parameters in parameter_grid:
        temp = parameters['temp']
        stopping_temp = parameters['stopping_temp']
        alpha = parameters['alpha']
        ordered_temp.append(temp)
        ordered_stopping_temp.append(stopping_temp)
        ordered_alpha.append(alpha)
        sa = SimulatedAnnealing(nodes, temp, alpha, stopping_temp, stopping_iter)
        initial_solution = sa.curr_solution
        start_time = time.time()
        sa.anneal()
        execution_time = time.time() - start_time
        results.append((sa.min_weight, sa.iteration, execution_time, parameters))

    weights, iterations, execution_times, parameters = zip(*results)
    weights = list(weights)
    iterations = list(iterations)
    execution_times = list(execution_times)
    simulations = list(range(parameter_size))

    # Get optimal parameters from all sumulations:
    optimal_run_data = optimal_run(results)
    parameters = optimal_run_data[3]
    temp = parameters['temp']
    stopping_temp = parameters['stopping_temp']
    alpha = parameters['alpha']

    '''general plots'''

    plt.scatter(simulations, weights)
    plt.title('Distancias Finales')
    plt.ylabel('Distancia')
    plt.xlabel('Simulacion')
    plt.show()

    plt.scatter(simulations, iterations)
    plt.title('Iteraciones Totales')
    plt.ylabel('Numero de Iteraciones')
    plt.xlabel('Simulacion')
    plt.show()

    plt.scatter(simulations, execution_times)
    plt.title('Tiempos de Ejecucion')
    plt.ylabel('Tiempo')
    plt.xlabel('Simulacion')
    plt.show()

    sa = SimulatedAnnealing(nodes, temp, alpha, stopping_temp, stopping_iter)
    start_time = time.time()
    sa.anneal()
    execution_time = time.time() - start_time

    print('Min weight: ', sa.min_weight)
    print('Iterations: ', sa.iteration)
    print('Execution time: ', execution_time)


    '''animate'''
    sa.animateSolutions()

    '''show the improvement over time'''
    sa.plotLearning()
示例#6
0
def main():
    '''define some global variables'''
    results = []
    '''set the simulated annealing algorithm parameter grid'''
    temp = list(range(100, 5000, 100))
    stopping_temp = [0.000000001, 0.00000001, 0.0000001, 0.000001, 0.00001]
    alpha = [a / 100 for a in range(1,100)]
    parameter_dict = {
    "temp": temp,
    "stopping_temp": stopping_temp,
    "alpha": alpha
    }
    stopping_iter = 10000000
    parameter_grid = ParameterGrid(parameter_dict)
    parameter_size = len(list(parameter_grid))

    '''set the dimensions of the grid'''
    size_width = 200
    size_height = 200

    '''set the number of nodes'''
    population_size = 12

    '''generate random list of nodes'''
    nodes = NodeGenerator(size_width, size_height, population_size).generate()

    '''run simulated annealing algorithm with 2-opt'''
    ordered_temp = []
    ordered_stopping_temp = []
    ordered_alpha = []
    for parameters in parameter_grid:
        temp = parameters['temp']
        stopping_temp = parameters['stopping_temp']
        alpha = parameters['alpha']
        ordered_temp.append(temp)
        ordered_stopping_temp.append(stopping_temp)
        ordered_alpha.append(alpha)
        sa = SimulatedAnnealing(nodes, temp, alpha, stopping_temp, stopping_iter)
        initial_solution = sa.curr_solution
        start_time = time.time()
        sa.anneal()
        execution_time = time.time() - start_time
        results.append((sa.min_weight, sa.iteration, execution_time, parameters))

    weights, iterations, execution_times, parameters = zip(*results)
    weights = list(weights)
    iterations = list(iterations)
    execution_times = list(execution_times)
    simulations = list(range(parameter_size))

    # Get optimal parameters from all sumulations:
    optimal_run_data = optimal_run(results)

    '''run brute force solution'''
    # The same initial solution is used
    bf = BruteForce(nodes, initial_solution)
    start_time = time.time()
    bf.solve()
    bf_execution_time = time.time() - start_time
    bf_min_weight = bf.min_weight
    bf_iterations = bf.iteration

    '''general plots'''

    plt.scatter(simulations, ordered_temp)
    plt.title('Temperatura')
    plt.ylabel('Temperatura')
    plt.xlabel('Simulacion')
    plt.show()

    plt.scatter(simulations, ordered_stopping_temp)
    plt.title('Temperatura Limite')
    plt.ylabel('Temperatura')
    plt.xlabel('Simulacion')
    plt.show()

    plt.scatter(simulations, ordered_alpha)
    plt.title('Alpha')
    plt.ylabel('Alpha')
    plt.xlabel('Simulacion')
    plt.show()

    plt.scatter(simulations, weights)
    plt.title('Distancias Finales')
    plt.ylabel('Distancia')
    plt.xlabel('Simulacion')
    plt.show()

    plt.scatter(simulations, iterations)
    plt.title('Iteraciones Totales')
    plt.ylabel('Numero de Iteraciones')
    plt.xlabel('Simulacion')
    plt.show()

    plt.scatter(simulations, execution_times)
    plt.title('Tiempos de Ejecucion')
    plt.ylabel('Tiempo')
    plt.xlabel('Simulacion')
    plt.show()

    plt.scatter(simulations, weights)
    line_bf = plt.axhline(y = bf_min_weight, color='r', linestyle='--')
    plt.legend([line_bf], ['Distancia con Fuerza Bruta'])
    plt.title('Distancias Finales')
    plt.ylabel('Distancia')
    plt.xlabel('Simulacion')
    plt.show()

    plt.scatter(simulations, iterations)
    line_bf = plt.axhline(y = bf_iterations, color='r', linestyle='--')
    plt.legend([line_bf], ['Iteraciones con Fuerza Bruta'])
    plt.title('Iteraciones Totales')
    plt.ylabel('Numero de Iteraciones')
    plt.xlabel('Simulacion')
    plt.show()

    plt.scatter(simulations, execution_times)
    line_bf = plt.axhline(y = bf_execution_time, color='r', linestyle='--')
    plt.legend([line_bf], ['Tiempo con Fuerza Bruta'])
    plt.title('Tiempos de Ejecucion')
    plt.ylabel('Tiempo')
    plt.xlabel('Simulacion')
    plt.show()

    '''animate'''
    sa.animateSolutions()

    '''show the improvement over time'''
    sa.plotLearning()

    '''animate (brute force)'''
    bf.animateSolutions()

    '''show the improvement over time (brute force)'''
    bf.plotLearning()
    SA_final = SimulatedAnnealing(3)
    initial_map_cost = SA_final.cost(data_map)
    print 'Initial map cost: %d' % initial_map_cost
    averages[0] += initial_map_cost

    # Plot initial map
    plot = Plot()
    plot.plot(data_map, False)

    # Run simulated annealing experiments
    for i in range(1, 5):
        print 'Running simulated annealing for type %d:' % i

        SA = SimulatedAnnealing(i)

        new_map = SA.anneal(data_map)
        cost = SA_final.cost(new_map)
        print 'Cost: %d' % cost
        averages[i] += cost
        plot.plot(new_map, False, i)

    # Run k-means
    dropoff_zones = data_map.dropoff_zones.keys()
    K = len(dropoff_zones)
    locations = data_map.coordinates.keys()

    k_means = KMeans(K, dropoff_zones, locations, data_map)

    print 'Running k-means clustering:'
    kmeans_cost = k_means.run()
    print 'Cost: %d' % kmeans_cost