Example #1
0
def test_TSP__nearest_neighbour_heuristic_four_vertices():
    g = G(grafo=np.array([[0, 1, 5, 4], [1, 0, 2, 6], [5, 2, 0, 3],
                          [4, 6, 3, 0]]))
    tsp = TSP(g=g, origem=0)
    path, cost, steps = tsp._TSP__nearest_neighbour_heuristic()
    assert np.allclose(path, np.array([0, 1, 2, 3, 0
                                       ])) and cost == 10 and steps == 3
Example #2
0
def print_seq(address_map,node0,node):
    tsp=TSP(address=address_map,node=node0,init_city=0,count=300)
    gene=tsp.run(10000)
    begin=gene.index(0)     #起始站位置
    for i in range(begin,begin-len(gene),-1):
        print(node[gene[i]],"---->",end=' ')
    print(node[gene[begin]])
Example #3
0
 def load_map(self, filename):
     rally_list = []
     temp_dict = {}
     file_length = self.get_cidades(filename)
     temp = -file_length
     cidades = self.quadratic_equation(1, -1, temp)
     n = cidades
     inicio = 0
     fim = n - 1
     for i in range(n):
         for j in range(inicio, fim):
             new_line = self.get_line_number(filename, j)
             number = new_line[4] + new_line[5]
             try:
                 number += new_line[6]
                 number += new_line[7]
                 temp_dict[new_line[2]] = int(number)
             except IndexError:
                 temp_dict[new_line[2]] = int(number)
         simbolo = new_line[0]
         new = RallyNode(simbolo, copy.deepcopy(temp_dict))
         rally_list.append(new)
         temp_dict.clear()
         inicio = fim
         fim = inicio + n - 1
     t = TSP()
     m = t.create_adjancency_maxtrix(rally_list)
     t.solve_tsp(m, rally_list)
Example #4
0
def test_TSP__brute_force_algorithm_four_vertices():
    g = G(grafo=np.array([[0, 1, 5, 4], [1, 0, 2, 6], [5, 2, 0, 3],
                          [4, 6, 3, 0]]))
    tsp = TSP(g=g, origem=0)
    path, cost, steps = tsp._TSP__brute_force_algorithm()
    assert np.allclose(path, np.array([0, 1, 2, 3, 0
                                       ])) and cost == 10 and steps == 6
Example #5
0
def main():
    print('Starting...')
    data = data_reader(args.target)
    # solution = LocalSearch(op_idx=2)
    # solution = VariableLocalSearch(op_idx1=0, op_idx2=2, keep_invariant=1000, keep_invariant_max=2000)
    # solution = SA(op_idx=0, init_coeff=0.9, init_inner_time=200, stop_temp=1e-2, alpha=0.98)
    solution = GA(population_size=200, cross_rate=[0.3, 0.5], mutation_rate=[0.1, 0.5], keep_invariant=50)
    tsp = TSP(solution, data, euclidean_dist)
    tsp.run(threshhold=args.thresh, savepath=args.savepath, save_freq=args.save_freq,
            print_freq=args.print_freq, max_iteration=args.max_itr)
    if args.savepath is not None:
        generate_gif(args.savepath)
        plot(args.savepath)
Example #6
0
 def runTSP(self):
     self.tsp = TSP(gui=self,
                    filename=self.filenameVar.get(),
                    lrate=int(self.lrateVar.get()),
                    maxepochs=int(self.maxepochsVar.get()),
                    xneurons=int(self.xneuronsVar.get()),
                    nhsize=int(self.nhsize.get()))
