蚁群算法源代码1
蚁群算法代码

//Basic Ant Colony Algorithm for TSP#include <iostream.h>#include <fstream.h>#include <math.h>#include <time.h>#include <conio.h>#include <stdlib.h>#include <iomanip.h>#define N 31 //city size#define M 31 //ant numberdouble inittao=1;double tao[N][N];double detatao[N][N];double distance[N][N];double yita[N][N];int tabu[M][N];int route[M][N];double solution[M];int BestRoute[N];double BestSolution=10000000000;double alfa,beta,rou,Q;int NcMax;void initparameter(void); // initialize the parameters of basic ACAdouble EvalueSolution(int *a); // evaluate the solution of TSP, and calculate the length of path void InCityXY( double x[], double y[], char *infile ); // input the nodes' coordinates of TSPvoid initparameter(void){alfa=1; beta=5; rou=0.9; Q=100;NcMax=200;}void main(void){int NC=0;initparameter();double x[N];double y[N];InCityXY( x, y, "city31.tsp" );for(int i=0;i<N;i++)for(int j=i+1;j<N;j++){distance[j][i]=sqrt((x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j])); distance[i][j]=distance[j][i];}// calculate the heuristic parametersfor(i=0;i<N;i++)for(int j=0;j<N;j++){tao[i][j]=inittao;if(j!=i)yita[i][j]=100/distance[i][j];}for(int k=0;k<M;k++)for(i=0;i<N;i++)route[k][i]=-1;srand(time(NULL));for(k=0;k<M;k++){route[k][0]=k%N;tabu[k][route[k][0]]=1;}//each ant try to find the optiamal pathdo {int s=1;double partsum;double pper;double drand;//ant choose one whole pathwhile(s<N){for(k=0;k<M;k++){int jrand=rand()%3000;drand=jrand/3001.;partsum=0;pper=0;for(int j=0;j<N;j++){if(tabu[k][j]==0)partsum+=pow(tao[route[k][s-1]][j],alfa)*pow(yita[route[k][s-1]][j],beta); }for(j=0;j<N;j++){if(tabu[k][j]==0)pper+=pow(tao[route[k][s-1]][j],alfa)*pow(yita[route[k][s-1]][j],beta)/partsum; if(pper>drand)break;}tabu[k][j]=1;route[k][s]=j;}s++;}// the pheromone is updatedfor(i=0;i<N;i++)for(int j=0;j<N;j++)detatao[i][j]=0;for(k=0;k<M;k++){solution[k]=EvalueSolution(route[k]);if(solution[k]<BestSolution){BestSolution=solution[k];for(s=0;s<N;s++)BestRoute[s]=route[k][s];}}for(k=0;k<M;k++){for(s=0;s<N-1;s++)detatao[route[k][s]][route[k][s+1]]+=Q/solution[k];detatao[route[k][N-1]][route[k][0]]+=Q/solution[k];}for(i=0;i<N;i++)for(int j=0;j<N;j++){tao[i][j]=rou*tao[i][j]+detatao[i][j];if(tao[i][j]<0.00001)tao[i][j]=0.00001;if(tao[i][j]>20)tao[i][j]=20;}for(k=0;k<M;k++)for(int j=1;j<N;j++){tabu[k][route[k][j]]=0;route[k][j]=-1;}NC++;} while(NC<NcMax);//output the calculating resultsfstream result;result.open("optimal_results.log", ios::app);if(!result){cout<<"can't open the <optimal_results.log> file!\n";exit(0);}result<<"*-------------------------------------------------------------------------*"<<endl; result<<"the initialized parameters of ACA are as follows:"<<endl;result<<"alfa="<<alfa<<", beta="<<beta<<", rou="<<rou<<", Q="<<Q<<endl;result<<"the maximum iteration number of ACA is:"<<NcMax<<endl;result<<"the shortest length of the path is:"<<BestSolution<<endl;result<<"the best route is:"<<endl;for(i=0;i<N;i++)result<<BestRoute[i]<<" ";result<<endl;result<<"*-------------------------------------------------------------------------*"<<endl<<endl; result.close();cout<<"the shortest length of the path is:"<<BestSolution<<endl;}double EvalueSolution(int *a){double dist=0;for(int i=0;i<N-1;i++)dist+=distance[a[i]][a[i+1]];dist+=distance[a[i]][a[0]];return dist;}void InCityXY( double x[], double y[], char *infile ){fstream inxyfile( infile, ios::in | ios::nocreate );if( !inxyfile ){cout<<"can't open the <"<<infile<<"> file!\n";exit(0);}int i=0;while( !inxyfile.eof() ){inxyfile>>x[i]>>y[i];if( ++i >= N ) break;}}31个城市坐标:1304 23123639 13154177 22443712 13993488 15353326 15563238 12294196 10044312 7904386 5703007 19702562 17562788 14912381 16761332 6953715 16783918 21794061 23703780 22123676 25784029 28384263 29313429 19083507 23673394 26433439 32012935 32403140 35502545 23572778 28262370 2975运行后可得到15602的巡游路径改正了n个错误。
蚁群算法源代码1

