蚁群算法代码
蚁群算法代码

//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.//--------------------------主函数结束--------------------------------------------------。
c++蚁群算法最短路径代码

temp=pow((1.0/Map.distance[curCity][i]),beta)*pow((Map.m_dTrial[curCity][i]),alpha);
j=i;
}
}
}
return j;
}
ant::ant()
double sel=0;
for (i=0;i<iCityCount;i++)
{
if(Map.distance[curCity][i]&&(AllowedCity[i]==1))
{
prob[i]=pow((1.0/Map.distance[curCity][i]),beta)*pow((Map.m_dTrial[curCity][i]),alpha)/temp;
int i;
for(i=0;tabu[i]!=iCityCount-1;i++)
m_dLength+=Map.distance[tabu[i]][tabu[i+1]];
}
int ant::move()
{
//the ant move to next town and add town ID to tabu.
{
for (j=0;ants[i].tabu[j]!=iCityCount-1&&rValue[j]!=-1;j++)
{
Map.m_dDeltTrial[ants[i].tabu[j]][ants[i].tabu[j+1]]+=Q/ants[i].m_dLength ;
Map.m_dDeltTrial[ants[i].tabu[j+1]][ants[i].tabu[j]]+=Q/ants[i].m_dLength;
蚁群算法代码

蚁群算法代码在⽹上看了⼀些蚁群算法原理,其中最为⼴泛的应⽤还是那个旅⾏家问题(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()。
蚁群算法路径优化matlab代码

蚁群算法路径优化matlab代码标题:蚁群算法路径优化 MATLAB 代码正文:蚁群算法是一种基于模拟蚂蚁搜索食物路径的优化算法,常用于求解复杂问题。
在路径优化问题中,蚂蚁需要从起点移动到终点,通过探索周围区域来寻找最短路径。
MATLAB 是一个常用的数值计算软件,可以用来实现蚁群算法的路径优化。
下面是一个基本的 MATLAB 代码示例,用于实现蚁群算法的路径优化:```matlab% 定义参数num_ants = 100; % 蚂蚁数量num_steps = 100; % 路径优化步数search_radius = 2; % 搜索半径max_iterations = 1000; % 最大迭代次数% 随机生成起点和终点的位置坐标start_pos = [randi(100), randi(100)];end_pos = [75, 75];% 初始化蚂蚁群体的位置和方向ants_pos = zeros(num_ants, 2);ants_dir = zeros(num_ants, 2);for i = 1:num_antsants_pos(i, :) = start_pos + randn(2) * search_radius; ants_dir(i, :) = randomvec(2);end% 初始化蚂蚁群体的速度ants_vel = zeros(num_ants, 2);for i = 1:num_antsants_vel(i, :) = -0.1 * ants_pos(i, :) + 0.5 *ants_dir(i, :);end% 初始时蚂蚁群体向终点移动for i = 1:num_antsans_pos = end_pos;ans_vel = ants_vel;for j = 1:num_steps% 更新位置和速度ans_pos(i) = ans_pos(i) + ans_vel(i);ants_vel(i, :) = ones(1, num_steps) * (-0.1 * ans_pos(i) + 0.5 * ans_dir(i, :));end% 更新方向ants_dir(i, :) = ans_dir(i, :) - ans_vel(i) * 3;end% 迭代优化路径max_iter = 0;for i = 1:max_iterations% 计算当前路径的最短距离dist = zeros(num_ants, 1);for j = 1:num_antsdist(j) = norm(ants_pos(j) - end_pos);end% 更新蚂蚁群体的位置和方向for j = 1:num_antsants_pos(j, :) = ants_pos(j, :) - 0.05 * dist(j) * ants_dir(j, :);ants_dir(j, :) = -ants_dir(j, :);end% 更新蚂蚁群体的速度for j = 1:num_antsants_vel(j, :) = ants_vel(j, :) - 0.001 * dist(j) * ants_dir(j, :);end% 检查是否达到最大迭代次数if i > max_iterationsbreak;endend% 输出最优路径[ans_pos, ans_vel] = ants_pos;path_dist = norm(ans_pos - end_pos);disp(["最优路径长度为:" num2str(path_dist)]);```拓展:上述代码仅仅是一个简单的示例,实际上要实现蚁群算法的路径优化,需要更加复杂的代码实现。
蚁群算法matlab程序代码

先新建一个主程序M文件ACATSP.m 代码如下:function [R_best,L_best,L_ave,Shortest_Route,Shortest_Length]=ACATSP(C,NC_max,m,Alpha,Beta,Rho,Q)%%================================================================ =========%% 主要符号说明%% C n个城市的坐标,n×2的矩阵%% NC_max 蚁群算法MATLAB程序最大迭代次数%% m 蚂蚁个数%% Alpha 表征信息素重要程度的参数%% Beta 表征启发式因子重要程度的参数%% Rho 信息素蒸发系数%% Q 表示蚁群算法MATLAB程序信息素增加强度系数%% R_best 各代最佳路线%% L_best 各代最佳路线的长度%%================================================================ =========%% 蚁群算法MATLAB程序第一步:变量初始化n=size(C,1);%n表示问题的规模(城市个数)D=zeros(n,n);%D表示完全图的赋权邻接矩阵for i=1:nfor j=1:nif i~=jD(i,j)=((C(i,1)-C(j,1))^2+(C(i,2)-C(j,2))^2)^0.5;D(i,j)=eps; % i = j 时不计算,应该为0,但后面的启发因子要取倒数,用eps(浮点相对精度)表示endD(j,i)=D(i,j); %对称矩阵endendEta=1./D; %Eta为启发因子,这里设为距离的倒数Tau=ones(n,n); %Tau为信息素矩阵Tabu=zeros(m,n); %存储并记录路径的生成NC=1; %迭代计数器,记录迭代次数R_best=zeros(NC_max,n); %各代最佳路线L_best=inf.*ones(NC_max,1); %各代最佳路线的长度L_ave=zeros(NC_max,1); %各代路线的平均长度while NC<=NC_max %停止条件之一:达到最大迭代次数,停止%% 蚁群算法MATLAB程序第二步:将m只蚂蚁放到n个城市上Randpos=[]; %随即存取for i=1:(ceil(m/n))Randpos=[Randpos,randperm(n)];endTabu(:,1)=(Randpos(1,1:m))'; %此句不太理解?%% 蚁群算法MATLAB程序第三步:m只蚂蚁按概率函数选择下一座城市,完成各自的周游for j=2:n %所在城市不计算for i=1:mvisited=Tabu(i,1:(j-1)); %记录已访问的城市,避免重复访问J=zeros(1,(n-j+1)); %待访问的城市P=J; %待访问城市的选择概率分布for k=1:nif length(find(visited==k))==0 %开始时置0J(Jc)=k;Jc=Jc+1; %访问的城市个数自加1endend%% 下面计算蚁群算法MATLAB程序待选城市的概率分布for k=1:length(J)P(k)=(Tau(visited(end),J(k))^Alpha)*(Eta(visited(end),J(k))^Beta);endP=P/(sum(P));%% 按概率原则选取下一个城市Pcum=cumsum(P); %cumsum,元素累加即求和Select=find(Pcum>=rand); %若计算的概率大于原来的就选择这条路线to_visit=J(Select(1));Tabu(i,j)=to_visit;endendif NC>=2Tabu(1,:)=R_best(NC-1,:);end%% 蚁群算法MATLAB程序第四步:记录本次迭代最佳路线L=zeros(m,1); %开始距离为0,m*1的列向量for i=1:mR=Tabu(i,:);for j=1:(n-1)L(i)=L(i)+D(R(j),R(j+1)); %原距离加上第j个城市到第j+1个城市的距离L(i)=L(i)+D(R(1),R(n)); %一轮下来后走过的距离endL_best(NC)=min(L); %最佳距离取最小pos=find(L==L_best(NC));R_best(NC,:)=Tabu(pos(1),:); %此轮迭代后的最佳路线L_ave(NC)=mean(L); %此轮迭代后的平均距离NC=NC+1 %迭代继续%% 蚁群算法MATLAB程序第五步:更新信息素Delta_Tau=zeros(n,n); %开始时信息素为n*n的0矩阵for i=1:mfor j=1:(n-1)Delta_Tau(Tabu(i,j),Tabu(i,j+1))=Delta_Tau(Tabu(i,j),Tabu(i,j+1))+Q/L(i);%此次循环在路径(i,j)上的信息素增量endDelta_Tau(Tabu(i,n),Tabu(i,1))=Delta_Tau(Tabu(i,n),Tabu(i,1))+Q/L(i);%此次循环在整个路径上的信息素增量endTau=(1-Rho).*Tau+Delta_Tau; %考虑信息素挥发,更新后的信息素%% 蚁群算法MATLAB程序第六步:禁忌表清零Tabu=zeros(m,n); %%直到最大迭代次数end%% 蚁群算法MATLAB程序第七步:输出结果Pos=find(L_best==min(L_best)); %找到最佳路径(非0为真)Shortest_Route=R_best(Pos(1),:) %最大迭代次数后最佳路径Shortest_Length=L_best(Pos(1)) %最大迭代次数后最短距离subplot(1,2,1) %绘制第一个子图形DrawRoute(C,Shortest_Route) %画路线图的子函数subplot(1,2,2) %绘制第二个子图形plot(L_best)hold on %保持图形plot(L_ave,'r')title('平均距离和最短距离') %标题建立一个子程序DrawRoute.m代码如下:function DrawRoute(C,R)%%================================================================ =========%% DrawRoute.m%% 画路线图的子函数%%-------------------------------------------------------------------------%% C Coordinate 节点坐标,由一个N×2的矩阵存储%% R Route 路线%%================================================================ =========N=length(R);scatter(C(:,1),C(:,2));hold onplot([C(R(1),1),C(R(N),1)],[C(R(1),2),C(R(N),2)],'g')hold onfor ii=2:Nplot([C(R(ii-1),1),C(R(ii),1)],[C(R(ii-1),2),C(R(ii),2)],'g')hold onendtitle('旅行商问题优化结果')需要输入的参数数据有:C: n个城市的坐标,n×2的矩阵NC_max: 蚁群算法MATLAB程序最大迭代次数M: 蚂蚁个数Alpha: 表征信息素重要程度的参数Beta:表征启发式因子重要程度的参数Rho: 信息素蒸发系数Q:表示蚁群算法MATLAB程序信息素增加强度系数运行时打开ACATSP.m 点击运行或输入ACATSP(C,NC_max,m,Alpha,Beta,Rho,Q)一个运行实例:m=31;Alpha=1;Beta=5;Rho=0.1;NC_max=200;Q=100;31都市坐标为:1304 23123639 13154177 22443712 13993488 15353326 15563238 12294196 10044312 7904386 5703007 1970 2562 1756 2788 1491 2381 1676 1332 695 3715 1678 3918 2179 4061 2370 3780 2212 3676 2578 4029 2838 4263 2931 3429 1908 3507 2367 3394 2643 3439 3201 2935 3240 3140 3550 2545 2357 2778 2826 2370 2975。
蚁群算法的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```上述代码中的参数可以根据具体问题进行调整。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
//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个错误。