Example #1
0
def generate_simulation(num_cities, min_coord, max_coord, trials, directory):
	t = TSP()
	t.randomize(str(num_cities), num_cities, min_coord, max_coord)
	if not os.path.exists(directory):
		os.makedirs(directory)
	f = open(os.path.join(directory, '{0}.tsp'.format(num_cities)), 'w+')
	t.write(f)
	f.close()
	zero_padding = int(math.ceil(math.log10(trials)))
	a, b = random.sample(range(num_cities), 2)
	for i in range(trials):
		d = os.path.join(directory, str(i).zfill(zero_padding))
		if not os.path.exists(d):
			os.mkdir(d)
		t_i = copy.deepcopy(t)
		x_a_0, y_a_0 = t_i.replace_node(a, random.uniform(min_coord, max_coord), random.uniform(min_coord, max_coord))
		f = open(os.path.join(d, '{0}_a.tsp'.format(num_cities)), 'w+')
		t_i.write(f)
		f.close()
		x_a_1, y_a_1 = t_i.replace_node(a, x_a_0, y_a_0)
		t_i.replace_node(b, random.uniform(min_coord, max_coord), random.uniform(min_coord, max_coord))
		f = open(os.path.join(d, '{0}_b.tsp'.format(num_cities)), 'w+')
		t_i.write(f)
		f.close()
		t_i.replace_node(a, x_a_1, y_a_1)
		f = open(os.path.join(d, '{0}_ab.tsp'.format(num_cities)), 'w+')
		t_i.write(f)
		f.close()
Example #2
0
def main(ctx, coordinates_file, distances_file, random):
    if random:
        tsp = TSP.from_random()
    elif coordinates_file or distances_file:
        tsp = TSP.from_files(coordinates_file, distances_file)
    else:
        warnings.warn('No problem to solve. Is this what you want?')
        return
    ctx.obj['tsp'] = tsp
Example #3
0
 def __init__(self,
              distance_matrix,
              initial_solution_strategy='greedy',
              neighbor_selection='first',
              neighborhood='2-opt',
              seed=None,
              tabu_size=None):
     TSP.__init__(self, distance_matrix, initial_solution_strategy,
                  neighbor_selection, neighborhood, seed)
     self.tabu_size = tabu_size
     self.tabu_ = [self.current_solution_]
     self.best_solution_ = self.current_solution_
     self.best_cost_ = self.current_cost_
    def createRoute(self, inputs):
        siteid, customerids = inputs

        vertices = [siteid] + customerids
        tsp = TSP(vertices)

        # site to customer edges
        for customerid in customerids:
            tsp.addEdge(siteid, customerid, self.distmat[siteid, customerid])
            tsp.addEdge(customerid, siteid, self.distmat[customerid, siteid])

        # customer to customer edges
        for customerid1 in customerids:
            for customerid2 in customerids:
                if customerid1 != customerid2:
                    tsp.addEdge(customerid1, customerid2,
                                self.distmat[customerid1, customerid2])

        greedytour, greedytourlen = tsp.greedyTour(startnode=siteid)
        threeopttour, threeopttourlen = tsp.threeOPT(greedytour)

        #print(len(customerids))
        #print(threeopttour)

        return threeopttour
Example #5
0
def test4(n=30, tsp_object=None):
    """
	Test concurrently over all possible 
	starting node using multiprocessing module
	"""
    if isinstance(tsp_object, TSP):
        tsp = tsp_object
    else:
        v, e, M = createRandomCompleteGraph(n)
        tsp = TSP(v, e)
    rows = []

    from multiprocessing import Pool
    from itertools import product

    p = Pool(8)
    greedysol = p.map(tsp.greedyTour, tsp.nodes)
    twooptsol = p.map(tsp.twoOPT, [sol[0] for sol in greedysol])
    threeoptsol1 = p.map(callAndTime,
                         [(tsp.threeOPT, sol[0]) for sol in greedysol])
    threeoptsol2 = p.map(callAndTime,
                         [(tsp.threeOPT, sol[0]) for sol in twooptsol])

    for ind in range(n):
        rows.append([
            tsp.nodes[ind], greedysol[ind][1], twooptsol[ind][1],
            threeoptsol1[ind][0][1], threeoptsol1[ind][1],
            threeoptsol2[ind][0][1], threeoptsol2[ind][1]
        ])
    testResultDataFrame(rows)