1.#include<iostream>2.#include<math.h>3.#include<time.h>ing namespace std;5.6.//该程序是以蚁群系统为模型写的蚁群算法程序(强调:非蚂蚁周模型),以三个著名的TSP问题为测试对象7.//通过微调参数,都可以获得较好的解8.9./*10.//----------(1)问题一:Oliver 30 城市 TSP 问题 best_length = 423.7406; ------------------------11.//该程序最好的结果是423.741,可运行多次获得12.//城市节点数目13.#define N 3014.//城市坐标15.double C[N][2]={16. {2,99},{4,50},{7,64},{13,40},{18,54},{18,40},{22,60},{24,42},{25,62},{25,38},17. {37,84},{41,94},{41,26},{44,35},{45,21},{54,67},{54,62},{58,35},{58,69},{62,32},18. {64,60},{68,58},{71,44},{71,71},{74,78},{82,7},{83,46},{83,69},{87,76},{91,38}19.};20.//----------上面参数是固定的,下面的参数是可变的-----------21.//蚂蚁数量22.#define M 3023.//最大循环次数NcMax24.int NcMax = 500;25.//信息启发因子,期望启发式因子,全局信息素挥发参数,局部信息素挥发参数, 状态转移公式中的q026.double alpha = 2, beta = 3, rou = 0.1, alpha1 = 0.1, qzero = 0.01;27.//-----------问题一结束------------------------------------------------------------------------28.*/29.30./*31.//----------(2)问题二:Elion50 城市 TSP 问题 best_length = 427.96; ----------------------------32.//该程序最好的结果是428.468,可运行多次获得33.//城市节点数目34.#define N 5035.//城市坐标36.double C[N][2]={37. {5,64}, {5,25}, {5,6}, {7,38}, {8,52}, {10,17},38. {12,42}, {13,13}, {16,57}, {17,33}, {17,63},39. {20,26}, {21,47}, {21,10}, {25,32}, {25,55},40. {27,68}, {27,23}, {30,48}, {30,15}, {31,62},41. {31,32}, {32,22}, {32,39}, {36,16}, {37,69},42. {37,52}, {38,46}, {39,10}, {40,30}, {42,57},43. {42,41}, {43,67}, {45,35}, {46,10}, {48,28},44. {49,49}, {51,21}, {52,33}, {52,41}, {52,64},45. {56,37}, {57,58}, {58,27}, {58,48}, {59,15},46. {61,33}, {62,42}, {62,63}, {63,69}47.};48.//----------上面参数是固定的,下面的参数是可变的-----------49.//蚂蚁数量50.#define M 5051.//最大循环次数NcMax52.int NcMax = 1000;53.//信息启发因子,期望启发式因子,全局信息素挥发参数,局部信息素挥发参数, 状态转移公式中的q054.double alpha = 2, beta = 4, rou = 0.1, alpha1 = 0.1, qzero = 0.01;55.//-----------问题二结束------------------------------------------------------------------------56.*/57.58.//----------(3)问题三:Elion75 城市 TSP 问题 best_length = 542.31;59.//该程序最好的结果是542.309,可运行多次获得60.//城市节点数目61.#define N 7562.//城市坐标63.double C[N][2]={64.{6,25}, {7,43}, {9,56}, {10,70}, {11,28},65.{12,17}, {12,38}, {15,5}, {15,14}, {15,56},66.{16,19}, {17,64}, {20,30}, {21,48}, {21,45},67.{21,36}, {22,53}, {22,22}, {26,29}, {26,13},68.{26,59}, {27,24}, {29,39}, {30,50}, {30,20},69.{30,60}, {31,76}, {33,34}, {33,44}, {35,51},70.{35,16}, {35,60}, {36,6}, {36,26}, {38,33},71.{40,37}, {40,66}, {40,60}, {40,20}, {41,46},72.{43,26}, {44,13}, {45,42}, {45,35}, {47,66},73.{48,21}, {50,30}, {50,40}, {50,50}, {50,70},74.{50,4}, {50,15}, {51,42}, {52,26}, {54,38},75.{54,10}, {55,34}, {55,45}, {55,50}, {55,65},76.{55,57}, {55,20}, {57,72}, {59,5}, {60,15},77.{62,57}, {62,48}, {62,35}, {62,24}, {64,4},78.{65,27}, {66,14}, {66,8}, {67,41}, {70,64}80.//----------上面参数是固定的,下面的参数是可变的-----------81.//蚂蚁数量82.#define M 7583.//最大循环次数NcMax84.int NcMax =1000;85.//信息启发因子,期望启发式因子,全局信息素挥发参数,局部信息素挥发参数, 状态转移公式中的q086.double alpha = 2, beta = 5, rou = 0.1, alpha1 = 0.1, qzero = 0.1;87.//-----------问题三结束------------------------------------------------------------------------88.89.90.//===========================================================================================================91.//局部更新时候使用的的常量,它是由最近邻方法得到的一个长度92.//什么是最近邻方法?:)就是从源节点出发,每次选择一个距离最短的点来遍历所有的节点得到的路径93.//每个节点都可能作为源节点来遍历94.double Lnn;95.//矩阵表示两两城市之间的距离96.double allDistance[N][N];97.98.//计算两个城市之间的距离99.double calculateDistance(int i, int j)100.{101.return sqrt(pow((C[i][0]-C[j][0]),2.0) + pow((C[i][1]-C[j][1]),2.0)); 102.}103.104.//由矩阵表示两两城市之间的距离105.void calculateAllDistance()106.{107.for(int i = 0; i < N; i++)108. {109.for(int j = 0; j < N; j++)110. {111.if (i != j)112. {113. allDistance[i][j] = calculateDistance(i, j);114. allDistance[j][i] = allDistance[i][j];115. }116. }117. }118.}120.//获得经过n个城市的路径长度121.double calculateSumOfDistance(int* tour)122.{123.double sum = 0;124.for(int i = 0; i< N ;i++)125. {126.int row = *(tour + 2 * i);127.int col = *(tour + 2* i + 1);128. sum += allDistance[row][col];129. }130.return sum;131.}132.133.class ACSAnt;134.135.class AntColonySystem136.{137.private:138.double info[N][N], visible[N][N];//节点之间的信息素强度,节点之间的能见度139.public:140. AntColonySystem()141. {142. }143.//计算当前节点到下一节点转移的概率144.double Transition(int i, int j);145.//局部更新规则146.void UpdateLocalPathRule(int i, int j);147.//初始化148.void InitParameter(double value);149.//全局信息素更新150.void UpdateGlobalPathRule(int* bestTour, int globalBestLength); 151.};152.153.//计算当前节点到下一节点转移的概率154.double AntColonySystem::Transition(int i, int j)155.{156.if (i != j)157. {158.return (pow(info[i][j],alpha) * pow(visible[i][j], beta)); 159. }160.else161. {162.return 0.0;163. }164.}165.//局部更新规则166.void AntColonySystem::UpdateLocalPathRule(int i, int j)167.{168. info[i][j] = (1.0 - alpha1) * info[i][j] + alpha1 * (1.0 / (N * Lnn));169. info[j][i] = info[i][j];170.}171.//初始化172.void AntColonySystem::InitParameter(double value)173.{174.//初始化路径上的信息素强度tao0175.for(int i = 0; i < N; i++)176. {177.for(int j = 0; j < N; j++)178. {179. info[i][j] = value;180. info[j][i] = value;181.if (i != j)182. {183. visible[i][j] = 1.0 / allDistance[i][j];184. visible[j][i] = visible[i][j];185. }186. }187. }188.}189.190.//全局信息素更新191.void AntColonySystem::UpdateGlobalPathRule(int* bestTour, int globalBestLen gth)192.{193.for(int i = 0; i < N; i++)194. {195.int row = *(bestTour + 2 * i);196.int col = *(bestTour + 2* i + 1);197. info[row][col] = (1.0 - rou) * info[row][col] + rou * (1.0 / global BestLength);198. info[col][row] =info[row][col];199. }200.}201.202.class ACSAnt203.{204.private:205. AntColonySystem* antColony;206.protected:207.int startCity, cururentCity;//初始城市编号,当前城市编号208.int allowed[N];//禁忌表209.int Tour[N][2];//当前路径210.int currentTourIndex;//当前路径索引,从0开始,存储蚂蚁经过城市的编号211.public:212. ACSAnt(AntColonySystem* acs, int start)213. {214. antColony = acs;215. startCity = start;216. }217.//开始搜索218.int* Search();219.//选择下一节点220.int Choose();221.//移动到下一节点222.void MoveToNextCity(int nextCity);223.224.};225.226.//开始搜索227.int* ACSAnt::Search()228.{229. cururentCity = startCity;230.int toCity;231. currentTourIndex = 0;232.for(int i = 0; i < N; i++)233. {234. allowed[i] = 1;235. }236. allowed[cururentCity] = 0;237.int endCity;238.int count = 0;239.do240. {241. count++;242. endCity = cururentCity;243. toCity = Choose();244.if (toCity >= 0)245. {246. MoveToNextCity(toCity);247. antColony->UpdateLocalPathRule(endCity, toCity);248. cururentCity = toCity;249. }250. }while(toCity >= 0);251. MoveToNextCity(startCity);252. antColony->UpdateLocalPathRule(endCity, startCity);253.254.return *Tour;255.}256.257.//选择下一节点258.int ACSAnt::Choose()259.{260.int nextCity = -1;261.double q = rand()/(double)RAND_MAX;262.//如果 q <= q0,按先验知识,否则则按概率转移,263.if (q <= qzero)264. {265.double probability = -1.0;//转移到下一节点的概率266.for(int i = 0; i < N; i++)267. {268.//去掉禁忌表中已走过的节点,从剩下节点中选择最大概率的可行节点269.if (1 == allowed[i])270. {271.double prob = antColony->Transition(cururentCity, i); 272.if (prob > probability)273. {274. nextCity = i;275. probability = prob;276. }277. }278. }279. }280.else281. {282.//按概率转移283.double p = rand()/(double)RAND_MAX;//生成一个随机数,用来判断落在哪个区间段284.double sum = 0.0;285.double probability = 0.0;//概率的区间点,p 落在哪个区间段,则该点是转移的方向286.//计算概率公式的分母的值287.for(int i = 0; i < N; i++)288. {289.if (1 == allowed[i])291. sum += antColony->Transition(cururentCity, i);292. }293. }294.for(int j = 0; j < N; j++)295. {296.if (1 == allowed[j] && sum > 0)297. {298. probability += antColony->Transition(cururentCity, j)/sum;299.if (probability >= p || (p > 0.9999 && probability > 0.9999 ))300. {301. nextCity = j;302.break;303. }304. }305. }306. }307.return nextCity;308.}309.310.//移动到下一节点311.void ACSAnt::MoveToNextCity(int nextCity)312.{313. allowed[nextCity]=0;314. Tour[currentTourIndex][0] = cururentCity;315. Tour[currentTourIndex][1] = nextCity;316. currentTourIndex++;317. cururentCity = nextCity;318.}319.320.//------------------------------------------321.//选择下一个节点,配合下面的函数来计算的长度322.int ChooseNextNode(int currentNode, int visitedNode[])323.{324.int nextNode = -1;325.double shortDistance = 0.0;326.for(int i = 0; i < N; i++)327. {328.//去掉已走过的节点,从剩下节点中选择距离最近的节点329.if (1 == visitedNode[i])330. {331.if (shortDistance == 0.0)333. shortDistance = allDistance[currentNode][i]; 334. nextNode = i;335. }336.if(shortDistance < allDistance[currentNode][i]) 337. {338. nextNode = i;339. }340. }341. }342.return nextNode;343.}344.345.//给一个节点由最近邻距离方法计算长度346.double CalAdjacentDistance(int node)347.{348.double sum = 0.0;349.int visitedNode[N];350.for(int j = 0; j < N; j++)351. {352. visitedNode[j] = 1;353. }354. visitedNode[node] = 0;355.int currentNode = node;356.int nextNode;357.do358. {359. nextNode = ChooseNextNode(currentNode, visitedNode); 360.if (nextNode >= 0)361. {362. sum += allDistance[currentNode][nextNode]; 363. currentNode= nextNode;364. visitedNode[currentNode] = 0;365. }366. }while(nextNode >= 0);367. sum += allDistance[currentNode][node];368.return sum;369.}370.371.//---------------------------------结束---------------------------------------------372.373.//--------------------------主函数--------------------------------------------------374.int main()375.{376.time_t timer,timerl;377.378. time(&timer);379. unsigned long seed = timer;380. seed %= 56000;381. srand((unsigned int)seed);382.383.//由矩阵表示两两城市之间的距离384. calculateAllDistance();385.//蚁群系统对象386. AntColonySystem* acs = new AntColonySystem();387. ACSAnt* ants[M];388.//蚂蚁均匀分布在城市上389.for(int k = 0; k < M; k++)390. {391. ants[k] = new ACSAnt(acs, (int)(k%N));392. }393. calculateAllDistance();394.//随机选择一个节点计算由最近邻方法得到的一个长度395.int node = rand() % N;396. Lnn = CalAdjacentDistance(node);397.398.//各条路径上初始化的信息素强度399.double initInfo = 1 / (N * Lnn);400. acs->InitParameter(initInfo);401.402.//全局最优路径403.int globalTour[N][2];404.//全局最优长度405.double globalBestLength = 0.0;406.for(int i = 0; i < NcMax; i++)407. {408.//局部最优路径409.int localTour[N][2];410.//局部最优长度411.double localBestLength = 0.0;412.//当前路径长度413.double tourLength;414.for(int j = 0; j < M; j++)415. {416.int* tourPath = ants[j]->Search();417. tourLength = calculateSumOfDistance(tourPath);418.//局部比较,并记录路径和长度419.if(tourLength < localBestLength || abs(localBestLength - 0.0) <0.000001)420. {421.for(int m = 0; m< N; m++)422. {423.int row = *(tourPath + 2 * m);424.int col = *(tourPath + 2* m + 1);425. localTour[m][0] = row;426. localTour[m][1] = col;427. }428. localBestLength = tourLength;429. }430. }431.//全局比较,并记录路径和长度432.if(localBestLength < globalBestLength || abs(globalBestLength - 0.0 ) < 0.000001)433. {434.for(int m = 0; m< N; m++)435. {436. globalTour[m][0] = localTour[m][0];437. globalTour[m][1] = localTour[m][1];438. }439. globalBestLength = localBestLength;440. }441. acs->UpdateGlobalPathRule(*globalTour, globalBestLength);442.//输出所有蚂蚁循环一次后的迭代最优路径443. cout<<"第 "<<i + 1<<" 迭代最优路径:"<<localBestLength<<"."<<endl; 444.for(int m = 0; m< N; m++)445. {446. cout<<localTour[m][0]<<".";447. }448. cout<<endl;449. }450.//输出全局最优路径451. cout<<"全局最优路径长度:"<<globalBestLength<<endl;452. cout<<"全局最优路径:";453.for(int m = 0; m< N; m++)454. {455. cout<<globalTour[m][0]<<".";456. }457. cout<<endl;458. time(&timerl);459.int t = timerl - timer;460.return 0;461.}462.//--------------------------主函数结束--------------------------------------------------。
蚁群算法代码

