def todo(files):
    coords = []
    with open(files, 'r') as f:
        i = 0
        for line in f.readlines():
            line = [float(x.replace('\n', '')) for x in line.split(' ')]
            coords.append([])
            for j in range(1, 3):
                coords[i].append(line[j])
            i += 1

    if __name__ == '__main__':
        #coords = [[round(random.uniform(-1000,1000),4),round(random.uniform(-1000,1000),4)] for i in range(100)]
        sa = SimAnneal(coords, stopping_iter=5000)
        sa.anneal()
        sa.visualize_routes()
        sa.plot_learning()
Exemple #2
0
from anneal import SimAnneal
from visualize_tsp import plotTSP
import matplotlib.pyplot as plt
import random, os, sys, time

def dotrial(t):
    print("doing %d" % t.id)
    t.anneal()
    return t

if __name__ == '__main__':
    ncities=100 
    ntrials=int(sys.argv[1])
    random.seed(0)
    coords = [[round(random.uniform(-1000,1000),4),round(random.uniform(-1000,1000),4)] for i in range(ncities)]

    plotTSP([range(ncities),], coords)

    t0=time.time()
    trials = [SimAnneal(coords, stopping_iter = 500000, alpha=0.9995, id=i) for i in range(ntrials)]
    got=map(dotrial, trials)
    
    best=sorted([(t.best_fitness, t) for t in got])[0][1]

    print("Time %f, Fitness %f" % (time.time()-t0, best.best_fitness))
    best.visualize_routes()
    best.plot_learning()
    
Exemple #3
0
    test_loader = InstanceLoader("test")
    with open('TSP-closest-anneal-log.dat', 'w') as logfile:
        print("inst_i\tinst_size\tclosest_fitness\tsa_fitness\tsa_iter",
              file=logfile)
        # Run for a number of epochs
        for epoch_i in range(1):

            sa_acc = 0
            cn_acc = 0

            print("Testing model...", flush=True)
            for (inst_i, inst) in enumerate(
                    test_loader.get_instances(len(test_loader.filenames))):
                _, Mw, _ = inst
                Mw = np.round(Mw * bins)
                sa = SimAnneal(Mw)
                cn_acc += sa.best_fitness
                print("{inst_i}\t{inst_size}\t{closest_fitness}\t".format(
                    inst_i=inst_i,
                    inst_size=Mw.shape[0],
                    closest_fitness=sa.best_fitness),
                      end="",
                      file=logfile)
                sa.anneal()
                sa_acc += sa.best_fitness
                print("{sa_fitness}\t{sa_iter}".format(
                    sa_fitness=sa.best_fitness, sa_iter=sa.iteration),
                      file=logfile)

            #end
            cn_acc /= inst_i
Exemple #4
0
from anneal import SimAnneal
import matplotlib.pyplot as plt
import random

coords = []
with open('coord.txt', 'r') as f:
    i = 0
    for line in f.readlines():
        line = [float(x.replace('\n', '')) for x in line.split(' ')]
        coords.append([])
        for j in range(1, 3):
            coords[i].append(line[j])
        i += 1

if __name__ == '__main__':
    #coords = [[round(random.uniform(-1000,1000),4),round(random.uniform(-1000,1000),4)] for i in range(100)]
    sa = SimAnneal(coords, stopping_iter=5000)
    sa.anneal()
    sa.visualize_routes()
    sa.plot_learning()
Exemple #5
0
def dotrial(t):
    print("doing %d" % t.id)
    random.seed(t)
    t.anneal()
    return t


if __name__ == '__main__':
    t0 = time.time()
    ncities = 100
    ntrials = int(sys.argv[1])
    random.seed(0)
    coords = [[
        round(random.uniform(-1000, 1000), 4),
        round(random.uniform(-1000, 1000), 4)
    ] for i in range(ncities)]

    p = Pool(int(os.getenv("SLURM_CPUS_PER_TASK",
                           "3")))  # get cpus from slurm, default to 3
    trials = [
        SimAnneal(coords, stopping_iter=500000, alpha=0.9995, id=i)
        for i in range(ntrials)
    ]
    got = p.map(dotrial, trials)

    best = sorted([(t.best_fitness, t) for t in got])[0][1]

    print("Time %f, Fitness %f" % (time.time() - t0, best.best_fitness))
    best.visualize_routes()
    best.plot_learning()
data = data + adjust

"""
# specify document name
file_name = "multivar_data_nb.txt"

all_data = np.loadtxt(file_name, delimiter=',')

# last column of data contains the classes for each input vector
data = all_data[:, :-1]
"""
# get the parameters
training_length, num_properties = data.shape

