1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
| import os import numpy as np import matplotlib.pyplot as plt
coordinates = np.array([[565.0, 575.0], [25.0, 185.0], [345.0, 750.0], [945.0, 685.0], [845.0, 655.0], [880.0, 660.0], [25.0, 230.0], [525.0, 1000.0], [580.0, 1175.0], [650.0, 1130.0], [1605.0, 620.0], [1220.0, 580.0], [1465.0, 200.0], [1530.0, 5.0], [845.0, 680.0], [725.0, 370.0], [145.0, 665.0], [415.0, 635.0], [510.0, 875.0], [560.0, 365.0], [300.0, 465.0], [520.0, 585.0], [480.0, 415.0], [835.0, 625.0], [975.0, 580.0], [1215.0, 245.0], [1320.0, 315.0], [1250.0, 400.0], [660.0, 180.0], [410.0, 250.0], [420.0, 555.0], [575.0, 665.0], [1150.0, 1160.0], [700.0, 580.0], [685.0, 595.0], [685.0, 610.0], [770.0, 610.0], [795.0, 645.0], [720.0, 635.0], [760.0, 650.0], [475.0, 960.0], [95.0, 260.0], [875.0, 920.0], [700.0, 500.0], [555.0, 815.0], [830.0, 485.0], [1170.0, 65.0], [830.0, 610.0], [605.0, 625.0], [595.0, 360.0], [1340.0, 725.0], [1740.0, 245.0]])
def getdistmat(coordinates): ''' 计算52个城市间的欧式距离矩阵 ''' num = coordinates.shape[0] distmat = np.zeros((52, 52)) for i in range(num): for j in range(i, num): distmat[i][j] = distmat[j][i] = np.linalg.norm(coordinates[i] - coordinates[j]) return distmat
numant = 60 numcity = coordinates.shape[0] alpha = 1 beta = 5 rho = 0.1 Q = 1
class ACO: ''' 蚁群算法 ''' def __init__(self, distmat, itermax): ''' distmat: 城市的距离矩阵 itermax: 最大迭代次数 ''' self.itermax = itermax self.etatable = 1.0 / (distmat + np.diag([1e10] * numcity)) self.pheromonetable = np.ones((numcity, numcity)) self.pathtable = np.zeros((numant, numcity)).astype(int) self.lengthaver = np.zeros(self.itermax) self.lengthbest = np.zeros(self.itermax) self.pathbest = np.zeros((self.itermax, numcity))
def showhistory(self): ''' 绘制蚁群算法迭代过程 ''' fig, axes = plt.subplots(nrows=2, ncols=1, figsize=(12, 10)) axes[0].plot(self.lengthaver, 'k', marker='*') axes[0].set_title('Average Length') axes[0].set_xlabel(u'self.iteration') axes[1].plot(self.lengthbest, 'k', marker='<') axes[1].set_title('Best Length') axes[1].set_xlabel(u'self.iteration') plt.show() def savebestpath(self): ''' 保存最优路径 ''' bestpath = self.pathbest[-1] plt.plot(coordinates[:, 0], coordinates[:, 1], 'r.', marker='>') plt.xlim([-100, 2000]) plt.ylim([-100, 1500]) for i in range(numcity - 1): m, n = int(bestpath[i]), int(bestpath[i + 1]) plt.plot([coordinates[m][0],coordinates[n][0]], [coordinates[m][1], coordinates[n][1]], 'k') plt.plot([coordinates[int(bestpath[0])][0],coordinates[int(bestpath[51])][0]], [coordinates[int(bestpath[0])][1],coordinates[int(bestpath[50])][1]] ,'b') ax = plt.gca() ax.set_title("Best Path") ax.set_xlabel('X_axis') ax.set_ylabel('Y_axis') plt.savefig('Best Path.png', dpi=500, bbox_inches='tight') plt.close()
def main(self): ''' 主流程:蚁群迭代过程 ''' self.iter = 0 while self.iter < self.itermax: if numant <= numcity: self.pathtable[:, 0] = np.random.permutation(range(numcity))[:numant] else: self.pathtable[:numcity, 0] = np.random.permutation(range(numcity))[:] self.pathtable[numcity:, 0] = np.random.permutation(range(numcity))[:numant - numcity] length = np.zeros(numant) for i in range(numant): visiting = self.pathtable[i, 0] unvisited = set(range(numcity)) unvisited.remove(visiting) for j in range(1, numcity): listunvisited = list(unvisited) probtrans = np.zeros(len(listunvisited)) for k in range(len(listunvisited)): probtrans[k] = np.power(self.pheromonetable[visiting][listunvisited[k]], alpha) * np.power(self.etatable[visiting][listunvisited[k]], alpha) cumsumprobtrans = (probtrans / sum(probtrans)).cumsum() cumsumprobtrans -= np.random.rand() k = listunvisited[list(cumsumprobtrans > 0).index(True)] self.pathtable[i, j] = k unvisited.remove(k) length[i] += distmat[visiting][k] visiting = k length[i] += distmat[visiting][self.pathtable[i, 0]] self.lengthaver[self.iter] = length.mean() if self.iter == 0: self.lengthbest[self.iter] = length.min() self.pathbest[self.iter] = self.pathtable[length.argmin()].copy() else: if length.min() > self.lengthbest[self.iter - 1]: self.lengthbest[self.iter] = self.lengthbest[self.iter - 1] self.pathbest[self.iter] = self.pathbest[self.iter - 1].copy() else: self.lengthbest[self.iter] = length.min() self.pathbest[self.iter] = self.pathtable[length.argmin()].copy() changepheromonetable = np.zeros((numcity, numcity)) for i in range(numant): for j in range(numcity - 1): changepheromonetable[self.pathtable[i, j]][self.pathtable[i, j + 1]] += Q / distmat[self.pathtable[i, j]][self.pathtable[i, j + 1]] changepheromonetable[self.pathtable[i, j + 1]][self.pathtable[i, 0]] += Q / distmat[self.pathtable[i, j + 1]][self.pathtable[i, 0]] self.pheromonetable = (1 - rho) * self.pheromonetable + changepheromonetable self.iter += 1 self.showhistory() self.savebestpath()
if __name__ == "__main__": distmat = getdistmat(coordinates) aco = ACO(distmat, 100) aco.main()
|