蚁群算法代码在⽹上看了⼀些蚁群算法原理,其中最为⼴泛的应⽤还是那个旅⾏家问题(TSP)。
诸如粒⼦群优化算法,蚁群算法都可以求⼀个⽬标函数的最⼩值问题的。
下⾯代码记录下跑的代码。
蚁群算法中最为重要的就是⽬标函数和信息素矩阵的设计。
其他的参数则为信息素重要程度,信息素挥发速度,适应度的重要程度。
import numpy as npfrom scipy import spatialimport pandas as pdimport matplotlib.pyplot as plt'''test Ant Aolony Algorithm'''num_points = 25points_coordinate = np.random.rand(num_points, 2) # generate coordinate of pointsdistance_matrix = spatial.distance.cdist(points_coordinate, points_coordinate, metric='euclidean')# routine 中应该为⼀个列表,其中存放的是遍历过程中的位置编号def cal_total_distance(routine):num_points, = routine.shapereturn sum([distance_matrix[routine[i % num_points], routine[(i + 1) % num_points]] for i in range(num_points)])# %% Do ACAfrom sko.ACA import ACA_TSP'''需要设置的参数包含以下部分:(1): ⽬标函数: ⽤于衡量之前⾛过的的路径的⽬标值(累计路程值), 需要有⼀个参数routine, ⽤于记录遍历的路径位置索引(2): 维度数⽬: 此数字将被⽤于程序进⾏构建遍历路径位置索引(3): 蚁群数⽬: size_pop(4): 最⼤迭代次数: 作为⼀项中值条件(5): 距离(⾪属度/信息素)矩阵: 蚁群算法中⼀般称其为信息素矩阵,需要预先进⾏计算,旨在记录两个路径点之间的距离长度[注意]: 距离矩阵在输⼊之前需要进⾏计算缺点: 速度太慢'''aca = ACA_TSP(func=cal_total_distance, n_dim=num_points,size_pop=500, max_iter=200,distance_matrix=distance_matrix)best_x, best_y = aca.run()# %% Plotfig, ax = plt.subplots(1, 2)best_points_ = np.concatenate([best_x, [best_x[0]]])best_points_coordinate = points_coordinate[best_points_, :]ax[0].plot(best_points_coordinate[:, 0], best_points_coordinate[:, 1], 'o-r')pd.DataFrame(aca.y_best_history).cummin().plot(ax=ax[1])plt.show()。
蚁群算法的Python代码及其效果演示(含注释)