Example #6
0
def test2(n=500):
    """
	Given number of nodes -
	Test greedy tour using default starting node, 
	two optimal tour using greedy tour
	three optimal tour using greedy tour 
	three optimal tour using two optimal tour
	"""
    v, e, M = createRandomCompleteGraph(n)
    tsp = TSP(v, e)

    print("Greedy tour")
    (greedytour, greedytourlen), time = callAndTime((tsp.greedyTour, ))
    print(greedytour, greedytourlen, time)

    print("\n2OPT")
    (twoopttour, twooptlen), time = callAndTime((tsp.twoOPT, greedytour))
    print(twoopttour, twooptlen, time)

    print("\n3OPT Using greedytour")
    (threeopttour, threeoptlen), time = callAndTime((tsp.threeOPT, greedytour))
    print(threeopttour, threeoptlen, time)

    print("\n3OPT Using 2OPT tour")
    (threeopttour, threeoptlen), time = callAndTime((tsp.threeOPT, twoopttour))
    print(threeopttour, threeoptlen, time)
Example #7
0
 def __init__(self,
              distance_matrix,
              initial_solution_strategy='greedy',
              neighbor_selection='first',
              neighborhood='2-opt',
              seed=None,
              t_max=100,
              t_min=0.01,
              cooling_function=(lambda (t, i): t * 0.99),
              max_iterations_at_each_t=50):
     TSP.__init__(self, distance_matrix, initial_solution_strategy,
                  neighbor_selection, neighborhood, seed)
     self.t_max = float(t_max)
     self.t_min = float(t_min)
     self.cooling_function = cooling_function
     self.max_iterations_at_each_t = max_iterations_at_each_t
Example #8
0
def main():
    genes = utils.parse_input(input_path)

    print("Running Genetic Algorithm on TSP problem with {} cities.".format(
        len(genes)))

    result = TSP.run(genes, population_size, n_generation, tournament_size,
                     mutation_rate)
Example #9
0
def test6(n=50):
    v, e, M = createRandomCompleteGraph(n)
    tsp = TSP(v, e)
    #ret, time = callAndTime((test3, n, tsp))
    #print(ret, time)

    ret, time = callAndTime((test4, n, tsp))
    print(ret, time)
Example #10
0
 def __init__(self, data_type='small'):
     self.tsp = TSP(data_type)
     self.data_type = data_type
     self.numant = 100  # 蚂蚁个数
     self.numcity = len(self.tsp.cities)  # 点的数量
     self.alpha = 1  # 信息素重要程度因子
     self.beta = 5  # 启发函数重要程度因子
     self.rho = 0.1  # 信息素的挥发速度
     self.Q = 1  # 完成率
     self.itermax = 100  # 迭代总数
     self.pheromonetable = np.ones((self.numcity, self.numcity))  # 信息素矩阵
     self.distances = self.get_dis()
     self.lengthaver = []  # 迭代,存放每次迭代后,路径的平均长度
     self.lengthbest = []  # 迭代,存放每次迭代后,最佳路径长度
     self.pathbest = []
     self.pathbest_length = None
     self.result_dir = os.path.join(sys.path[0],'Results')
Example #11
0
 def __init__(self, data_type='small'):
     self.tsp = TSP(data_type)
     self.data_type = data_type
     self.cross_rate = 0.2  # 交叉概率 不能太大
     self.mutate_rate = 0.02  # 变异概率 选择两个点进行互换位置
     self.numcity = len(self.tsp.cities)  # 点的数量
     self.pop_size = 500  # 种群数量
     self.itermax = 1000  # 迭代轮数
     self.pop = np.vstack([np.random.permutation(self.numcity) for _ in range(self.pop_size)])  # 整个种群
     self.scale = None # 对距离缩放的尺度
     self.update_fitness()
     # 存放最优路径和最优路径对应的长度
     self.lengthaver = []  # 迭代,存放每次迭代后,路径的平均长度
     self.lengthbest = []  # 迭代,存放每次迭代后,最佳路径长度
     self.pathbest = []
     self.pathbest_length = None
     self.result_dir = os.path.join(sys.path[0], 'Results')
def main():

    simulation_runs = 5
    num_ants = 5
    q = 10000
    nc_max = 100

    aco = ACO(simulation_runs=simulation_runs,
              num_ants=num_ants,
              pheromone_quantity=q,
              num_colonies=nc_max)
    tsp = TSP()

    graph_nodes_list = [9, 10, 11]
    alpha_list = [1, 3, 7]
    beta_list = [1, 3, 7]
    ro_list = [0.0, 0.5, 0.9, 1.0]
    table_data = []

    for graph_nodes in graph_nodes_list:
        cost_graph = create_graph(graph_nodes)
        # print_graph(cost_graph)
        total_tsp_cost, tsp_solution = tsp.run(cost_graph)
        for alpha in alpha_list:
            for beta in beta_list:
                for ro in ro_list:
                    print(
                        "graph_nodes = {3}, alpha = {0}, beta = {1}, ro = {2}".
                        format(alpha, beta, ro, graph_nodes))
                    solution, total_aco_cost = aco.run(cost_graph, alpha, beta,
                                                       ro)
                    error_value = abs(total_tsp_cost - total_aco_cost)
                    table_data += [[
                        str(graph_nodes),
                        str(alpha),
                        str(beta),
                        str(ro),
                        str(total_aco_cost),
                        str(total_tsp_cost),
                        str(error_value)
                    ]]
                    pass

    print_table_data(table_data)