Example #7
0
def main(argv):

    number_exec = int(argv[1])
    filename = ""

    cities = []

    while True:
        try:
            line = input().strip()

            if "NAME" in line:
                filename = line

            elif line == "NODE_COORD_SECTION":

                while True:
                    try:

                        line = input().split()
                        city = City(line[0], line[1], line[2])
                        cities.append(city)
                    except Exception as e:
                        #print ("1 " + str(e) + " city :" + str(city.id))
                        break

        except Exception as e:
            #print ("2 " + str(e) + " city :" + str(city.id))
            break

    tsp = TSP()
    M = tsp.get_distance_matrix(cities)

    #tsp.pretty_print(M)
    #exit()

    #print ("\nCusto NN : " + str(custo_nn))
    #tsp.print_tour_simple(nn_tour)

    print("Executing " + str(number_exec) + " times on : " + str(filename))

    start_time = timeit.default_timer()

    minimo = float("inf")
    for i in range(number_exec):
        #alpha = random.uniform(0, 1)
        alpha = 0.5
        grasp_tour = tsp.GRASP_TSP(cities, M, alpha)
        custo_final = tsp.get_cost(grasp_tour, M)

        if custo_final < minimo:
            print("\nAlpha : " + str(alpha) + " Custo GRASP: " +
                  str(custo_final))
            tsp.plot_cities(grasp_tour)
            minimo = custo_final

    elapsed = timeit.default_timer() - start_time

    print("Elapsed time : " + str(elapsed) + " s")
    print("---------------------------------------------\n\n")
Example #8
0
 def main_tarefa1_3(self):
     option = input("Quer carregar um ficheiro?(y/n): ")
     if option == 'y':
         filename = input("Nome do ficheiro: ")
         while not self.search_file("./" + filename):
             filename = input(
                 "Ficheiro não existe por favor introduza um nome válido: ")
         inicio = process_time()
         self.load_map(filename)
         fim = process_time()
         print("Operação concluida em " + str(fim - inicio) + " segundos")
     elif option == 'n':
         n_cidades = eval(input("Número de cidades: "))
         rally_list = self.input_map(n_cidades)
         self.print_map(rally_list)
         print("Map created\n\n")
         t = TSP()
         m = t.create_adjancency_maxtrix(rally_list)
         t.solve_tsp(m, rally_list)
def main(argv):
    print("init main...")
    number_exec = int(argv[1])

    cities = []

    # Read file
    fileContent = open(argv[2], 'r').read()

    # Attention: file must be well formated
    # TODO: make it more robust
    lines = fileContent.split("\n")
    filename = lines[0]
    for line in lines[7:]:
        try:
            aux = line.split(" ")
            # Get id, position x and position Y
            city = City(aux[0], aux[1], aux[2])
            cities.append(city)
        except Exception as e:
            print("1 " + str(e) + " city :" + str(city.id))
            break

    tsp = TSP()
    M = tsp.get_distance_matrix(cities)

    # print matrix of distances
    # tsp.pretty_print(M)
    # exit()

    print("Executing " + str(number_exec) + " times on : " + str(filename))

    start_time = timeit.default_timer()

    minimo = float("inf")

    for i in range(number_exec):
        print("Attempt " + str(i))

        alpha = random.uniform(0, 1)
        tour, custo_final = tsp.runGRASP(cities, M, alfa=alpha)

        if custo_final < minimo:
            print("\nCusto: " + str(custo_final))
            tsp.plot_cities(tour)
            minimo = custo_final

    elapsed = timeit.default_timer() - start_time

    input("presse ENTER to continue")
    print("Elapsed time : " + str(elapsed) + " s")
    print("---------------------------------------------\n\n")
Example #10
0
import matplotlib.pyplot as plt
import numpy as np
from GA import GA
from TSP import TSP

N_CITIES = 20  # DNA size
CROSS_RATE = 0.1
MUTATE_RATE = 0.02
POP_SIZE = 500
N_GENERATIONS = 500

ga = GA(DNA_size=N_CITIES,
        pcross=CROSS_RATE,
        pmutation=MUTATE_RATE,
        pop_size=POP_SIZE)
env = TSP(N_CITIES)
for gen in range(N_GENERATIONS):
    lx, ly = ga.translateDNA(ga.pop, env.city_position)
    fitness, total_distance = ga.get_fitness(lx, ly)
    ga.evolve(fitness)
    best_idx = np.argmax(fitness)  #返回最大值的索引
    print(
        'Gen:',
        gen,
        '| best fit: %.2f' % fitness[best_idx],
    )
    env.plotting(lx[best_idx], ly[best_idx], total_distance[best_idx])
    #绘制出每一代的最优路径

plt.ioff()
plt.show()
Example #11
0
from TSP import TSP
import matplotlib
import numpy as np
import matplotlib.pyplot as plt

training = []

