【PYTHON数学建模编程实战】五种智能算法求解TSP问题含代码——数学建模必备!(禁忌搜索算法、粒子群优化算法、模拟退火算法、遗传算法、蚁群算法)

【PYTHON数学建模编程实战】五种智能算法求解TSP问题含代码——数学建模必备!(禁忌搜索算法、粒子群优化算法、模拟退火算法、遗传算法、蚁群算法)

欢迎关注,高强度更新和MATLAB,PYTHON编程,C++编程,算法编程,深度学习,自然语言处理,图像处理,OPENCV等相关知识:)

【PYTHON数学建模编程实战】五种智能算法求解TSP问题含代码——数学建模必备!(禁忌搜索算法、粒子群优化算法、模拟退火算法、遗传算法、蚁群算法)

文件内容如图所示,其中还有一个用遗传算法求解最短路径的matlab脚本:
在这里插入图片描述
结果如图所示:
在这里插入图片描述
这里给出遗传算法的代码:
全部代码和文档下载链接(可一键运行)

#!/usr/bin/python
# _*_ coding:utf-8 _*_
import math
import random
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import sys
from numpy.matlib import rand

from matplotlib.artist import getp
import copy

'''
记录错误,数组直接复制是复制地址
例如, current = route
想要得到一个新的有同样内容的数组,应该用: current = copy.copy(route) 
'''

city_x = []
city_y = []
with open('data45.txt', 'r', encoding='UTF-8') as f:
    lines = f.readlines()
    # 调用readlines()一次读取所有内容并按行返回list给lines
    # for循环每次读取一行
    for line in lines:
        line = line.split('\n')[0]
        line = line.split('\t')
        city_x.append(int(line[1]))
        city_y.append(int(line[2]))
# 城市数量
n = 45
distance = [[0 for col in range(n)] for raw in range(n)]
# 初始温度 结束温度
T0 = 30
Tend = 1e-8
# 循环控制常数
L = 10
# 温度衰减系数
a = 0.98


# 构建初始参考距离矩阵
def getdistance():
    for i in range(n):
        for j in range(n):
            x = pow(city_x[i] - city_x[j], 2)
            y = pow(city_y[i] - city_y[j], 2)
            distance[i][j] = pow(x + y, 0.5)
    for i in range(n):
        for j in range(n):
            if distance[i][j] == 0:
                distance[i][j] = sys.maxsize


# 计算总距离
def cacl_best(rou):
    sumdis = 0.0
    for i in range(n - 1):
        sumdis += distance[rou[i]][rou[i + 1]]
    sumdis += distance[rou[n - 1]][rou[0]]
    return sumdis


# 得到新解
def getnewroute(route, time):
    # 如果是偶数次,二变换法
    current = copy.copy(route)

    if time % 2 == 0:
        u = random.randint(0, n - 1)
        v = random.randint(0, n - 1)
        temp = current[u]
        current[u] = current[v]
        current[v] = temp
    # 如果是奇数次,三变换法
    else:
        temp2 = random.sample(range(0, n), 3)
        temp2.sort()
        u = temp2[0]
        v = temp2[1]
        w = temp2[2]
        w1 = w + 1
        temp3 = [0 for col in range(v - u + 1)]
        j = 0
        for i in range(u, v + 1):
            temp3[j] = current[i]
            j += 1

        for i2 in range(v + 1, w + 1):
            current[i2 - (v - u + 1)] = current[i2]
        w = w - (v - u + 1)
        j = 0
        for i3 in range(w + 1, w1):
            current[i3] = temp3[j]
            j += 1

    return current


def draw(best):
    result_x = [0 for col in range(n + 1)]
    result_y = [0 for col in range(n + 1)]

    for i in range(n):
        result_x[i] = city_x[best[i]]
        result_y[i] = city_y[best[i]]
    result_x[n] = result_x[0]
    result_y[n] = result_y[0]
    print(result_x)
    print(result_y)

    plt.plot(result_x, result_y, marker='>', mec='r', mfc='w', label=u'Route')
    plt.legend()  # 让图例生效
    plt.margins(0)
    plt.subplots_adjust(bottom=0.15)
    plt.xlabel(u"x")  # X轴标签
    plt.ylabel(u"y")  # Y轴标签
    plt.title("TSP Solution")  # 标题

    plt.show()
    plt.close(0)


def solve():
    # 得到距离矩阵
    getdistance()
    # 得到初始解以及初始距离
    route = random.sample(range(0, n), n)
    total_dis = cacl_best(route)
    print("初始路线:", route)
    print("初始距离:", total_dis)
    # 新解
    newroute = []
    new_total_dis = 0.0
    best = route
    best_total_dis = total_dis
    t = T0

    while True:
        if t <= Tend:
            break
        # 令温度为初始温度
        for rt2 in range(L):
            newroute = getnewroute(route, rt2)
            new_total_dis = cacl_best(newroute)
            delt = new_total_dis - total_dis
            if delt <= 0:
                route = newroute
                total_dis = new_total_dis
                if best_total_dis > new_total_dis:
                    best = newroute
                    best_total_dis = new_total_dis
            elif delt > 0:
                p = math.exp(-delt / t)
                ranp = random.uniform(0, 1)
                if ranp < p:
                    route = newroute
                    total_dis = new_total_dis
        t = t * a
    print("现在温度为:", t)
    print("最佳路线:", best)
    print("最佳距离:", best_total_dis)
    draw(best)


if __name__ == "__main__":
    solve()


  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
我可以为您提供一段粒子群算法求解TSP问题Python代码。这段代码可以在Python环境中直接运行。它使用了粒子群算法解决TSP问题,该问题是一个典型的NP完全问题,目前还没有找到多项式时间的有效算法解决它。这段代码非常适合用于路径规划、机器学习、数据爬虫和数据分析处理等领域。 以下是代码的主要内容: ``` # 导入所需的库 import random # 定义粒子类 class Particle: def __init__(self, num_cities): self.num_cities = num_cities self.position = random.sample(range(num_cities), num_cities) self.velocity = [0 * num_cities self.best_position = self.position.copy() self.best_fitness = float("inf") def update_velocity(self, global_best_position, w, c1, c2): for i in range(self.num_cities): r1 = random.random() r2 = random.random() self.velocity[i = ( w * self.velocity[i] + c1 * r1 * (self.best_position[i - self.position[i]) + c2 * r2 * (global_best_position[i - self.position[i]) ) def update_position(self): self.position = [ (self.position[i + int(self.velocity[i])) % self.num_cities for i in range(self.num_cities) ] def evaluate_fitness(self, distance_matrix): fitness = 0 for i in range(self.num_cities): fitness += distance_matrix[self.position[i]][self.position[(i + 1) % self.num_cities]] if fitness < self.best_fitness: self.best_fitness = fitness self.best_position = self.position.copy() # 定义粒子群算法函数 def particle_swarm_optimization(distance_matrix, num_particles, num_iterations, w, c1, c2): num_cities = len(distance_matrix) particles = [Particle(num_cities) for _ in range(num_particles)] global_best_position = particles

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

瞲_大河弯弯

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值