Example #13
0
def generate_simulation(num_cities, min_coord, max_coord, trials, directory):
    t = TSP()
    t.randomize(str(num_cities), num_cities, min_coord, max_coord)
    if not os.path.exists(directory):
        os.makedirs(directory)
    f = open(os.path.join(directory, '{0}.tsp'.format(num_cities)), 'w+')
    t.write(f)
    f.close()
    zero_padding = int(math.ceil(math.log10(trials)))
    a, b = random.sample(range(num_cities), 2)
    for i in range(trials):
        d = os.path.join(directory, str(i).zfill(zero_padding))
        if not os.path.exists(d):
            os.mkdir(d)
        t_i = copy.deepcopy(t)
        x_a_0, y_a_0 = t_i.replace_node(a,
                                        random.uniform(min_coord, max_coord),
                                        random.uniform(min_coord, max_coord))
        f = open(os.path.join(d, '{0}_a.tsp'.format(num_cities)), 'w+')
        t_i.write(f)
        f.close()
        x_a_1, y_a_1 = t_i.replace_node(a, x_a_0, y_a_0)
        t_i.replace_node(b, random.uniform(min_coord, max_coord),
                         random.uniform(min_coord, max_coord))
        f = open(os.path.join(d, '{0}_b.tsp'.format(num_cities)), 'w+')
        t_i.write(f)
        f.close()
        t_i.replace_node(a, x_a_1, y_a_1)
        f = open(os.path.join(d, '{0}_ab.tsp'.format(num_cities)), 'w+')
        t_i.write(f)
        f.close()
Example #14
0
    def loadTSP(name):
        """Returns a TSP problem instance from a study name"""
        with open(DISTANCE_FILE_ROOT.format(name), "r") as myfile:
            lines = myfile.readlines()
        distances = []
        for line in lines:
            distance = line.split()
            distance = [int(d.strip()) for d in distance]
            distances.append(distance)
        with open(SOLUTION_DISTANCE_FILE_ROOT.format(name), "r") as myfile:
            line = myfile.readline()
        absolute_best_distance = int(line.strip())

        return TSP(name, distances, absolute_best_distance)
Example #15
0
def test3(n=30, tsp_object=None):
    """
	Test sequentially over all possible starting
	node
	"""
    if isinstance(tsp_object, TSP):
        tsp = tsp_object
    else:
        v, e, M = createRandomCompleteGraph(n)
        tsp = TSP(v, e)

    rows = []
    for v_ in tsp.nodes:
        greedytour, greedytourlen = tsp.greedyTour(v_)
        twoopttour, twooptlen = tsp.twoOPT(greedytour)
        (threeopttour1, threeoptlen1), time1 = callAndTime(
            (tsp.threeOPT, greedytour))
        (threeopttour2, threeoptlen2), time2 = callAndTime(
            (tsp.threeOPT, twoopttour))
        rows.append([
            v_, greedytourlen, twooptlen, threeoptlen1, time1, threeoptlen2,
            time2
        ])
    testResultDataFrame(rows)
def histogram():
    num_bins = 40
    start_temp, stop_temp = temps[-1], 1e-6
    bestDistanceListEX = []
    bestDistanceListL = []
    factor_linear = start_temp / ITER
    factor_exp = np.exp(np.log(stop_temp / start_temp) / ITER)
    for i in range(200):
        tsp_linear = TSP(coords, temps[-1], stop_temp, "linear", factor_linear)
        tsp_exp = TSP(coords, start_temp, stop_temp, "exponential", factor_exp)
        tsp_linear.simulated_annealing()
        tsp_exp.simulated_annealing()
        print("Linear:", tsp_linear.best_distance)
        print("Exponential:", tsp_exp.best_distance)
        bestDistanceListL.append(round(tsp_linear.best_distance, 2))
        bestDistanceListEX.append(round(tsp_exp.best_distance, 2))
        print("iteration:", i)
    print(bestDistanceListL)
    print(bestDistanceListEX)
    # plt.hist(bestDistanceListL, num_bins,facecolor='blue', alpha=0.5)
    # plt.xlabel('Distance')
    # plt.ylabel('Amount')
    # plt.title('Best estimated distances for linear cooling schemes')
    # plt.savefig("eil51/linear_cooling/histogram_linear.pdf", dpi=300)
    # newbestDistanceListL = np.asarray(bestDistanceListL)
    # np.save(f"eil51/LinearBestDistanceHist.npy", newbestDistanceListL)

    # plt.show()
    # plt.hist(bestDistanceListEX,num_bins, facecolor='blue', alpha=0.5)
    # plt.xlabel('Distance')
    # plt.ylabel('Amount')
    # plt.title('Best estimated distances for exponential cooling schemes')
    # plt.savefig("eil51/exp_cooling/histogram_exponential.pdf", dpi=300)
    # newbestDistanceListEX = np.asarray(bestDistanceListEX)
    # np.save(f"eil51/EXBestDistanceHist.npy", newbestDistanceListEX)

    plt.show()
    return bestDistanceListL, bestDistanceListEX
