#生成节点坐标 defcreate_coordinate(port_num, x_range, y_range): x = [] y = [] for i inrange(port_num): x1 = random.randint(0, x_range) y1 = random.randint(0, y_range) x.append(x1) y.append(y1) return x,y
TSP问题中,节点位置是固定的,可以从外部导入。此处没有固定数据,因此使用随机生成的点
3)生成种群基因
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#生成种群基因 defcreat_gene(port_num,size): all_point = [x for x inrange(port_num)] allin = [] for i inrange(size): point_all = all_point[:] d = [] for j inrange(len(point_all)): c = len(point_all) b = random.randint(0,c-1) a = point_all.pop(b) d.append(a) allin.append(d) return allin
#计算适应度 deffitness(gene,x,y): fit = [] for i inrange(len(gene)): one_gene = gene[i] xx = [] yy = [] for j in one_gene: xx.append(x[j]) yy.append(y[j]) distence = 0 for k inrange(len(xx)-1): dis = math.sqrt(pow((xx[k]-xx[k+1]),2)+pow((yy[k]-yy[k+1]),2)) distence += dis distence = round(distence,3) fit.append(distence) return fit
#基因突变(交换两个基因的位置) defmutation(gene,pm): pop = gene[:] px = len(pop) py = len(pop[0]) #py = 10 # 每条染色体随便选一个杂交 for i inrange(px): if (random.random() < pm): mpoint1 = random.randint(0, py - 1) mpoint2 = random.randint(0, py - 1) a = pop[i][mpoint1] b = pop[i][mpoint2] pop[i][mpoint1] = b pop[i][mpoint2] = a return pop
在基因突变环节,同样有节点不重复的要求,因此对染色体随机选出两点,进行点对点交换
tips:如果随机出来的两个点都是正中间,则变异后染色体仍不变
9)迭代过程中每代最优解变化
1 2 3 4 5 6 7
#查看迭代过程中结果变化 defplot_iter_curve(iter, results): X = [i for i inrange(iter)] Y = [results[i] for i inrange(iter)] plt.plot(X, Y) plt.title("各代最优解") plt.show()
import matplotlib.pyplot as plt import math import random import numpy as np import time plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签 plt.rcParams['axes.unicode_minus']=False#用来正常显示负号