//=====================================================================
Basic ant colony Algorithm source code
The city data used is EIL51.TSP
//=====================================================================
AO.cpp: Defines the entry point of the console application.
#pragma once
#include "stdafx.h"
#include <iostream>
#include <math.h>
#include <time.h>
//=====================================================================
Constant definitions and parameter definitions
//=====================================================================
const double alpha=1.0; Heuristic factor, importance of pheromone
const double beta=2.0; Expected factor, the importance of distance between cities
const double rou=0.5; Pheromone Residue Parameters
const int n_ant_count=34; Number of ants
const int n_it_count=1000; Number of iterations
const int n_city_count=51; Number of cities
const double dbq=100.0; The total pheromone
const double DB_MAX=10E9; A flag number, 10 of the 9-time Square
Double G_trial[n_city_count][n_city_count]; 22 Inter-city pheromone is the environmental pheromone
Double G_distance[n_city_count][n_city_count]; 22 Distance between cities
EIL51.TSP City Coordinate data
Double x_ary[n_city_count]=
{
37,49,52,20,40,21,17,31,52,51,
42,31,5,12,36,52,27,17,13,57,
62,42,16,8,7,27,30,43,58,58,
37,38,46,61,62,63,32,45,59,5,
10,21,5,30,39,32,25,25,48,56,
};
Double y_ary[n_city_count]=
{
52,49,64,26,30,47,63,62,33,21,
41,32,25,42,16,41,23,33,13,58,
42,57,57,52,38,68,48,67,48,27,
69,46,10,33,63,69,22,35,15,6,
17,10,64,15,10,39,32,55,28,37,
};
Returns a random integer in the specified range
int rnd (int nlow,int nupper)
{
Return nlow+ (Nupper-nlow) *rand ()/(rand_max+1);
}
Returns the random floating-point number in the specified range
Double rnd (double dblow,double dbupper)
{
Double Dbtemp=rand ()/((double) rand_max+1.0);
Return dblow+dbtemp* (Dbupper-dblow);
}
Returns the floating-point number of a floating-point number rounding rounding
Double ROUND (double DbA)
{
Return (double) ((int) (dba+0.5));
}
//=====================================================================
The definition and realization of ant class
//=====================================================================
Define Ant Class
Class CAnt
{
Public
CAnt (void);
~cant (void);
Public
int M_npath[n_city_count]; The path of the ant walking
Double m_dbpathlength; The length of the path that ants walk through
int M_nallowedcity[n_city_count]; A city you've never been to.
int M_ncurcityno; Current City number
int m_nmovedcitycount; Number of cities that have been visited
Public
int choosenextcity (); Choose the next City
void Init (); Initialization
void Move (); The ants move between cities
void Search (); Search Path
void Calpathlength (); Calculate the length of the path that ants walk through
};
constructor function
Cant::cant (void)
{
}
Destructors
Cant::~cant (void)
{
}
Initialize function, call before Ant search
void Cant::init ()
{
for (int i=0;i<n_city_count;i++)
{
M_nallowedcity[i]=1; Set up all cities for never been to
m_npath[i]=0; The path of the ant goes all set to 0
}
The length of the path the ant traversed was set to 0
m_dbpathlength=0.0;
Randomly select a departure city
M_ncurcityno=rnd (0,n_city_count);
Save the departure city into an array of paths
M_npath[0]=m_ncurcityno;
Identify the departure city to have been gone
m_nallowedcity[m_ncurcityno]=0;
The number of cities that have been visited is set to 1
M_nmovedcitycount=1;
}
Choose the next City
The return value is the city number
int cant::choosenextcity ()
{
int nselectedcity=-1; To return the result, set it to 1 temporarily
//==============================================================================
Calculates the sum of pheromone between the current city and the city that has not been visited
Double dbtotal=0.0;
Double Prob[n_city_count]; The probability of saving each city being selected
for (int i=0;i<n_city_count;i++)
{
if (m_nallowedcity[i] = = 1)//city has not been to
{
The pheromone between the city and the current city
Prob[i]=pow (G_trial[m_ncurcityno][i],alpha) *pow (1.0/g_distance[m_ncurcityno][i],beta);
Dbtotal=dbtotal+prob[i]; Accumulate pheromone, get the sum
}
else//If the city has been gone, the probability of its being selected is 0
{
prob[i]=0.0;
}
}
//==============================================================================
Make Roulette selection
Double dbtemp=0.0;
if (Dbtotal > 0.0)//Total pheromone value is greater than 0
{
Dbtemp=rnd (0.0,dbtotal); Take a random number
for (int i=0;i<n_city_count;i++)
{
if (m_nallowedcity[i] = = 1)//city has not been to
{
printf ("dbtemp=%f-i=%d", dbtemp,i); System ("pause");
Dbtemp=dbtemp-prob[i]; This operation is equivalent to rotating the roulette wheel, if you are unfamiliar with the roulette selection, carefully consider
if (Dbtemp < 0.0)//Roulette stop turning, write down the city number, jump out of the loop directly
{
Nselectedcity=i;
Break
}
}
}
if (dbtemp>0) {printf ("dbtemp=%d", dbtemp); System ("Pause");}
}
//==============================================================================
If the pheromone between cities is very small (smaller than the smallest number that a double can represent)
Then, due to the error of floating-point arithmetic, the probability sum calculated above may be 0.
will appear after the above operation, no city is selected
In this case, we return the first city I have never been to.
if (nselectedcity = =-1)
{
for (int i=0;i<n_city_count;i++)
{
if (m_nallowedcity[i] = = 1)//city has not been to
{
Nselectedcity=i;
Break
}
}
}
//==============================================================================
Return the result, the city number
return nselectedcity;
}
The ants move between cities
void Cant::move ()
{
int ncityno=choosenextcity (); Choose the next City
M_npath[m_nmovedcitycount]=ncityno; Save the path of the Ant's Walk
m_nallowedcity[ncityno]=0;//set the city to have been gone.
M_ncurcityno=ncityno; Change the current city for the selected city
m_nmovedcitycount++; Number of cities already visited plus 1
}
Ant to search once
void Cant::search ()
{
Init (); Before the ant searches, first initialize
If the number of cities that ants have visited is smaller than the number of cities, move on.
while (M_nmovedcitycount < N_city_count)
{
Move ();
}
Calculate traversed path length after completion of search
Calpathlength ();
}
Calculate the length of the path that ants walk through
void Cant::calpathlength ()
{
m_dbpathlength=0.0; Set the path length to 0 first
int m=0;
int n=0;
for (int i=1;i<n_city_count;i++)
{
M=m_npath[i];
N=M_NPATH[I-1];
M_dbpathlength=m_dbpathlength+g_distance[m][n];
}
Plus the distance from the last city back to the departure city.
N=M_NPATH[0];
M_dbpathlength=m_dbpathlength+g_distance[m][n];
}
//=====================================================================
The definition and implementation of TSP class
//=====================================================================
TSP class
Class CTSP
{
Public
CTSP (void);
~CTSP (void);
Public
CAnt M_cantary[n_ant_count]; Ant Array
CAnt m_cbestant; Define an ant variable to hold the best results in the search process
The ant does not participate in the search, just to save the best results
Public
Initializing data
void InitData ();
Start Search
void Search ();
Update Environmental pheromone
void Updatetrial ();
};
constructor function
CTSP::CTSP (void)
{
}
CTSP::~CTSP (void)
{
}
Initializing data
void Ctsp::initdata ()
{
First, the path length of the optimal ant is set to a very large value.
M_cbestant.m_dbpathlength=db_max;
Calculate the distance between 22 cities
Double dbtemp=0.0;
for (int i=0;i<n_city_count;i++)
{
for (int j=0;j<n_city_count;j++)
{
Dbtemp= (X_ary[i]-x_ary[j]) * (X_ary[i]-x_ary[j]) + (Y_ary[i]-y_ary[j]) * (Y_ary[i]-y_ary[j]);
Dbtemp=pow (dbtemp,0.5);
Inter-city distance rounding, the shortest path of EIL51.TSP 426 is the distance is rounded rounding out after getting the whole.
G_distance[i][j]=round (dbtemp);
}
}
To initialize the environment pheromone, first set the inter-city pheromone to the same
This is set to 1.0, the number of settings to the effect of the result is not too large, the convergence speed of the algorithm has some impact
for (int i=0;i<n_city_count;i++)
{
for (int j=0;j<n_city_count;j++)
{
g_trial[i][j]=1.0;
}
}
}
Update Environmental pheromone
void Ctsp::updatetrial ()
{
Temporary array, preserving the new pheromone left by each ant in 22 cities
Double Dbtempary[n_city_count][n_city_count];
memset (dbtempary,0,sizeof (dbtempary)); Set all to 0 first
Calculates the newly added pheromone and saves it in a temporary array.
int m=0;
int n=0;
for (int i=0;i<n_ant_count;i++)//Calculate the pheromone left by each ant
{
for (int j=1;j<n_city_count;j++)
{
M=M_CANTARY[I].M_NPATH[J];
N=M_CANTARY[I].M_NPATH[J-1];
Dbtempary[n][m]=dbtempary[n][m]+dbq/m_cantary[i].m_dbpathlength;
DBTEMPARY[M][N]=DBTEMPARY[N][M];
}
The pheromone between the last city and the beginning of the city
N=M_CANTARY[I].M_NPATH[0];
Dbtempary[n][m]=dbtempary[n][m]+dbq/m_cantary[i].m_dbpathlength;
DBTEMPARY[M][N]=DBTEMPARY[N][M];
}
//==================================================================
Update Environmental pheromone
for (int i=0;i<n_city_count;i++)
{
for (int j=0;j<n_city_count;j++)
{
G_TRIAL[I][J]=G_TRIAL[I][J]*ROU+DBTEMPARY[I][J]; Latest Environmental pheromone = retained pheromone + newly-left pheromone
}
}
}
void Ctsp::search ()
{
Char cbuf[256]; Printing information with
Loop over iteration number of iterations
for (int i=0;i<n_it_count;i++)
{
Every ant searches for it again.
for (int j=0;j<n_ant_count;j++)
{
M_CANTARY[J]. Search ();
}
Save best results
for (int j=0;j<n_ant_count;j++)
{
if (M_cantary[j].m_dbpathlength < m_cbestant.m_dbpathlength)
{
M_CBESTANT=M_CANTARY[J];
}
}
Update Environmental pheromone
Updatetrial ();
Output the length of the optimal path found so far
sprintf (Cbuf, "\n[%d]%.0f", i+1,m_cbestant.m_dbpathlength);
printf (CBUF);
}
}
//=====================================================================
Main program
//=====================================================================
int main ()
{
Initializes random seeds with the current point-in-time to prevent the same results for each run
time_t TM;
Time (&TM);
unsigned int nseed= (unsigned int) TM;
Srand (Nseed);
Start Search
CTSP tsp;
Tsp. InitData (); Initialization
Tsp. Search (); Start Search
Output results
printf ("\nthe is: \ n");
Char cbuf[128];
for (int i=0;i<n_city_count;i++)
{
sprintf (Cbuf, "%02d", tsp.m_cbestant.m_npath[i]+1);
if (i% 20 = = 0)
{
printf ("\ n");
}
printf (CBUF);
}
printf ("\n\npress any key to exit!");
GetChar ();
return 0;
}
Reprint: http://www.cnblogs.com/sky-view/p/3281186.html
Basic Ant Colony algorithm