policy_network = GNN_Policy()
optimizer = torch.optim.Adam(params=policy_network.parameters(), lr=3e-4)
loss_fn = nn.MSELoss()


# generate examples
for _ in range(25):
    print("iterating")
    tsp = TSP(10, 2)
    solver = MCTSExample(tsp, training)
    solver.solve()
print(training)
# train
trainer = GNN_Trainer(policy_network, training)
trainer.train_all()
policy_network = trainer.model
print(trainer.losses)
# plot loss
plt.scatter(x=np.arange(len(trainer.losses)), y=trainer.losses, marker='.')
plt.show()

print("start testing")
# test choices of policy network
results = []
from io_files import read_file_dist, read_file_solution
from graphics import *
from TSP import TSP
from AG import AG
import sys

try:
    file = str(sys.argv[1])
    npop = int(sys.argv[2])
    ngen = int(sys.argv[3])
    pc = float(sys.argv[4])
    pm = float(sys.argv[5])
except:
    print('Erro nos argumentos')
    print('python3 main.py file_name(lau15 ou wg59) npop, ngen, pcruzamento, pmutação')
    sys.exit(1)

partial_statics_dict = dict()

n, dist_tsp = read_file_dist(file)
sol = read_file_solution(file)
tsp = TSP(n, dist_tsp, sol)
genetic = AG(npop, ngen, 1, 1, pc, pm, tsp)
history, statics_dict = genetic.init()
fo_star = genetic.get_fo(tsp.solution)
#print(f'Melhor Solução: {fo_star}')
plot_best(history, npop, ngen, pc, pm, file)
plot_mean(statics_dict, npop, ngen, pc, pm, file)
partial_statics(statics_dict, partial_statics_dict, 0)
generate_table(npop, ngen, pc, pm, 1, partial_statics_dict, file)
Example #13
0
def main():
    controller = Controller()
    controller.setTSP(TSP())
    PESolver(controller)
    ChSolver(controller)
    GUI(controller)
Example #14
0
    packages = csv.reader(packageFile, delimiter=",")
    # using the python csv reader
    for row in packages:
        # inserting the packages into the allPackages hash table
        allPackages.insert(int(row[0]), row[1], row[5], row[2], int(row[4]), row[6])

with open('WGUPSDistanceTable.csv') as distanceFile:
    distance = csv.reader(distanceFile, delimiter=",")
    # using the python csv reader
    for row in distance:
        # adding the distance table per row to the allDistances Table
        allDistances.append(row)

# creating a Truck 1 instance as well as a TSP 1 instance and adding packages to Truck 1 manually
truck_1 = Truck('Truck 1', 9, 5)
TSP_1 = TSP(truck_1)
truck_1.load_truck(allPackages, 1)
truck_1.load_truck(allPackages, 6)
truck_1.load_truck(allPackages, 12)
truck_1.load_truck(allPackages, 22)
truck_1.load_truck(allPackages, 23)
truck_1.load_truck(allPackages, 24)
truck_1.load_truck(allPackages, 25)
truck_1.load_truck(allPackages, 26)
truck_1.load_truck(allPackages, 28)
truck_1.load_truck(allPackages, 27)
truck_1.load_truck(allPackages, 31)
truck_1.load_truck(allPackages, 32)
truck_1.load_truck(allPackages, 40)
truck_1.load_truck(allPackages, 34)
truck_1.load_truck(allPackages, 4)
Example #15
0
def plot_tour(dat, index_list, p=plt):
    for k in range((index_list).shape[0]):
        if k == (index_list).shape[0] - 1:
            x1 = [dat[index_list[k], 0], dat[index_list[0], 0]]
            x2 = [dat[index_list[k], 1], dat[index_list[0], 1]]
            p.plot(x1, x2, 'k')
        else:
            x1 = [dat[index_list[k], 0], dat[index_list[k + 1], 0]]
            x2 = [dat[index_list[k], 1], dat[index_list[k + 1], 1]]
            p.plot(x1, x2, 'k')