Example #17
0
File: ref.py Project: esavaner/AMH
from pso import PSO
from tsp import TSP

if __name__ == "__main__":
    t, n, s, w, g1, g2 = map(float, input().split())
    t, n, s = map(int, [t, n, s])
    grid = [[int(c) for c in input().split()[:n]] for _ in range(n)]
    tsp = TSP(grid, n)
    pso = PSO(tsp, s, w, g1, g2)
    minPos, minimum = pso.test(t)
    print('\nNajkrotsza znaleziona sciezka:', minPos, 'odleglosc:', minimum)
Example #18
0
class GaTsp:
    '''
    利用遗传算法解决TSP问题
    输入数据类型
    '''
    def __init__(self, data_type='small'):
        self.tsp = TSP(data_type)
        self.data_type = data_type
        self.cross_rate = 0.2  # 交叉概率 不能太大
        self.mutate_rate = 0.02  # 变异概率 选择两个点进行互换位置
        self.numcity = len(self.tsp.cities)  # 点的数量
        self.pop_size = 500  # 种群数量
        self.itermax = 1000  # 迭代轮数
        self.pop = np.vstack([np.random.permutation(self.numcity) for _ in range(self.pop_size)])  # 整个种群
        self.scale = None # 对距离缩放的尺度
        self.update_fitness()
        # 存放最优路径和最优路径对应的长度
        self.lengthaver = []  # 迭代,存放每次迭代后,路径的平均长度
        self.lengthbest = []  # 迭代,存放每次迭代后,最佳路径长度
        self.pathbest = []
        self.pathbest_length = None
        self.result_dir = os.path.join(sys.path[0], 'Results')

    def find_path(self, iterations=None):
        '''
        寻找最短路径
        '''
        if iterations is None:
            iterations = self.itermax
        for iter in range(iterations):
            # 迭代itermax轮
            # 交叉、配对、变异
            pop = self.select()
            pop_copy = pop.copy()
            for parent in pop:  # for every parent
                child = self.crossover(parent, pop_copy)
                child = self.mutate(child)
                parent[:] = child
            self.pop = pop
            self.update_fitness()
            # 保存最优值
            min_index = self.fit.argmax()
            self.lengthbest.append(self.distances.min())
            self.lengthaver.append(self.distances.mean())
            if self.pathbest == []:
                # 第一次
                self.pathbest = self.pop[min_index].copy()
                self.pathbest_length = self.distances[min_index]
            else:
                # 如果当前不是最优,继续更改
                if self.pathbest_length > self.distances[min_index]:
                    self.pathbest_length = self.distances[min_index]
                    self.pathbest = self.pop[min_index].copy()
            print('Iterations:%d,ave_length:%.2f,best_length:%.2f,global best:%.2f' % (
                iter + 1, self.lengthaver[-1], self.lengthbest[-1], self.pathbest_length))

    def select(self):
        '''
        按照fitness值选择配对父母,未选择到的自行淘汰
        '''
        index = np.random.choice(np.arange(
            self.pop_size), size=self.pop_size, replace=True, p=self.fit / self.fit.sum())
        return self.pop[index].copy()

    def crossover(self, parent, pop):
        '''
        从pop中选择一个父代与parent产生子代
        如果不交叉的话直接继承父代的特性
        '''
        if np.random.rand() < self.cross_rate:
            index = np.random.randint(0, self.pop_size, size=1)  # 选择另一个亲代
            cross_points = np.random.randint(
                0, 2, self.numcity).astype(np.bool)
            # 选择交叉点,numcity个0或者1的随机数
            keep_city = parent[~cross_points]  # 取出父代保留的城市
            swap_city = pop[index, np.isin(
                pop[index].ravel(), keep_city, invert=True)]
            parent[:] = np.concatenate((keep_city, swap_city))
        return parent

    def mutate(self, child):
        '''
        对路径进行变异,两个点进行交换
        '''
        for point in range(self.numcity):
            if np.random.rand() < self.mutate_rate:
                swap_point = np.random.randint(0, self.numcity)
                swapA, swapB = child[point], child[swap_point]
                child[point], child[swap_point] = swapB, swapA
        return child

    def update_fitness(self):
        '''
        得到当前种群的评价
        距离和适应值
        '''
        self.distances = np.array([self.tsp.get_fitness(pop) for pop in self.pop])
        if self.scale is None:
            self.scale = self.distances.max()
        self.fit = self.get_fitness(self.distances)
    
    def get_fitness(self,dis):
        '''
        将距离转化为适应值
        '''
        return np.exp(self.scale*3/(dis))

    def plot_result(self):
        
        self.tsp.plot_map(self.pathbest)

    def save_result(self):
        self.tsp.plot_map(self.pathbest)
        plt.savefig(os.path.join(self.result_dir,
                                 'GA_%s.png' % self.data_type))
