Example #1
0
    plt.plot(progress)
    plt.ylabel('Distance')
    plt.xlabel('Generation')
    plt.subplot(212)
    plt.plot(progress_min)
    plt.ylabel('Minimum Distance')
    plt.xlabel('Generation')
    plt.show()
    print("Minimum distance :", min_dist)
    print("Best route :", bestRoute)


#INPUT

import sys
if len(sys.argv) < 2:
    print("need inpute file")
    sys.exit(1)
r = ReadData(sys.argv[1])
print(r.size)
size = r.size
dist_matrix = r.GetDistanceMat()
cityList = []
for i in range(size):
    cityList.append(City(label=i + 1, distance_list=dist_matrix[i]))
geneticAlgorithmPlot(population=cityList,
                     popSize=500,
                     eliteSize=100,
                     mutationRate=0.01,
                     generations=100)
Example #2
0
class NN():
    name = "Nearest Neighbor"

    def __init__(self, file):
        """   
            Intialize: Instaces file,
                       Distance Matrix,
                       and size
        """
        self.file = file
        self.instance = ReadData(self.file)
        self.size = self.instance.size
        self.dis_mat = self.instance.GetDistanceMat()
        self.time_read = self.instance.time_to_read
        self.time_algo = 0

    def get_dist_mat(self):
        """
        changing the distances between tha
        i to i with infinity for simility in code
        """
        D = self.dis_mat.copy()
        for i in range(self.size):
            D[i][i] = np.inf
        return D

    def nn_algo(self, startPoint):
        """
        Nearest Neighbour algorithm
        """
        dist_mat = self.get_dist_mat()
        Tour = [startPoint]
        for _ in range(self.size - 1):
            min_index = np.argmin(dist_mat[Tour[-1]])
            for t in Tour:
                dist_mat[min_index][t] = np.inf
                dist_mat[t][min_index] = np.inf
            Tour.append(min_index)
        return np.array(Tour)

    def run(self):
        """
        randomly chooces starting point
        10% of intances size
        and max = 1000
        min = 10
        and call nn_algo for tour
        """
        tours_dist = []
        tours = []
        self._write_info()
        startPoints = self._start_pt_list()
        #print(startPoints)
        #startPoints = 0
        for s in startPoints:
            t = self.nn_algo(s)
            d = self.get_tour_distance(t)
            tours.append(t + 1)
            tours_dist.append(d)

        self._best_tour(tours, tours_dist)

    def _best_tour(self, Ts, Tsd):
        min_dist_index = np.argmin(Tsd)
        self._writestat(Tsd[min_dist_index], Ts[min_dist_index])

    def get_tour_distance(self, T):
        s = 0
        for i, t in enumerate(T):
            try:
                s += self.dis_mat[t][T[i + 1]]
            except IndexError:
                s += self.dis_mat[t][T[0]]
        return s

    def _write_info(self):
        """
        write info about instance
        """
        print("Instance name:", self.instance.name)
        print("Dimention:", self.size)
        print("Distance Type:", self.instance.EdgeWeightType)
        print("\n \t \t Running 2-opt over 50 random tour ")

    def _writestat(self, D, T):
        """
        Write stats
        """
        print("\n Tour Distance: ", D)
        print(" Best Tour by 2-opt is: \n", T)
        print("\n Time to read instance (sec): ", round(self.time_read))
        self.time_algo = time.time() - start_time
        print(" Time to run instances(sec): ", round(self.time_algo))
        print(" Total Time (sec): ", round(self.time_read + self.time_algo))

    def _start_pt_list(self):
        """
        return starting points list
        """
        np.random.seed(1)
        a = round(self.size * 0.1)
        mi = 10
        mx = 1000
        if a > mx:
            l = np.random.choice(self.size, mx, replace=False)
            return (l)
        elif a <= 10:
            l = np.random.choice(self.size, mi, replace=False)
            return (l)
        else:
            l = np.random.choice(self.size, a, replace=False)
            return (l)
class TwoOPT:
    """
    2-opt:
          Generate intial tour
          and improve it by deleting 1 one edges
          and change with other
    -- It gives nearly optimal tour    
    """

    def __init__(self, file):
        """
            Intialize: Instaces file,
                       Distance Matrix,
                       and size
        """
        self.file = file
        self.instance = ReadData(self.file)
        self.size = self.instance.size
        self.dis_mat = self.instance.GetDistanceMat()
        self.time_read = self.instance.time_to_read
        self.time_algo = 0

    def get_initial_tour(self):
        """
        Return: intial tour
        """
        return [*range(1, self.size + 1)]

    def Swap(self, tour, x, y):
        """
            tour : Given TSP tour
            x = swappping First index in tour 
            y = swappping last index in tour
            return : new_tour with perfomming swapping 
            note: x and y should be index only (in tour) not exact city number
        """
        new_tour = tour[:x] + [*reversed(tour[x:y + 1])] + tour[y + 1:]
        return new_tour

    def get_distance(self, tour):
        """
        Given any tour it return total distance of
        given tour
        dis_mat : distance matrix 
        """
        total_dis = 0
        for ind, r in enumerate(tour):
            _from = r
            if ind + 1 == len(tour):
                _to = tour[0]
                total_dis += self.dis_mat[_from - 1][_to - 1]
            else:
                _to = tour[ind + 1]
                total_dis += self.dis_mat[_from - 1][_to - 1]
        return total_dis

    def _optimize(self, initial_tour, Debuglevel=0):
        """
            Improve existing tour 
            using 2-opt method
        """
        minchange = -1
        tour = initial_tour
        while minchange < 0:
            minchange = 0
            for i in range(self.size - 3):
                for j in range(i + 2, self.size - 1):
                    t1 = tour[i]
                    t2 = tour[i + 1]
                    t3 = tour[j]
                    t4 = tour[j + 1]

                    change = (self.dis_mat[t1 - 1][t3 - 1] +
                              self.dis_mat[t2 - 1][t4 - 1] -
                              self.dis_mat[t1 - 1][t2 - 1] -
                              self.dis_mat[t3 - 1][t4 - 1])
                    if change < minchange:
                        minchange = change
                        tour = self.Swap(tour, i + 1, j)
            if Debuglevel:
                print("Tour After Change : ", minchange, "Distances: ",
                      self.get_distance(tour))
        self.best_tour = tour
        return tour

    def _initial_random_tour(self,seed):
        """"
        Return randomly generated tour
        """
        np.random.seed(seed)
        T = np.arange(1,self.size+1)
        np.random.shuffle(T)
        return list(T)

    def run(self):
        tours = []
        tours_dist = []
        #self._write_info()
        for r in range(1):
            T = self._initial_random_tour(r)
            tour = self._optimize(T)
            tour_distance = self.get_distance(tour)
            tours.append(tour)
            tours_dist.append(tour_distance)

        min_dist_index = np.argmin(tours_dist)
        return (tours_dist[min_dist_index], tours[min_dist_index])
        

    """def _write_info(self):
from readData import ReadData
from SA2opt import SimAnneal
import matplotlib.pyplot as plt
import random
import numpy as np


import sys 
if len(sys.argv)<2:
	print("need inpute file")
	sys.exit(1)
filename = sys.argv[1]
D = ReadData(filename)

if __name__ == "__main__":
    # coords = [[random.uniform(-1000, 1000), random.uniform(-1000, 1000)] for i in range(100)]
    sa = SimAnneal(D.GetDistanceMat(),filename)#, stopping_iter=2)
    sa.anneal()
    #sa.batch_anneal()
    #sa.visualize_routes()
    sa.plot_learning()