if __name__ == '__main__':
    # Initialisation
    filename = 'berlin52'
    m = TSP('data/' + filename + '.tsp')
    a = 0.8
    t = 0.2

    t0 = time.time()
    sd = PS(m)
    (dist_d, x_d, u_d) = sd.solve()
    t1 = time.time()
    total = t1 - t0
    print("Résourdre TSP déterministe en {0:.1f}s, \n\tfonction objectif = {1:.2f}"\
          .format(total, dist_d))

    t0_ = time.time()
    ss = PS(m, mod="stochastic", alpha=a, taux_majoration=t)
    (dist_s, x_s, u_s) = ss.solve()
    t1_ = time.time()
Example #16
0
    for i in range(arr.shape[0]):
        A, B = np.partition(arr[i], 2)[1:3]
        bound = bound + (A + B) / 2

    return bound


def min2_3(arr):
    bound = 0
    for i in range(arr.shape[0]):
        bound = bound + np.mean(np.sort(arr[i])[1:3])
    return bound


if __name__ == '__main__':
    tsp = TSP()
    arr = tsp.obtener_random(1000)
    import time
    repetitions = 50
    total1 = []
    for i in range(repetitions):
        start = time.time()
        res = min2_1(tsp.graph)
        end = time.time()
        total1.append(end - start)
        print(f'{i}/50')
    print(f'Media min21 : {np.mean(total1[1:])}')
    total2 = []
    for i in range(repetitions):
        start = time.time()
        res = min2_2(tsp.graph)
Example #17
0
    #"""
    for obj in gal.actual_population:
        if obj.fitness == min(map(lambda x: x.fitness, gal.actual_population)):
            file.writelines(json.dumps(obj, default=lambda o: o.__dict__))
            break
    #"""

    file.close()

    print '\nbest fitness actual pop: ', min(
        map(lambda x: x.fitness, gal.actual_population))


# tsp = TSP('../test/a280.tsp')  # con espacios al principio, 280 elementos
tsp = TSP('../test/Nueva Carpeta/att48.tsp'
          )  # sin espacios al principio, 48 elementos
# tsp = TSP('../test/Nueva Carpeta/ch130.tsp')  # sin espacios al principio, 130 elementos

# print json.dumps(tsp, default=lambda o: o.__dict__) #best wea ever

# tsp = TSP('../test/Nueva Carpeta/mine.tsp')  # custom, 20 elements

#t1 = threading.Thread(target=gen_thread1, args=(tsp,), name='gen_1')
#t1.daemon = True

t2 = threading.Thread(target=gen_thread2, args=(tsp, ), name='gen_2')
t2.daemon = True

t_init = datetime.datetime.now()