Example #19
0
        for j in range(sorted_generation.__len__() - 1):
            if eval_solution(generation[i]) > eval_solution(generation[j]):
                tmp = generation[j]
                generation[j] = generation[i]
                generation[i] = tmp


def randomly_delete(generation):
    print "randomly deleting a member of the population to make it even"
    r = randrange(0, generation.__len__())
    generation.pop(r)
    

if __name__ == '__main__':
    print "Genetic Algorithm (e.g. chromosome => [0,1,2,3,4,5,6,7] "
    tsp_problem = TSP(8)        # use 8 cities from now, use sys.argv later
    cities_distances = tsp_problem.compute_distances()
    locuses = cities_distances[0].__len__() # loci?
    p_c = 0.7                   # crossover probability
    p_m = 0.001                 # mutation probability, tried with 0.005...
    best_generation = []
    n = 8                       # number of chromosomes in the generation
    max_generations = 2
    generation = []
    generation_fitnesses = []
    base = range(0,locuses)           # [0,1,2,3,4,5,6,7]
   

    # Create a random first generation
    for i in range(n):
        next = base[:]
Example #20
0
 def __init__(self, filename):
     self.paths = []
     self.tsp = TSP(filename)
Example #21
0
class AntTsp:
    def __init__(self, data_type='small'):
        self.tsp = TSP(data_type)
        self.data_type = data_type
        self.numant = 100  # 蚂蚁个数
        self.numcity = len(self.tsp.cities)  # 点的数量
        self.alpha = 1  # 信息素重要程度因子
        self.beta = 5  # 启发函数重要程度因子
        self.rho = 0.1  # 信息素的挥发速度
        self.Q = 1  # 完成率
        self.itermax = 100  # 迭代总数
        self.pheromonetable = np.ones((self.numcity, self.numcity))  # 信息素矩阵
        self.distances = self.get_dis()
        self.lengthaver = []  # 迭代,存放每次迭代后,路径的平均长度
        self.lengthbest = []  # 迭代,存放每次迭代后,最佳路径长度
        self.pathbest = []
        self.pathbest_length = None
        self.result_dir = os.path.join(sys.path[0],'Results')

    def find_path(self, iterations=None):
        if iterations is None:
            iterations = self.itermax
        for iter in range(iterations):
            # 迭代itermax轮
            paths = []  # 本轮每个蚂蚁走过的路径
            lengths = []  # 每个蚂蚁的本轮走过的长度
            start_index = 0  # 从第0个开始寻找
            for ant in range(self.numant):
                # 每个蚂蚁开始找路
                visiting = start_index
                length = 0
                unvisited = list(range(self.numcity))
                unvisited.remove(visiting)  # 删除已经访问过的点
                paths.append([visiting])  # 添加刚经过的节点
                while True:
                    # 根据概率选择下个要探索的点
                    probtrans=[]  # 每次循环都初始化转移概率矩阵
                    for city in unvisited:
                        probtrans.append(np.power(self.pheromonetable[visiting, city], self.alpha)
                            * np.power(1.0/self.distances[visiting, city], self.alpha))
                    # 利用轮盘赌来找到需要探索的点
                    probtrans=np.array(probtrans)
                    cumsumprobtrans=(probtrans / sum(probtrans)).cumsum()
                    cumsumprobtrans -= np.random.rand()
                    k=list(cumsumprobtrans >= 0).index(True)  # 找到在list中的索引值
                    next_city=unvisited[k]
                    length += self.distances[visiting, next_city]
                    paths[ant].append(next_city)
                    # 选择下个点
                    visiting=next_city
                    unvisited.remove(visiting)  # 删除已经访问过的城市元素
                    if unvisited == []:
                        length += self.distances[visiting, start_index]
                        paths[ant].append(start_index)
                        break
                # 结束之后添加长度
                lengths.append(length)
            # 进行信息素更新
            changepheromonetable=np.zeros((self.numcity, self.numcity))
            lengths=np.array(lengths)
            min_index=lengths.argmin()
            self.lengthbest.append(lengths.min())
            self.lengthaver.append(lengths.mean())
            if self.pathbest == []:
                # 第一次
                self.pathbest=paths[min_index].copy()
                self.pathbest_length=lengths[min_index]
            else:
                # 如果当前不是最优,继续更改
                if self.pathbest_length > lengths[min_index]:
                    self.pathbest_length=lengths[min_index]
                    self.pathbest=paths[min_index].copy()
            for i in range(len(paths)):  # 更新所有的蚂蚁
                path=paths[i]
                for j in range(len(path)-1):
                    changepheromonetable[path[j], path[j+1]] +=  self.Q*10 / self.distances[path[j],path[j+1]]
            print('Iterations:%d,ave_length:%.2f,best_length:%.2f,global best:%.2f' % (iter+1, self.lengthaver[-1], self.lengthbest[-1], self.pathbest_length))
            self.pheromonetable=(1 - self.rho) * self.pheromonetable + changepheromonetable

    def get_dis(self):
        '''
        得到城市之间的距离矩阵
        '''
        distances=np.zeros((self.numcity,self.numcity))
        for i in range(self.numcity):
            for j in range(self.numcity):
                if i == j:
                    continue
                elif i > j:
                    # 计算过就不用算了
                    distances[i, j]=distances[j, i]
                else:
                    distances[i, j]=np.linalg.norm(self.tsp.cities[i]-self.tsp.cities[j])+1e-2
        return distances

    def plot_result(self):
        self.tsp.plot_map(self.pathbest)

    def save_result(self):
        self.tsp.plot_map(self.pathbest)
        plt.savefig(os.path.join(self.result_dir,'ACO_%s.png'%self.data_type))