蚁群算法的Python代码及其效果演示(含注释)以下为基本蚁群算法的Python代码(含注释)。
随时可以运行:from turtle import*from random import*from json import loadk=load(open("stats.json"))city_num,ant_num=30,30 #规定城市和蚂蚁总数x_data=k[0] #城市的x坐标之集合y_data=k[1] #城市的y坐标之集合best_length=float("inf")best_path=[]alpha=1beta=7rho=0.5potency_list=[1 for xx in range(city_num**2)]Q=1##城市的index从0开始#下面列表存储城市间距离def get_i_index(n):if n%city_num==0:return n//city_num-1else:return n//city_numdef get_j_index(n):if n%city_num==0:return city_num-1else:return n%city_num-1distance_list=[((x_data[get_i_index(z)]-x_data[get_j_index(z)])**2+(y_data[get_i_index(z)]-y_data[get_j_index(z)])**2)**0.5 for z in range(1,city_num**2+1)]class ant(object):def __init__(self,ant_index):self.ant_index=ant_indexself.cities=list(range(city_num))self.current_length=0self.current_city=randint(0,city_num-1)self.initial_city=self.current_cityself.cities.remove(self.current_city)self.path=[self.current_city]self.length=0#根据城市的index求出两城市间距离def get_distance(self,index_1,index_2):return distance_list[index_1*city_num+index_2]def get_potency(self,index_1,index_2):return potency_list[index_1*city_num+index_2]def get_prob_list(self):res=[self.get_potency(self.current_city,x)**alpha*(1/self.get_distance(self.current_city,x))**bet a for x in self.cities]sum_=sum(res)final_res=[y/sum_ for y in res]return final_res##轮盘赌选择城市def __choose_next_city(self):city_list=self.citiesprob_list=self.get_prob_list()tmp=random()sum_=0for city,prob in zip(city_list,prob_list):sum_+=probif sum_>=tmp:self.length+=self.get_distance(self.current_city,city)self.current_city=cityself.path.append(self.current_city)self.cities.remove(self.current_city)returndef running(self):global best_length,best_pathfor x in range(city_num-1):self.__choose_next_city()self.length+=self.get_distance(self.current_city,self.initial_city)self.path.append(self.initial_city)if self.length<best_length:best_length=self.lengthbest_path=self.pathreturn (self.path,self.length)def go():operation=[]for x in potency_list:x*=(1-rho)for x in range(ant_num):operation.append(ant(x).running())for x in operation:for y in range(city_num-1):potency_list[x[0][y]*city_num+x[0][y+1]]+=Q/x[1]#print(f"potency_list:{potency_list}")#print(f"best_path:{best_path}")#print(f"best_length:{best_length}")for yy in range(1000):go()print(f"best_length:{best_length}")pu()setpos(x_data[best_path[0]],y_data[best_path[0]])pd()for x in range(1,city_num+1):setpos(x_data[best_path[x]],y_data[best_path[x]]) 运行效果:。
蚁群算法matlab代码讲解