#t1.start()
Example #18
0
def hyper_opt(tspOn, param, paramList, numIter=25):
    """!
    Performs a hyper optimization on the Gnowee control paramenters for both
    TSP and standard mixed integer, condinuous, and discrete problems.

    The parameters considered are hardwired.  It is kind of crappy and only
    allows one parameter to be optimized at a time.

    @param tspOn: \e boolean \n 
        If true, the settings will be optimized for TSP problems. \n
    @param param: \e string \n 
        An attribute name of the GnoweeHeuristics object to be optimized. \n
    @param paramList: \e list \n 
        List of the parameters to be considered in the optimization. \n
    @param numIter: \e integer \n 
        The number of iterations to perform for each parameter. \n
   
    @return <em> numpy array: </em> Returns the results of the hyper-
        optimization. \n
    """

    assert tspOn == False or tspOn == True, 'tspOn must be True or False.'

    # Build list of optimization problem types
    if tspOn == False:
        optFunct = [
            'welded_beam', 'pressure_vessel', 'speed_reducer', 'spring',
            'mi_spring', 'mi_pressure_vessel', 'mi_chemical_process', 'ackley',
            'dejong', 'easom', 'griewank', 'rastrigin', 'rosenbrock'
        ]
        numProb = len(optFunct)
        dimension = [0, 0, 0, 0, 0, 0, 0, 3, 4, 2, 6, 5, 5]

    else:
        optFunct = [
            'eil51.tsp', 'st70.tsp', 'pr107.tsp', 'bier127.tsp', 'ch150.tsp'
        ]
        tspPath = [
            os.path.pardir + '/Benchmarks/TSPLIB/eil51.tsp',
            os.path.pardir + '/Benchmarks/TSPLIB/st70.tsp',
            os.path.pardir + '/Benchmarks/TSPLIB/pr107.tsp',
            os.path.pardir + '/Benchmarks/TSPLIB/bier127.tsp',
            os.path.pardir + '/Benchmarks/TSPLIB/ch150.tsp'
        ]
        numProb = len(tspPath)
        dimension = [0, 0, 0, 0, 0]

    # Initialize variables
    maxIter = numIter  #Number of algorithm iterations
    results = np.zeros((numProb, len(paramList), 3))

    for i in range(0, numProb, 1):
        for j in range(0, len(paramList), 1):
            history = []  # Contains the final timeline results from each run

            # Set default optimization settings
            gh = GnoweeHeuristics()
            if tspOn == False:
                gh.set_preset_params(optFunct[i],
                                     'Gnowee',
                                     dimension=dimension[i])
            else:
                gh.stallLimit = 15000
                tspProb = TSP()
                tspProb.read_tsp(tspPath[i])
                tspProb.build_prob_params(gh)

            # Update current settings
            setattr(gh, param, paramList[j])

            for k in range(0, maxIter, 1):
                print "Run: {}, {}={}, iter# {}".format(
                    optFunct[i], param, paramList[j], k)

                #Run Optimization Algorithm
                (timeline) = Gnowee.main(gh)

                # Save final timeline data for future processing
                minGen = min(timeline, key=attrgetter('fitness'))
                history.append(
                    Event(minGen.generation, minGen.evaluations,
                          minGen.fitness, minGen.design))

            # Calculate averages and standard deviations
            tmp = []
            averages = Event(sum(c.generation for c in history)\
                             /float(len(history)),
                             sum(c.evaluations for c in history)\
                             /float(len(history)),
                             sum(c.fitness for c in history)\
                             /float(len(history)),tmp)

            if maxIter > 1:
                for l in range(len(history[-1].design)):
                    stdDev = Event(m.sqrt(sum([(c.generation \
                                - averages.generation)**2 for c in history])\
                                /(len(history) - 1)),
                              m.sqrt(sum([(c.evaluations \
                                - averages.evaluations)**2 for c in history])\
                                /(len(history) - 1)),
                              m.sqrt(sum([(c.fitness - averages.fitness)**2 \
                                for c in history])/(len(history) - 1)), tmp)
            else:
                tmp = np.zeros(len(history[-1].design))
                stdDev = Event(0, 0, 0.0, tmp)

            # Save Results for plotting
            results[i, j, 0] = paramList[j]
            if gh.optimum == 0.0:
                results[i, j, 1] = (averages.fitness*(averages.evaluations+3\
                                                      *stdDev.evaluations))
            else:
                results[i ,j , 1] = (abs((averages.fitness-gh.optimum)\
                                         /gh.optimum)*(averages.evaluations+3\
                                                       *stdDev.evaluations))
            if gh.optimum != 0:
                results[i, j, 2] = m.sqrt((stdDev.fitness/averages.fitness)**2\
                                          +(stdDev.evaluations\
                                            /averages.evaluations)**2)\
                                          /gh.optimum*results[1, j, 1]
            else:
                results[i, j, 2]=m.sqrt((stdDev.fitness/averages.fitness)**2\
                                        +(stdDev.evaluations\
                                          /averages.evaluations)**2)\
                                        *results[1,j,1]

    # Output the results and some statistics
    print repr(results)
    print(
        "Variable   Weighted Relative Sum (Low is Better)  "
        "Sum of Ordinal Rank   Number of Minimums")
    print(
        "==================================================="
        "=======================================")
    weighted = cp.copy(results)
    for i in range(0, len(results[0])):
        minLoc = []
        ranks = []
        for j in range(0, len(results)):
            weighted[j, :, 1] = results[j, :, 1] / min(results[j, :, 1])
            minLoc.append(np.argmin(results[j, :, 1]))
            ranks.append(rankdata(results[j, :, 1], method='ordinal'))
        print(
            "{}                  {}                          "
            "{}                  {}".format(paramList[i], sum(weighted[:, i,
                                                                       1]),
                                            sum(np.asarray(ranks)[:, i]),
                                            Counter(minLoc)[i]))

    #Plot the results
    if tspOn == False:
        label = [
            '\\textbf{Welded Beam}', '\\textbf{Pressure Vessel}',
            '\\textbf{Speed Reducer}', '\\textbf{Spring}',
            '\\textbf{MI Spring}', '\\textbf{MI Pressure Vessel}',
            '\\textbf{MI Chemical Process}'
        ]
        title = '\\textbf{Hyper-Optimization of Gnowee Algorithm for %s}' % param
        op.plot_optimization(results[0:len(label)], label, title)
        label2 = [
            '\\textbf{Ackley}', '\\textbf{De Jong}', '\\textbf{Easom}',
            '\\textbf{Griewank}', '\\textbf{Rastrigin}', '\\textbf{Rosenbrock}'
        ]
        op.plot_optimization(results[len(label):len(label) + len(label2)],
                             label2, title)
    else:
        label = [
            '\\textbf{Eil51}', '\\textbf{St70}', '\\textbf{Pr107}',
            '\\textbf{Bier127}', '\\textbf{Ch150}'
        ]
        title = '\\textbf{Hyper-Optimization of Gnowee Algorithm for %s}' % param
        op.plot_optimization(results, label, title)

    return results