Example #22
0
File: algo.py Project: afofa/tsp

if __name__ == '__main__':
    from city import City2D
    from tsp import TSP
    from ea import EvolutionaryAgent

    # c1 = City2D(35, "Izmir", 0, 0)
    # c2 = City2D(6, "Ankara", 6, 8)
    # c3 = City2D(34, "Istanbul", 6, 0)
    # c4 = City2D(9, "Aydin", -2, -3)
    # c5 = City2D(1, "Adana", -7, -12)
    # c6 = City2D(45, "Manisa", 1, 1)
    # c7 = City2D(10, "Balikesir", 12, 14)
    # c8 = City2D(81, "Duzce", 20, 12)

    # cs = [c1, c2, c3, c4, c5, c6, c7, c8]
    num_of_cities = 500
    scale = 200
    cs = [
        City2D(i, f"City{i}",
               random.random() * scale,
               random.random() * scale) for i in range(num_of_cities)
    ]

    tsp = TSP(cs)

    eas = [EvolutionaryAgent() for i in range(100)]

    algo = EvolutionaryAlgorithm(tsp, eas)
    algo.run_algorithm()
Example #23
0
from tsp import TSP
from SA import SimulatedAnnealing
from ga import GeneticAlgorithm
#import numpy as np
tsp = TSP(20, True)
tsp.showSA(list(range(0, 20)))
"""
lst = []
l = list(range(0,20))
for i in range(40):
    x = tsp.energia(l)
    l = tsp.move(l)
    lst.append(np.abs(tsp.energia(l)-x))
print(np.mean(lst))
print(np.std(lst))
"""
par = {
    "crossover.type": "permutation.ox",
    "elitism": True,
    "n.generations": 100,
    "n.individuals": 100,
    "p.crossover": 0.8,
    "p.mutation": 0.1,
    "selection.type": "tournament.selection",
    "tournament.size": 4,
    "type": "permutation"
}