蚁群算法matlab代码讲解蚁群算法(Ant Colony Algorithm)是模拟蚁群觅食行为而提出的一种优化算法。
它以蚁群觅食的方式来解决优化问题,比如旅行商问题、图着色问题等。
该算法模拟了蚂蚁在寻找食物时的行为,通过信息素的正反馈和启发式搜索来实现问题的最优解。
在蚁群算法中,首先需要初始化一组蚂蚁和问题的解空间。
每只蚂蚁沿着路径移动,通过信息素和启发式规则来选择下一步的移动方向。
当蚂蚁到达目标位置后,会根据路径的长度来更新信息素。
下面是一个用MATLAB实现蚁群算法的示例代码:```matlab% 参数设置num_ants = 50; % 蚂蚁数量num_iterations = 100; % 迭代次数alpha = 1; % 信息素重要程度因子beta = 5; % 启发式因子rho = 0.1; % 信息素蒸发率Q = 1; % 信息素增加强度因子pheromone = ones(num_cities, num_cities); % 初始化信息素矩阵% 初始化蚂蚁位置和路径ants = zeros(num_ants, num_cities);for i = 1:num_antsants(i, 1) = randi([1, num_cities]);end% 迭代计算for iter = 1:num_iterations% 更新每只蚂蚁的路径for i = 1:num_antsfor j = 2:num_cities% 根据信息素和启发式规则选择下一步移动方向next_city = choose_next_city(pheromone, ants(i, j-1), beta);ants(i, j) = next_city;endend% 计算每只蚂蚁的路径长度path_lengths = zeros(num_ants, 1);for i = 1:num_antspath_lengths(i) = calculate_path_length(ants(i, :), distances);end% 更新信息素矩阵pheromone = (1 - rho) * pheromone;for i = 1:num_antsfor j = 2:num_citiespheromone(ants(i, j-1), ants(i, j)) = pheromone(ants(i, j-1), ants(i, j)) + Q / path_lengths(i); endendend```上述代码中的参数可以根据具体问题进行调整。
蚁群算法python编程实现

蚁群算法python编程实现蚁群算法(Ant Colony Optimization,ACO)是一种群体智能算法,在解决问题时模拟蚂蚁寻找食物的过程,通过蚂蚁在路径上释放信息素的方式引导其他蚂蚁进行探索。
下面是使用Python实现蚁群算法的代码:首先需要导入相关的库:```import numpy as npnp.random.seed(42)```定义一个城市距离矩阵,表示任意两个城市之间的距离:```distance_matrix = np.array([[0, 1, 2, 3, 4],[1, 0, 5, 6, 7],[2, 5, 0, 8, 9],[3, 6, 8, 0, 10],[4, 7, 9, 10, 0]])```定义一个蚂蚁的类,用于描述蚂蚁的位置、经过的城市、路径长度等信息:```class Ant:def __init__(self, num_cities):self.num_cities = num_citiesself.position = np.random.randint(num_cities)self.visited = {self.position}self.path_length = 0def choose_next_city(self, pheromone_matrix, alpha, beta): pheromone_powered =np.power(pheromone_matrix[self.position, :], alpha)distance_powered =np.power(1/distance_matrix[self.position, :], beta)probabilities = (pheromone_powered * distance_powered) probabilities[list(self.visited)] = 0probabilities /= np.sum(probabilities)next_city = np.random.choice(self.num_cities,p=probabilities)self.visited.add(next_city)self.path_length += distance_matrix[self.position,next_city]self.position = next_city```定义一个蚂蚁群体的类,用于描述所有蚂蚁的行为,包括释放信息素、更新信息素等:```class AntColony:def __init__(self, num_ants, num_cities, alpha=1, beta=2, rho=0.5, q0=0.5):self.num_ants = num_antsself.num_cities = num_citiesself.alpha = alphaself.beta = betaself.rho = rhoself.q0 = q0self.pheromone_matrix = np.ones((num_cities,num_cities))def run(self, iterations):best_path_length = np.infbest_path = []for i in range(iterations):ants = [Ant(self.num_cities) for _ inrange(self.num_ants)]for ant in ants:while len(ant.visited) < self.num_cities:ant.choose_next_city(self.pheromone_matrix, self.alpha, self.beta)ant.path_length +=distance_matrix[ant.position, ants[0].position]if ant.path_length < best_path_length:best_path_length = ant.path_lengthbest_path = list(ant.visited)delta_pheromone_matrix =np.zeros((self.num_cities, self.num_cities))for ant in ants:for i in range(self.num_cities):j = list(ant.visited).index(i)if j < self.num_cities - 1:delta_pheromone_matrix[i,list(ant.visited)[j+1]] += 1 / ant.path_lengthelse:delta_pheromone_matrix[i,ants[0].position] += 1 / ant.path_lengthself.pheromone_matrix *= (1 - self.rho)self.pheromone_matrix += delta_pheromone_matrix return best_path_length, best_path```最后,我们可以使用AntColony类来解决一个具体的问题,如下所示:```colony = AntColony(num_ants=10, num_cities=5)colony.run(iterations=1000)```该代码会输出最优路径的长度和经过的城市编号,例如:```(18, [0, 2, 3, 1, 4])```其中,路径的长度为18,依次经过的城市编号为0、2、3、1、4。
蚁群算法 最短路径python