Example #19
0
import matplotlib.pyplot as plt
from TSP import TSP
from read_data import read_data

City = read_data("../人工智能与大数据实验/data.txt").data()
print(City)

tsp = TSP(city=City, init_city=3, count=1000)
tsp.run(10000)
# -*- coding: utf-8 -*-
"""
Created on Tue May  4 12:02:52 2021

@author: 2rome
"""

from TSP import TSP
from profundidad_y_poda import branchAndBound
from time import sleep
import pandas as pd

if __name__ == '__main__':
    tsp = TSP()  #Crear el objeto

    min_dim = 4
    max_dim = 21
    scenarios_per_dim = 20
    tiempos = {}

    for dim in range(min_dim, max_dim):
        tiempos[dim] = [None] * scenarios_per_dim
        for i in range(scenarios_per_dim):
            sleep(1)
            tsp.obtener_random(dim)
            time = branchAndBound(tsp)
            tiempos[dim][i] = time
            tsp.save_scenario()
            tsp.save_solucion()
            df = pd.DataFrame(tiempos)
            df.to_csv('tiempos_branch_ejecucion.csv', index=False)
Example #21
0
from Graph import Graph
from TSP import TSP

N = 10
repeat = 10

allGraph = Graph("graph100.txt")
townGraph = allGraph.pickAdjacent(range(N))
townGraph.printWeight()
# TSP.executeCompleteEnumeration(townGraph, repeat)
TSP.executeNearestAddition(townGraph)
Example #22
0
def test_TSP_two_vertices():
    g = G(grafo=np.array([[0, 2], [2, 0]]))
    tsp = TSP(g=g, origem=0)
    path, cost, steps = tsp.solve()
    assert np.allclose(path, np.array([0, 1, 0])) and cost == 4 and steps == 1
Example #23
0
def test_TSP():
    assert TSP()
Example #24
0
import sys

from TSP import TSP

t_n_string = input().split(" ", 2)
t = int(t_n_string[0])
n = int(t_n_string[1])
matrix = []
for i in range(n):
    matrix.append([int(mat) for mat in input().split(" ", n)])

result = TSP.find_way(matrix, t)

print(result[1])
output = ""
for i in range(n):
    output += str(result[0][i] + 1) + " "

output += "1"

print(output)
Example #25
0
import tkinter as tk
from pylab import mpl

mpl.rcParams['font.sans-serif'] = ['FangSong']  # 指定默认字体

City = read_data("./data.txt").data()

for i, c in enumerate(City):
    print("%d:%s" % (i, c[0]))

a = input("请输入城市:")
a = a.split()
aa = []
for i in a:
    aa.append(City[int(i)])
print(aa)
tsp = TSP(city=aa, init_city=0, count=100)
gene = tsp.run(3000)
print(gene)
city_x = []
city_y = []

plt.figure(2)
for i in range(-1, len(gene), 1):
    plt.scatter(aa[i][1], aa[i][2], color='r')
    plt.text(aa[i][1], aa[i][2] + 0.2, aa[i][0])
    city_x.append(aa[i][1])
    city_y.append(aa[i][2])
