Пример #1
0
    def initial_solution(self):
        """
        初始化贪心算法的路径,以便后续模拟退火算法来进行优化
        :return: 贪心算法最短路径已经路径长度
        """
        i_nodes = random.choice(self.nodes)
        # 随机寻找初始城市/节点
        node_solution = [i_nodes]
        # 节点加入列表
        f_nodes = set(self.nodes)
        # 定义空闲城市列表/节点
        f_nodes.remove(i_nodes)
        # 释放随机寻找到的初始城市/节点

        while f_nodes:
            next_node = min(f_nodes, key=lambda x: self.dist(i_nodes, x))
            # 求最近节点
            f_nodes.remove(next_node)
            node_solution.append(next_node)
            # 添加最近节点至解决路径里
            i_nodes = next_node
            # 遍历节点

        current_fit = self.fitness(node_solution)
        if current_fit < self.best_fitness:
            self.best_fitness = current_fit
            self.best_solution = node_solution
        self.fitness_list.append(current_fit)
        visualize_tsp.plotTSP([node_solution], self.places)
        return node_solution, current_fit
Пример #2
0
 def visualize_routes(self):
     """
     Visualize the TSP route with matplotlib.
     """
     visualize_tsp.plotTSP([self.best_solution], self.coords)
Пример #3
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()
    
Пример #4
0
 def visualizeRotes(self):
     '''
     Visualize the TSP route with matplotlib
     '''
     visualize_tsp.plotTSP([self.best_solution], self.coords)
 def visualize_routes(self):
     visualize_tsp.plotTSP([self.best_solution], self.coords)
Пример #6
0
from sa import sa
import visualize_tsp

if __name__ == "__main__":
    sa1 = sa()
    sa1.ann()
    sol, pla = sa1.r_sol()
    visualize_tsp.plotTSP([sol], pla)