properties = {
    "reservoir_size": 20,
    "training_length": training_length,
    "num_properties": num_properties,
    "num_classes": 2
}


if __name__ == "__main__":
    sa = SimAnneal(data, properties, stopping_iter=5000)
    sa.anneal()
    plt.figure()
    sa.plot_best()
    plt.show()
    plt.figure()

from anneal import SimAnneal
import matplotlib.pyplot as plt
import random

coords = []
with open('coord.txt', 'r') as f:
    i = 0
    for line in f.readlines():
        line = [float(x.replace('\n', '')) for x in line.split(' ')]
        coords.append([])
        for j in range(1, 3):
            coords[i].append(line[j])
        i += 1

if __name__ == '__main__':
    #coords = [[round(random.uniform(-1000,1000),4),round(random.uniform(-1000,1000),4)] for i in range(100)]
    sa = SimAnneal(coords, stopping_iter=5000)
    sa.Anneal()
    sa.visualizeRotes()
    sa.plotLearning()
Exemple #8
0
from anneal import SimAnneal
import matplotlib.pyplot as plt
import random
import drawing

cards = []
vehicles = []
with open("data2.txt", "r") as f:
    ncard = int(f.readline().replace("\n", ""))
    for i in range(ncard):
        line = f.readline()
        line = [float(x.replace("\n", "")) for x in line.split(" ")]
        cards.append(line)
    print("cards = ", cards)

    nvehicle = int(f.readline().replace("\n", ""))
    for i in range(nvehicle):
        line = f.readline()
        line = [float(x.replace("\n", "")) for x in line.split(" ")]
        vehicles.append(line)
    print("vehicles = ", vehicles)

if __name__ == "__main__":
    # coords = [[random.uniform(-1000, 1000), random.uniform(-1000, 1000)] for i in range(100)]
    sa = SimAnneal(cards, vehicles, stopping_iter=5000)
    if sa.anneal() == True:
        # sa.visualize_routes()
        drawing.draw_simulate(sa.cards, sa.vehicles, sa.best_solution)
        sa.plot_learning()
Exemple #9
0
     # print(partition[1])
     partial_dm = gmaps.distance_matrix(
         [vertex[v]['geometry']['location'] for v in partition[0]],
         [vertex[v]['geometry']['location'] for v in partition[1]])
     # pprint.pprint(partial_dm)
     storeDataFrame(partial_dm, partition[0], partition[1], dfDist, dfTime)
     time.sleep(3)
 dfDist.to_csv('dfDist.csv')
 dfTime.to_csv('dfTime.csv')
 city_list = []
 for idx, v in enumerate(vertex.keys()):
     loc = vertex[v]['geometry']['location']
     city_list.append([loc['lat'], loc['lng']])
 pprint.pprint(city_list)
 s****t = SimAnneal(coords=city_list,
                    dist=dfDist.to_numpy(),
                    alpha=0.999,
                    stopping_iter=1000000)
 s****t.batch_anneal(times=30)
 solidxs = s****t.best_solution
 startidx = list(vertex.keys()).index(starting_vertex['place_id'])
 solidxs = solidxs[solidxs.index(startidx):] + solidxs[0:solidxs.
                                                       index(startidx)]
 solidxs.append(solidxs[0])
 print(f'https://www.google.com/maps/dir/' +
       ('/').join([(',').join([str(s) for s in city_list[idx]])
                   for idx in solidxs]))
 print(f'https://maps.openrouteservice.org/directions?' + 'n1=' +
       str(city_list[solidxs[0]][0]) + '&n2=' +
       str(city_list[solidxs[0]][1]) + '&n3=13' + '&a=' +
       ','.join(','.join([str(s) for s in city_list[idx]])
                for idx in solidxs) + '&b=0&c=0&k1=en-US&k2=km')
Exemple #10
0
k=1
while k <= n:
    rand_pt=round(random.uniform(1, 100),4)
    ptime=np.append(ptime,rand_pt)
    k+=1
'''

fitness_list = ()
matrix = np.vstack((job_number, ptime))  #將兩個矩陣合併

i = 1
while i <= 5:
    if __name__ == '__main__':
        sa = SimAnneal(matrix,
                       alpha=0.95,
                       T=100,
                       stopping_iter=100,
                       stopping_T=0.0001)  #
        sa.anneal()
        sa.spt()
        sa.plot_learning()
        each_gap_fitness = round(
            (sa.best_fitness - sa.spt()) / sa.best_fitness, 8)
        print('Each Time Gap', each_gap_fitness * 100, '%')
        print('')
        fitness_list = np.append(fitness_list, sa.best_fitness)
    i += 1
# print(fitness_list)
print(sa.T)
print(sa.iteration)
mean_fitness = sum(fitness_list) / (i - 1)