plt.plot(city_x, city_y, color='b', linewidth=0.5)

plt.show()
Example #26
0
#iterations = list(range(25))
iterations = [500, 1000, 1500, 2000, 2500, 3000, 3500, 4000, 4500,
              6000]  #, 30, 35, 45, 50]

for iters in iterations:

    training = []

    policy_network = GNN_Policy()
    optimizer = torch.optim.Adam(params=policy_network.parameters(), lr=3e-4)
    loss_fn = nn.MSELoss()

    # generate examples
    for i in range(solve_iterations):
        print(f"Iterating {i}/{solve_iterations}")
        tsp = TSP(nodes, 2)
        solver = MCTSExample(tsp, training, iterations=iters)
        solver.solve()
    #print(training)
    # train
    trainer = GNN_Trainer(policy_network, training)
    trainer.train_all()
    policy_network = trainer.model
    #print(trainer.losses)
    # plot loss
    #plt.scatter(x=np.arange(len(trainer.losses)), y=trainer.losses, marker='.')
    #plt.show()

    # test choices of policy network
    #print("start testing")
    results = []
Example #27
0
File: tspexec.py Project: oiwah/tsp
#!/usr/bin/python
# -*- coding: utf-8 -*-

from TSP import TSP
import time

ber52 = TSP('kroA100')
cities = ber52.readFile()
distMap = ber52.createDistMap(cities)

toList = ber52.optimalDist(cities)
ber52.prettyPrint(toList, distMap)
print

t1 = time.time()
(toList, totalDist) = ber52.greedyOne(cities)
t2 = time.time()
print t2 - t1, 'sec'
ber52.prettyPrint(toList, distMap)
print "totalDistance is ", totalDist
print

t1 = time.time()
(toList, totalDist) = ber52.greedyTwo(cities)
t2 = time.time()
print t2 - t1, 'sec'
ber52.prettyPrint(toList, distMap)
print "totalDistance is ", totalDist
print

t1 = time.time()
Example #28
0
import matplotlib.pyplot as plt
from TSP import TSP
from Map import Map
from dijkstra import Dijkstra_Path

#读取数据库中西电地图的内容
node_map, node = Map("./data.txt").data()
print(node_map, node)

#迪杰斯特拉算法求解对应点之间的最短距离
for i in range(len(node)):
    for j in range(len(node)):
        if i != j and node_map[i][j] == 0:
            node_map[i][j] = 9999
address_map = []
Dijkstra = Dijkstra_Path(node_map)
for i in range(len(node)):
    address_map.append(Dijkstra(i, i - 1))

tsp = TSP(address=address_map, node=node, init_city=0, count=100)
gene = tsp.run(10000)

#起始站
begin = gene.index(0)
for i in range(begin, begin - len(gene), -1):
    print(node[gene[i]], "---->", end=' ')
print(node[gene[begin]])
if __name__ == '__main__':
	import json
	from time import sleep
	import click
	from TSP import TSP
	from Genetic import GeneticAlgorithm

	tsp = TSP('../test/Nueva Carpeta/att48.tsp')
	#tsp = TSP('../test/Nueva Carpeta/kroA200.tsp')


	# gal = GeneticAlgorithm(tsp, max_pop = 100, max_gen = 100, max_fit=350000.0, mut_rate=0.2)
	gal = GeneticAlgorithm(tsp, max_pop = 1000, max_gen = 1000, max_fit=140000.0, mut_rate=0.2)

	"""
	with click.progressbar(range(gal.max_generation)) as bar:
		for i in bar:
			gal.run()
	"""
	fit = 0.0
	for i in range(gal.max_generation):
		print 'max fitness actual generation:', i+1, str(max(map(lambda x: x.fitness, gal.actual_population)))
		print 'min fitness actual generation:', i+1, str(min(map(lambda x: x.fitness, gal.actual_population)))
		print 'expected fitness chrom:', str(min(map(lambda x: x.expected_fitness, gal.actual_population)))
		print 'fitness decrement', str(fit)
		print
		gal.run(fit)
		if fit > str(min(map(lambda x: x.fitness, gal.actual_population))):
			fit += gal.max_population/gal.max_generation
		else fit += 0.1
		#sleep(1)