#Con estos parámetros nunca encuentra la solución, porque el mutation rate es muy bajo, no es elitista, y el tamaño del torneo es demasiado bajo
"""
par = {"crossover.type" : "permutation.ox",
Example #24
0
def trip_estimator():
    #lyft = lyft()
    global lyft
    data1 = json.loads(request.data)
    startID = data1['start']
    locationsID = data1['others']

    alllocations = []
    alllocations.append(int(startID))
    for i in range(len(locationsID)):
        alllocations.append(int(locationsID[i]))
    #print alllocations

    #start_location = Location_API.query.filter_by(id=start).first_or_404()
    #alllocations.append(start_location.id)
    #end_location = Location_API.query.filter_by(id=start).first_or_404()

    #create a dictionary for mapping the matrix numbers to the locatcation ids
    location = []
    for i in range(len(alllocations)):
        location.append(
            Location_API.query.filter_by(id=alllocations[i]).first_or_404())
        #print location[i]
        #print location[i].lat
        #alllocations.append(location[i].id)

    matrixlength = len(alllocations)
    Ubermatrix = [[0 for row in range(0, matrixlength)]
                  for col in range(0, matrixlength)]
    for i in range(matrixlength):
        for j in range(matrixlength):
            if i == j:
                Ubermatrix[i][j] = 0
            else:
                Ubermatrix[i][j] = uber.uber_price(location[i].lat,
                                                   location[i].lng,
                                                   location[j].lat,
                                                   location[j].lng)
    #print Ubermatrix[i][j]

    #x = uber.uber_price(location[0].lat, location[0].lng, location[0].lat, location[0].lng)
    #print x
    #lyft = lyft()
    lyftmatrix = [[0 for row in range(0, matrixlength)]
                  for col in range(0, matrixlength)]
    for i in range(matrixlength):
        for j in range(matrixlength):
            if i == j:
                lyftmatrix[i][j] = 0
            else:
                lyftmatrix[i][j] = lyft.lyft_price(location[i].lat,
                                                   location[i].lng,
                                                   location[j].lat,
                                                   location[j].lng)
    #print lyftmatrix[i][j]
    #for i in range(matrixlength):
    #	for j in range(matrixlength):
    #		print Ubermatrix[i][j]
    bestroute_uber = TSP(Ubermatrix).getFinalCityFlow()
    bestroute_lyft = TSP(lyftmatrix).getFinalCityFlow()

    #print bestroute_uber
    #print bestroute_lyft

    Uber_bestroute_prices = []
    Uber_bestroute_distance = []
    Uber_bestroute_duration = []

    uber_best_route = bestroute_uber.split('->')
    #print uber_best_route
    uber_best_route_locations = []
    for i in range(0, len(uber_best_route) - 1):
        #print uber_best_route[i]
        uber_best_route_locations.append(
            str(location[int(uber_best_route[i])].name))
        Uber_bestroute_prices.append(
            uber.uber_price(location[int(uber_best_route[i])].lat,
                            location[int(uber_best_route[i])].lng,
                            location[int(uber_best_route[i + 1])].lat,
                            location[int(uber_best_route[i + 1])].lng))
        Uber_bestroute_distance.append(
            uber.uber_distance(location[int(uber_best_route[i])].lat,
                               location[int(uber_best_route[i])].lng,
                               location[int(uber_best_route[i + 1])].lat,
                               location[int(uber_best_route[i + 1])].lng))
        Uber_bestroute_duration.append(
            uber.uber_duration(location[int(uber_best_route[i])].lat,
                               location[int(uber_best_route[i])].lng,
                               location[int(uber_best_route[i + 1])].lat,
                               location[int(uber_best_route[i + 1])].lng))

    #print Uber_bestroute_prices
    uber_price_total = sum(Uber_bestroute_prices)
    uber_distance_total = sum(Uber_bestroute_distance)
    uber_duration_total = sum(Uber_bestroute_duration)
    #print uber_price_total

    lyft_bestroute_prices = []
    lyft_bestroute_distance = []
    lyft_bestroute_duration = []

    lyft_best_route = bestroute_lyft.split('->')
    #print lyft_best_route
    lyft_best_route_locations = []
    for i in range(0, len(lyft_best_route) - 1):
        #print lyft_best_route[i]
        lyft_best_route_locations.append(
            str(location[int(lyft_best_route[i])].name))
        lyft_bestroute_prices.append(
            lyft.lyft_price(location[int(lyft_best_route[i])].lat,
                            location[int(lyft_best_route[i])].lng,
                            location[int(lyft_best_route[i + 1])].lat,
                            location[int(lyft_best_route[i + 1])].lng))
        lyft_bestroute_distance.append(
            lyft.lyft_distance(location[int(lyft_best_route[i])].lat,
                               location[int(lyft_best_route[i])].lng,
                               location[int(lyft_best_route[i + 1])].lat,
                               location[int(lyft_best_route[i + 1])].lng))
        lyft_bestroute_duration.append(
            lyft.lyft_duration(location[int(lyft_best_route[i])].lat,
                               location[int(lyft_best_route[i])].lng,
                               location[int(lyft_best_route[i + 1])].lat,
                               location[int(lyft_best_route[i + 1])].lng))

    #print lyft_bestroute_prices

    lyft_price_total = sum(lyft_bestroute_prices)
    lyft_distance_total = sum(lyft_bestroute_distance)
    lyft_duration_total = sum(lyft_bestroute_duration)
    #print lyft_price_total

    # "best_route_by_costs"

    uber_best_route_locations.pop(0)
    lyft_best_route_locations.pop(0)
    if lyft_price_total < uber_price_total:
        best_route_by_costs = lyft_best_route_locations
        start_location = str(location[int(lyft_best_route[0])].name)
    else:
        best_route_by_costs = lyft_best_route_locations
        start_location = str(location[int(uber_best_route[0])].name)
    #print best_route_by_costs

    #"providers"

    providers = []

    uber_response = {
        "name": "Uber",
        "total_costs_by_cheapest_car_type": uber_price_total,
        "currency_code": "USD",
        "total_duration": uber_duration_total,
        "duration_unit": "minute",
        "total_distance": uber_distance_total,
        "distance_unit": "mile"
    }
    lyft_response = {
        "name": "Lyft",
        "total_costs_by_cheapest_car_type": lyft_price_total,
        "currency_code": "USD",
        "total_duration": lyft_duration_total,
        "duration_unit": "minute",
        "total_distance": lyft_distance_total,
        "distance_unit": "mile"
    }

    providers.append(uber_response)
    providers.append(lyft_response)

    trip_planner_response = {
        "start": start_location,
        "best_route_by_costs": best_route_by_costs,
        "providers": providers,
        "end": start_location
    }
    return json.dumps(trip_planner_response)
Example #25
0
    parser.add_argument("--asys", action="store_true")
    parser.add_argument("--eas", action="store_true")
    parser.add_argument("--ras", action="store_true")
    parser.add_argument("--mmas", action="store_true")
    parser.add_argument("--bwas", action="store_true")
    parser.add_argument("--acs", action="store_true")
    parser.add_argument("--quiet", action="store_true")

    args = parser.parse_args()

    return args


if __name__ == "__main__":

    args = parse_arguments()
    heuristic = Metaheuristic(args)

    tsplibfile = args.tsplibfile
    instance = TSP(tsplibfile)

    n = instance.n
    heuristic.update_parameters(n)

    nn = max(heuristic.nn_ls, heuristic.nn_ants)
    instance.compute_nn_lists(nn)
    instance.report("instance_report.txt")

    ant_colony = AntColony(heuristic, instance)
    ant_colony.report("ant_colony_report.txt")
Example #26
0
def tsp_obj(coordinates_file, distances_file):
    return TSP.from_files(coordinates_file, distances_file)
Example #27
0
from tsp import TSP
from math import inf

generations = 10
population_size = 4
mutation_chance = 0.2
adj_matrix = [[inf, 10, 8, 3],
              [10, inf, 4, 2],
              [8, 4, inf, 1],
              [3, 2, 1, inf]]


instance = TSP(adj_matrix, generations, population_size, mutation_chance)
instance.genetic_algorithm()
population = instance.get_population()

print("Number of generations: {}\nSize of the population:{}\nMutation chance:{}".format(
    generations, population_size, mutation_chance))

print("The best individual is {} and its fitness is {}".format(
    population[0], instance.get_fitness(population[0])))
Example #28
0
from point import Point
from tsp import TSP
from gui import GUI
import genetic_algorithms as GA

SCREEN = GUI()
POINTS = [Point.random() for _ in range(50)]
# Initialise
solver = TSP(POINTS, 300, 150)

solver.distance2fitness = lambda distance: 1 / (distance**4)
solver.fitness2distance = lambda fitness: 1 / (fitness**(1 / 4))

solver.initialise_population()
solver.set_parent_selection(GA.stochastic_universal_sampling)
solver.set_crossover(GA.edge_recombination_operator)
#solver.set_mutation(GA.cycle_inversion_mutation, 0.2, k=10)
solver.set_mutations([GA.cycle_inversion_mutation, GA.swap_mutation],
                     [0.4, 0.5], [2, 2])
solver.set_survivor_selection(GA.stochastic_universal_sampling_index)

while True:
    solver.evolve(1)
    SCREEN.display(solver.population, solver.fitnesses, solver.distances,
                   solver.generation)
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 21 22:03:10 2018

@author: 周宝航
"""

from genetic_algorithm import TSPGA
from tsp import TSP

N_CITIES = 20
CROSS_RATE = 0.1
MUTATE_RATE = 0.08
POP_SIZE = 500
N_GENERATIONS = 100

tsp_model = TSP(N_CITIES)
ga = TSPGA(N_CITIES, POP_SIZE, tsp_model,
                 cross_rate=CROSS_RATE, mutation_rate=MUTATE_RATE,
                 n_generations=N_GENERATIONS)

ga.evolve()