蚁群算法最短路径python蚁群算法是一种模拟蚂蚁寻找食物的算法,可以用于求解最短路径问题。
下面是一个用Python实现的最短路径蚁群算法的示例程序:```pythonimport numpy as np# 定义城市距离矩阵distances = np.array([[0, 2, 3, 5],[2, 0, 4, 7],[3, 4, 0, 4],[5, 7, 4, 0]])# 初始化参数num_cities = 4 # 城市数量num_ants = 5 # 蚂蚁数量pheromone = 0.1 * np.ones((num_cities, num_cities)) # 信息素矩阵alpha = 1 # 信息素重要程度因子beta = 2 # 启发式因子Q = 1 # 常数因子decay = 0.1 # 信息素挥发因子max_iterations = 20 # 最大迭代次数# 主循环for i in range(max_iterations):# 初始化每只蚂蚁的位置和路径长度positions = np.zeros(num_ants, dtype=int)lengths = np.zeros(num_ants)for j in range(num_ants):positions[j] = np.random.randint(num_cities)# 逐个城市路径选择for k in range(num_cities - 1):for j in range(num_ants):# 计算每个城市的行走概率mask = np.ones(num_cities, dtype=bool)mask[positions[j]] = Falsepheromone_temp = np.power(pheromone[positions[j], mask], alpha) * \np.power(1.0 /distances[positions[j], mask], beta)prob = pheromone_temp / np.sum(pheromone_temp)# 轮盘赌选择下一个城市next_city = np.random.choice(num_cities - 1,p=prob) + \(1 if np.sum(mask[:positions[j]]) < positions[j] else 0)positions[j] = next_citylengths[j] += distances[positions[j-1],positions[j]]# 更新信息素delta_pheromone = np.zeros((num_cities, num_cities))for j in range(num_ants):for k in range(num_cities - 1):delta_pheromone[positions[j], positions[j+1]] += Q / lengths[j]pheromone = (1 - decay) * pheromone + delta_pheromone# 输出最短路径best_path_length = np.min(lengths)best_path = positions[np.argmin(lengths)]print(f"Iteration {i}: best path length{best_path_length}, best path {best_path}")```上述程序定义了一个$4\times 4$的城市距离矩阵(即城市之间的直线距离),包含4个城市。
蚁群算法代码

#define MAXX 80
#define MAXY 23
#define MAX_FOOD 10000
#define TARGET_FOOD 200
#define MAX_SMELL 5000
#define SMELL_DROP_RATE 0.05
小小的蚂蚁总是能够找到食物,他们具有什么样的智能呢?设想,如果我们要为蚂蚁设计一个人工智能的程序,那么这个程序要多么复杂呢?首先,你要让蚂蚁能够避开障碍物,就必须根据适当的地形给它编进指令让他们能够巧妙的避开障碍物,其次,要让蚂蚁找到食物,就需要让他们遍历空间上的所有点;再次,如果要让蚂蚁找到最短的路径,那么需要计算所有可能的路径并且比较它们的大小,而且更重要的是,你要小心翼翼的编程,因为程序的错误也许会让你前功尽弃。这是多么不可思议的程序!太复杂了,恐怕没人能够完成这样繁琐冗余的程序。
为什么这么简单的程序会让蚂蚁干这样复杂的事情?答案是:简单规则的涌现。事实上,每只蚂蚁并不是像我们想象的需要知道整个世界的信息,他们其实只关心很小范围内的眼前信息,而且根据这些局部信息利用几条简单的规则进行决策,这样,在蚁群这个集体里,复杂性的行为就会凸现出来。这就是人工生命、复杂性科学解释的规律!
timeuse+=100;
oldsec = t.ti_sec;
}
timeuse+=t.ti_hund-oldhund;
oldhund = t.ti_hund;
if(tu>=60&&!CanFindFood)
{
gotoxy(1,MAXY+1);
printf(“Can not find food, maybe a block world.”);
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
1.#include<iostream>2.#include<math.h>3.#include<time.h>ing namespace std;5.6.//该程序是以蚁群系统为模型写的蚁群算法程序(强调:非蚂蚁周模型),以三个著名的TSP问题为测试对象7.//通过微调参数,都可以获得较好的解8.9./*10.//----------(1)问题一:Oliver 30 城市 TSP 问题 best_length = 423.7406; ------------------------11.//该程序最好的结果是423.741,可运行多次获得12.//城市节点数目13.#define N 3014.//城市坐标15.double C[N][2]={16. {2,99},{4,50},{7,64},{13,40},{18,54},{18,40},{22,60},{24,42},{25,62},{25,38},17. {37,84},{41,94},{41,26},{44,35},{45,21},{54,67},{54,62},{58,35},{58,69},{62,32},18. {64,60},{68,58},{71,44},{71,71},{74,78},{82,7},{83,46},{83,69},{87,76},{91,38}19.};20.//----------上面参数是固定的,下面的参数是可变的-----------21.//蚂蚁数量22.#define M 3023.//最大循环次数NcMax24.int NcMax = 500;25.//信息启发因子,期望启发式因子,全局信息素挥发参数,局部信息素挥发参数, 状态转移公式中的q026.double alpha = 2, beta = 3, rou = 0.1, alpha1 = 0.1, qzero = 0.01;27.//-----------问题一结束------------------------------------------------------------------------28.*/29.30./*31.//----------(2)问题二:Elion50 城市 TSP 问题 best_length = 427.96; ----------------------------32.//该程序最好的结果是428.468,可运行多次获得33.//城市节点数目34.#define N 5035.//城市坐标36.double C[N][2]={37. {5,64}, {5,25}, {5,6}, {7,38}, {8,52}, {10,17},38. {12,42}, {13,13}, {16,57}, {17,33}, {17,63},39. {20,26}, {21,47}, {21,10}, {25,32}, {25,55},40. {27,68}, {27,23}, {30,48}, {30,15}, {31,62},41. {31,32}, {32,22}, {32,39}, {36,16}, {37,69},42. {37,52}, {38,46}, {39,10}, {40,30}, {42,57},43. {42,41}, {43,67}, {45,35}, {46,10}, {48,28},44. {49,49}, {51,21}, {52,33}, {52,41}, {52,64},45. {56,37}, {57,58}, {58,27}, {58,48}, {59,15},46. {61,33}, {62,42}, {62,63}, {63,69}47.};48.//----------上面参数是固定的,下面的参数是可变的-----------49.//蚂蚁数量50.#define M 5051.//最大循环次数NcMax52.int NcMax = 1000;53.//信息启发因子,期望启发式因子,全局信息素挥发参数,局部信息素挥发参数, 状态转移公式中的q054.double alpha = 2, beta = 4, rou = 0.1, alpha1 = 0.1, qzero = 0.01;55.//-----------问题二结束------------------------------------------------------------------------56.*/57.58.//----------(3)问题三:Elion75 城市 TSP 问题 best_length = 542.31;59.//该程序最好的结果是542.309,可运行多次获得60.//城市节点数目61.#define N 7562.//城市坐标63.double C[N][2]={64.{6,25}, {7,43}, {9,56}, {10,70}, {11,28},65.{12,17}, {12,38}, {15,5}, {15,14}, {15,56},66.{16,19}, {17,64}, {20,30}, {21,48}, {21,45},67.{21,36}, {22,53}, {22,22}, {26,29}, {26,13},68.{26,59}, {27,24}, {29,39}, {30,50}, {30,20},69.{30,60}, {31,76}, {33,34}, {33,44}, {35,51},70.{35,16}, {35,60}, {36,6}, {36,26}, {38,33},71.{40,37}, {40,66}, {40,60}, {40,20}, {41,46},72.{43,26}, {44,13}, {45,42}, {45,35}, {47,66},73.{48,21}, {50,30}, {50,40}, {50,50}, {50,70},74.{50,4}, {50,15}, {51,42}, {52,26}, {54,38},75.{54,10}, {55,34}, {55,45}, {55,50}, {55,65},76.{55,57}, {55,20}, {57,72}, {59,5}, {60,15},77.{62,57}, {62,48}, {62,35}, {62,24}, {64,4},78.{65,27}, {66,14}, {66,8}, {67,41}, {70,64}80.//----------上面参数是固定的,下面的参数是可变的-----------81.//蚂蚁数量82.#define M 7583.//最大循环次数NcMax84.int NcMax =1000;85.//信息启发因子,期望启发式因子,全局信息素挥发参数,局部信息素挥发参数, 状态转移公式中的q086.double alpha = 2, beta = 5, rou = 0.1, alpha1 = 0.1, qzero = 0.1;87.//-----------问题三结束------------------------------------------------------------------------88.89.90.//===========================================================================================================91.//局部更新时候使用的的常量,它是由最近邻方法得到的一个长度92.//什么是最近邻方法?:)就是从源节点出发,每次选择一个距离最短的点来遍历所有的节点得到的路径93.//每个节点都可能作为源节点来遍历94.double Lnn;95.//矩阵表示两两城市之间的距离96.double allDistance[N][N];97.98.//计算两个城市之间的距离99.double calculateDistance(int i, int j)100.{101.return sqrt(pow((C[i][0]-C[j][0]),2.0) + pow((C[i][1]-C[j][1]),2.0)); 102.}103.104.//由矩阵表示两两城市之间的距离105.void calculateAllDistance()106.{107.for(int i = 0; i < N; i++)108. {109.for(int j = 0; j < N; j++)110. {111.if (i != j)112. {113. allDistance[i][j] = calculateDistance(i, j);114. allDistance[j][i] = allDistance[i][j];115. }116. }117. }118.}120.//获得经过n个城市的路径长度121.double calculateSumOfDistance(int* tour)122.{123.double sum = 0;124.for(int i = 0; i< N ;i++)125. {126.int row = *(tour + 2 * i);127.int col = *(tour + 2* i + 1);128. sum += allDistance[row][col];129. }130.return sum;131.}132.133.class ACSAnt;134.135.class AntColonySystem136.{137.private:138.double info[N][N], visible[N][N];//节点之间的信息素强度,节点之间的能见度139.public:140. AntColonySystem()141. {142. }143.//计算当前节点到下一节点转移的概率144.double Transition(int i, int j);145.//局部更新规则146.void UpdateLocalPathRule(int i, int j);147.//初始化148.void InitParameter(double value);149.//全局信息素更新150.void UpdateGlobalPathRule(int* bestTour, int globalBestLength); 151.};152.153.//计算当前节点到下一节点转移的概率154.double AntColonySystem::Transition(int i, int j)155.{156.if (i != j)157. {158.return (pow(info[i][j],alpha) * pow(visible[i][j], beta)); 159. }160.else161. {162.return 0.0;163. }164.}165.//局部更新规则166.void AntColonySystem::UpdateLocalPathRule(int i, int j)167.{168. info[i][j] = (1.0 - alpha1) * info[i][j] + alpha1 * (1.0 / (N * Lnn));169. info[j][i] = info[i][j];170.}171.//初始化172.void AntColonySystem::InitParameter(double value)173.{174.//初始化路径上的信息素强度tao0175.for(int i = 0; i < N; i++)176. {177.for(int j = 0; j < N; j++)178. {179. info[i][j] = value;180. info[j][i] = value;181.if (i != j)182. {183. visible[i][j] = 1.0 / allDistance[i][j];184. visible[j][i] = visible[i][j];185. }186. }187. }188.}189.190.//全局信息素更新191.void AntColonySystem::UpdateGlobalPathRule(int* bestTour, int globalBestLen gth)192.{193.for(int i = 0; i < N; i++)194. {195.int row = *(bestTour + 2 * i);196.int col = *(bestTour + 2* i + 1);197. info[row][col] = (1.0 - rou) * info[row][col] + rou * (1.0 / global BestLength);198. info[col][row] =info[row][col];199. }200.}201.202.class ACSAnt203.{204.private:205. AntColonySystem* antColony;206.protected:207.int startCity, cururentCity;//初始城市编号,当前城市编号208.int allowed[N];//禁忌表209.int Tour[N][2];//当前路径210.int currentTourIndex;//当前路径索引,从0开始,存储蚂蚁经过城市的编号211.public:212. ACSAnt(AntColonySystem* acs, int start)213. {214. antColony = acs;215. startCity = start;216. }217.//开始搜索218.int* Search();219.//选择下一节点220.int Choose();221.//移动到下一节点222.void MoveToNextCity(int nextCity);223.224.};225.226.//开始搜索227.int* ACSAnt::Search()228.{229. cururentCity = startCity;230.int toCity;231. currentTourIndex = 0;232.for(int i = 0; i < N; i++)233. {234. allowed[i] = 1;235. }236. allowed[cururentCity] = 0;237.int endCity;238.int count = 0;239.do240. {241. count++;242. endCity = cururentCity;243. toCity = Choose();244.if (toCity >= 0)245. {246. MoveToNextCity(toCity);247. antColony->UpdateLocalPathRule(endCity, toCity);248. cururentCity = toCity;249. }250. }while(toCity >= 0);251. MoveToNextCity(startCity);252. antColony->UpdateLocalPathRule(endCity, startCity);253.254.return *Tour;255.}256.257.//选择下一节点258.int ACSAnt::Choose()259.{260.int nextCity = -1;261.double q = rand()/(double)RAND_MAX;262.//如果 q <= q0,按先验知识,否则则按概率转移,263.if (q <= qzero)264. {265.double probability = -1.0;//转移到下一节点的概率266.for(int i = 0; i < N; i++)267. {268.//去掉禁忌表中已走过的节点,从剩下节点中选择最大概率的可行节点269.if (1 == allowed[i])270. {271.double prob = antColony->Transition(cururentCity, i); 272.if (prob > probability)273. {274. nextCity = i;275. probability = prob;276. }277. }278. }279. }280.else281. {282.//按概率转移283.double p = rand()/(double)RAND_MAX;//生成一个随机数,用来判断落在哪个区间段284.double sum = 0.0;285.double probability = 0.0;//概率的区间点,p 落在哪个区间段,则该点是转移的方向286.//计算概率公式的分母的值287.for(int i = 0; i < N; i++)288. {289.if (1 == allowed[i])291. sum += antColony->Transition(cururentCity, i);292. }293. }294.for(int j = 0; j < N; j++)295. {296.if (1 == allowed[j] && sum > 0)297. {298. probability += antColony->Transition(cururentCity, j)/sum;299.if (probability >= p || (p > 0.9999 && probability > 0.9999 ))300. {301. nextCity = j;302.break;303. }304. }305. }306. }307.return nextCity;308.}309.310.//移动到下一节点311.void ACSAnt::MoveToNextCity(int nextCity)312.{313. allowed[nextCity]=0;314. Tour[currentTourIndex][0] = cururentCity;315. Tour[currentTourIndex][1] = nextCity;316. currentTourIndex++;317. cururentCity = nextCity;318.}319.320.//------------------------------------------321.//选择下一个节点,配合下面的函数来计算的长度322.int ChooseNextNode(int currentNode, int visitedNode[])323.{324.int nextNode = -1;325.double shortDistance = 0.0;326.for(int i = 0; i < N; i++)327. {328.//去掉已走过的节点,从剩下节点中选择距离最近的节点329.if (1 == visitedNode[i])330. {331.if (shortDistance == 0.0)333. shortDistance = allDistance[currentNode][i]; 334. nextNode = i;335. }336.if(shortDistance < allDistance[currentNode][i]) 337. {338. nextNode = i;339. }340. }341. }342.return nextNode;343.}344.345.//给一个节点由最近邻距离方法计算长度346.double CalAdjacentDistance(int node)347.{348.double sum = 0.0;349.int visitedNode[N];350.for(int j = 0; j < N; j++)351. {352. visitedNode[j] = 1;353. }354. visitedNode[node] = 0;355.int currentNode = node;356.int nextNode;357.do358. {359. nextNode = ChooseNextNode(currentNode, visitedNode); 360.if (nextNode >= 0)361. {362. sum += allDistance[currentNode][nextNode]; 363. currentNode= nextNode;364. visitedNode[currentNode] = 0;365. }366. }while(nextNode >= 0);367. sum += allDistance[currentNode][node];368.return sum;369.}370.371.//---------------------------------结束---------------------------------------------372.373.//--------------------------主函数--------------------------------------------------374.int main()375.{376.time_t timer,timerl;377.378. time(&timer);379. unsigned long seed = timer;380. seed %= 56000;381. srand((unsigned int)seed);382.383.//由矩阵表示两两城市之间的距离384. calculateAllDistance();385.//蚁群系统对象386. AntColonySystem* acs = new AntColonySystem();387. ACSAnt* ants[M];388.//蚂蚁均匀分布在城市上389.for(int k = 0; k < M; k++)390. {391. ants[k] = new ACSAnt(acs, (int)(k%N));392. }393. calculateAllDistance();394.//随机选择一个节点计算由最近邻方法得到的一个长度395.int node = rand() % N;396. Lnn = CalAdjacentDistance(node);397.398.//各条路径上初始化的信息素强度399.double initInfo = 1 / (N * Lnn);400. acs->InitParameter(initInfo);401.402.//全局最优路径403.int globalTour[N][2];404.//全局最优长度405.double globalBestLength = 0.0;406.for(int i = 0; i < NcMax; i++)407. {408.//局部最优路径409.int localTour[N][2];410.//局部最优长度411.double localBestLength = 0.0;412.//当前路径长度413.double tourLength;414.for(int j = 0; j < M; j++)415. {416.int* tourPath = ants[j]->Search();417. tourLength = calculateSumOfDistance(tourPath);418.//局部比较,并记录路径和长度419.if(tourLength < localBestLength || abs(localBestLength - 0.0) <0.000001)420. {421.for(int m = 0; m< N; m++)422. {423.int row = *(tourPath + 2 * m);424.int col = *(tourPath + 2* m + 1);425. localTour[m][0] = row;426. localTour[m][1] = col;427. }428. localBestLength = tourLength;429. }430. }431.//全局比较,并记录路径和长度432.if(localBestLength < globalBestLength || abs(globalBestLength - 0.0 ) < 0.000001)433. {434.for(int m = 0; m< N; m++)435. {436. globalTour[m][0] = localTour[m][0];437. globalTour[m][1] = localTour[m][1];438. }439. globalBestLength = localBestLength;440. }441. acs->UpdateGlobalPathRule(*globalTour, globalBestLength);442.//输出所有蚂蚁循环一次后的迭代最优路径443. cout<<"第 "<<i + 1<<" 迭代最优路径:"<<localBestLength<<"."<<endl; 444.for(int m = 0; m< N; m++)445. {446. cout<<localTour[m][0]<<".";447. }448. cout<<endl;449. }450.//输出全局最优路径451. cout<<"全局最优路径长度:"<<globalBestLength<<endl;452. cout<<"全局最优路径:";453.for(int m = 0; m< N; m++)454. {455. cout<<globalTour[m][0]<<".";456. }457. cout<<endl;458. time(&timerl);459.int t = timerl - timer;460.return 0;461.}462.//--------------------------主函数结束--------------------------------------------------。