Solving tsp problem (JAVA) __c language based on particle swarm optimization

Source: Internet
Author: User
Tags chr gety numeric value rand

One, TSP problem

TSP (travelling salesman Problem) is one of the famous problems in the field of mathematics, which is the traveling salesman problem and the traveling salesman problem. Suppose a traveling businessman wants to visit N cities, he must choose the path he wants to take, the limit of which is that each city can only visit once, and finally return to the original city. The path's selection target is the minimum value in all paths required for the path to be travelled.

TSP problem is a combinatorial optimization problem. This problem can be proved to have NPC computational complexity. TSP can be divided into two kinds, one is symmetric tsp (symmetric tsp) and the other is asymmetric problem (asymmetric tsp). All TSP problems can be described in one graph (graph):

v={c1, c2, ..., CI, ..., cn},i = 1,2, ..., N, is a collection of all cities. CI represents the first city, N is the number of cities;

e={(R, s): R,s∈v} is a collection of connections between all cities;

C = {Crs:r,s∈v} is the cost metric for connections between all cities (generally the distance between cities);

If CRS = CSR, then the TSP problem is symmetric or asymmetric.


a TSP problem can be expressed as:

The solution traverses graph G = (V, E, C), all nodes at once and back to the starting node, making the path cost of connecting these nodes the lowest.

second, particle swarm algorithm

1. Basic Ideas

Particle swarm optimization (PSO) is the basic idea of simulating the predation behavior of bird populations. Imagine a scene where a flock of birds are searching for food at random. There is only one piece of food in the area. All the birds don't know where the food is. But they know how far the current position is from the food. So what's the best strategy for finding food? The simplest and most effective way is to search the surrounding area of the bird nearest to the food.

PSO is derived from this model and is used to solve the optimization problem. In PSO, the solution of each optimization problem is a bird in the search space. We call them "particles." All particles have an adaptive value determined by the function being optimized (fitness value), and each particle has a speed that determines the direction and distance of their flight. The particles then follow the current optimal particle search in the solution space.

The PSO is initialized to a group of random particles (random solutions). Then the optimal solution is found by iteration. In each iteration, the particle updates itself by tracking two "extremes." The first is the optimal solution found by the particle itself, which is called an individual extremum pbest. The other extreme value is the optimal solution that the whole population finds at present, and the Extremum is the global extremum gbest. In addition, it is possible to use only one part of the population as the particle's neighbor, so the extreme value in all the neighbors is the local extremum.

2. Particle formula

When the two optimal values are found, the particle updates its own speed and new position according to the following formula:

V[i] = w * V[i] + C1 * RAND () * (Pbest[i]-present[i]) + C2 * RAND () * (gbest-present[i))

Present[i] = Present[i] + v[i]

where V[i] represents the velocity of the first particle,w represents the inertia weight,C1 and C2 represent learning parameters, andrand () represents the 0-1 the random number,Pbest[i] represents the optimal value of the first particle search,gbest represents the optimal value of the entire cluster search,Present[i] represents the first the current position of the I particle.

3. Personal opinion

So far, particle swarm optimization algorithms can be divided into two main categories, one is the initial elementary particle swarm optimization algorithm, one is the improved generalized particle swarm optimization algorithm, in fact, the initial design of PSO is mainly used to deal with continuous optimization problems, such as the extremum of function, in complex combinatorial optimization problem, its application is very limited, Later, after many scholars ' improvement, it is applied to solve the problem of TSP and single machine scheduling. The generalized particle swarm optimization model is quite similar to the genetic algorithm, at present, there are many papers or codes on solving TSP on the Internet, which are based on the generalized particle swarm algorithm, and the simple point is evolutionary thought, which replaces the iterative formula of elementary particle swarm algorithm with crossover mutation, of course they also have the essence idea of particle swarm optimization, such as crossover with global optimal coding, crossover with local optimal coding, and mutation are all derived from iterative formulae of elementary particle swarm algorithm.

three, particle swarm optimization algorithm to solve TSP problem on the use of elementary particle swarm optimization algorithm, we can refer to the recent article, since the speech particle swarm algorithm, since it is to solve the TSP, using the basic particle swarm algorithm iterative formula is certainly not the case, Here I do not want to write a genetic algorithm similar to the particle swarm algorithm, it is not necessary, as long as the understanding of genetic algorithms, can be written in minutes, here I would like to use a more specific iterative method, first look at its iterative formula:


Here I do not verbose, want to learn more, maybe you need to look at this paper: http://download.csdn.net/detail/wangqiuyun/6373499 is a bit old, it doesn't matter, want is its thought.


We use the TSP problem still comes from the att48 on the Tsplib, this is a symmetric tsp problem, the city scale is 48, its optimal value is 10628. The distance calculation method is shown in the following figure:

OK, here's the specific code:

Package Noah;
Import Java.io.BufferedReader;
Import Java.io.FileInputStream;
Import java.io.IOException;
Import Java.io.InputStreamReader;
Import java.util.ArrayList;

Import Java.util.Random;
	public class PSO {private int bestnum;
	Private float W; private int max_gen;//Iteration number private int scale;//population size private int citynum; Number of cities, encoded length private int t;//current algebra private int[][] distance;  Distance matrix private int[][] opopulation;//particle swarm private arraylist<arraylist<so>> listv;//The initial exchange sequence of each family of particles private  Int[][] pd;//The best solution of a particle in successive dynasties, private int[] vpd;//The evaluation value of the solution private int[] pgd;//the best solution that the whole particle group has ever experienced, each particle can remember the best solution private 

	int vpgd;//best solution evaluation Value private int bestt;//best appearance algebra private int[] fitness;//population adaptability, indicating the fitness of each individual in the population is private Random Random;
	 Public PSO () {}/** * constructor of GA * * @param n * City number * @param g * Run algebra
		* @param w * weight **/public PSO (int n, int g, int s, float w) {this.citynum = n; This. Max_gen= g;
		This.scale = s;
	THIS.W = W; //give the compiler a directive telling it to remain silent @SuppressWarnings ("resource")/** * Initialize the PSO algorithm class * @param filename data file name, which is the file store
		There are city node coordinates data * @throws IOException/private void init (String filename) throws IOException {//Read data int[] x;
		Int[] y;
		String Strbuff;
		BufferedReader data = new BufferedReader (new InputStreamReader) (new FileInputStream (filename));
		Distance = new Int[citynum][citynum];
		x = new Int[citynum];
		y = new Int[citynum];
			for (int i = 0; i < Citynum; i++) {//read one row of data, data format 1 6734 1453 Strbuff = Data.readline ();
			Character segmentation string[] Strcol = Strbuff.split (""); X[i] = integer.valueof (strcol[1])//x coordinate y[i] = integer.valueof (strcol[2]),//Y coordinate}//compute distance matrix//, the distance calculation method is not Like, here is att48 as a case, it has 48 cities, the distance calculation method is pseudo Euclidean distance, the optimal value is 10628 for (int i = 0; i < cityNum-1; i++) {distance[i][i] = 0;//Diagonal Line is 0 for (int j = i + 1; j < Citynum J + +) {double Rij = Math. sqrt ((x[i)-x[j]) * (x[I]-x[j]) + (Y[i]-y[j]) * (Y[i]-y[j))/10.0);
				Rounding, taking the whole int tij = (int) math.round (Rij);
					if (Tij < Rij) {Distance[i][j] = Tij + 1;
				Distance[j][i] = Distance[i][j];
					else {distance[i][j] = Tij;
				Distance[j][i] = Distance[i][j];

		}} Distance[citynum-1][citynum-1] = 0;
		Opopulation = new Int[scale][citynum];

		Fitness = new Int[scale];
		Pd = new Int[scale][citynum];

		VPd = new Int[scale];
		 /* for (int i=0;i<scale;i++) {Vpd[i]=integer.max_value}
		* * PGD = new Int[citynum];

		VPGD = Integer.max_value;

		Npopulation = new Int[scale][citynum];
		BESTT = 0;

		t = 0;
		Random = new Random (System.currenttimemillis ()); /* for (int i=0;i<citynum;i++) {for (int j=0;j<citynum;j++) {* System.out.print (distance[i][j]+ ",");} System.out.println ();
		}///initialization population, multiple random generation methods void Initgroup () {int I, j, K; for (k = 0; k < scale; k++)//Population number {opopulation[k][0] = RANDOM.NExtint (65535)% Citynum;
				for (i = 1; i < citynum;)//number of particles {opopulation[k][i] = random.nextint (65535)% Citynum;
					for (j = 0; J < i; J +) {if (opopulation[k][i] = = Opopulation[k][j]) {break;
				} if (j = = i) {i++; }}/* * for (i=0;i<scale;i++) {for (j=0;j<citynum;j++) {* System.out.print (oldpopulation[i][j]+ ",") ; } System.out.println ();
		} */} void Initlistv () {int ra;
		int RaA;

		int RaB;

		Listv = new arraylist<arraylist<so>> ();
			for (int i = 0; i < scale i++) {arraylist<so> list = new arraylist<so> ();
			RA = random.nextint (65535)% Citynum;
				for (int j = 0; J < Ra; j +) {RaA = Random.nextint (65535)% Citynum;
				RaB = random.nextint (65535)% Citynum;
				while (RaA = = RaB) {RaB = Random.nextint (65535)% Citynum;
				}//RaA is not the same as RaB so s = new SO (RaA, RaB);
			List.add (s);
		} listv.add (list); } public int evaluate (int[] Chr) {//0123 int len = 0; Coding, starting city, City 1, City 2 ...
		City N for (int i = 1; i < Citynum i++) {len + + distance[chr[i-1]][chr[i]];
		}//city N, starting city Len + + distance[chr[citynum-1]][chr[0]];
	return Len;
		//Find a basic switching sequence that acts on the encoded ARR after encoding public void Add (int[] arr, arraylist<so> list) {int temp =-1;
		So s;
			for (int i = 0; i < list.size (); i++) {s = list.get (i);
			temp = Arr[s.getx ()];
			Arr[s.getx ()] = Arr[s.gety ()];
		Arr[s.gety ()] = temp;
		}//Find two basic exchange sequences encoded, such as A-b=ss public arraylist<so> minus (int[] A, int[] B) {int[] temp = B.clone (); * * * int[] temp=new int[l];
		 for (int i=0;i<l;i++) {temp[i]=b[i];}
		*/int index;
		Commutative son so s;
		Exchange sequence arraylist<so> list = new arraylist<so> (); for (int i = 0; i < Citynum i++) {if (a[i)!= Temp[i]) {//find subscript index = A[i with the same numeric value as FindNum in temp (temp
				, A[i]);
				Exchange subscript I with the value of subscript index in temp changeindex (temp, I, index);
		Remember the commutative son s = new So (i, index);		Save the commutative list.add (s);
	} return list;
		///Find num in the ARR array, return the subscript public int findnum (int[] arr of num, int num) {int index =-1;
				for (int i = 0; i < Citynum i++) {if (arr[i] = num) {index = i;
			Break
	} return index; 
		Index1 the value of the array arr subscript and subscript index2 to the public void Changeindex (int[] arr, int index1, int index2) {int temp = arr[index1];
		ARR[INDEX1] = Arr[index2];
	ARR[INDEX2] = temp;  }//Two d array copy public void Copyarray (int[][] from, int[][] to) {for (int i = 0; i < scale; i++) {for (int j = 0; J < Citynum;
			J + +) {To[i][j] = from[i][j];  }}//one-dimensional array copy public void Copyarraynum (int[] from, int[] to) {for (int i = 0; i < Citynum; i++) {To[i] =
		From[i];
		} public void Evolution () {int I, j, K;
		int len = 0;

		float RA = 0f;
		
		Arraylist<so> Vi; 
				Iterate for (t = 0; t < Max_gen; t++) {//For each particle for (i = 0; i < scale; i++) {if (i==bestnum) continue; arraylist<so&Gt
				Vii = new arraylist<so> ();
				System.out.println ("------------------------------");

				Update speed//Vii=wvi+ra (PID-XID) +rb (pgd-xid) Vi = Listv.get (i);
				wvi+ means to get the entire commutative sequence len = (int) (Vi.size () * W) in Vi size*w;
				Cross-border judgment//if (Len>citynum) len=citynum;
				System.out.println ("W:" +w+ "len:" +len+ "Vi.size ():" +vi.size ());
				for (j = 0; J < Len; J +) {Vii.add (Vi.get (j));
				}//Pid-xid arraylist<so> a = minus (Pd[i), opopulation[i]);

				RA = random.nextfloat ();
				RA (pid-xid) + len = (int) (A.size () * ra);
				Cross-border judgment//if (Len>citynum) len=citynum;
				System.out.println ("RA:" +ra+ "len:" +len+ "A.size ():" +a.size ());
				for (j = 0; J < Len; J +) {Vii.add (A.get (j));
				}//Pid-xid arraylist<so> B = Minus (PGD, opopulation[i]);

				RA = random.nextfloat ();
				RA (pid-xid) + len = (int) (B.size () * ra);
				Cross-border judgment//if (Len>citynum) len=citynum; System.out.println ("RA:" +ra+ "Len:" +len+ "B.size ():" +b.size ());
					for (j = 0; J < Len; J +) {so tt= b.get (j);
				Vii.add (TT);

				}//system.out.println ("------------------------------vii.size ():" +vii.size ());

				Preservation of New VII Listv.add (I, vii);
			Update position//Xid ' =xid+vid Add (opopulation[i], Vii);
				///Calculate the new particle swarm fitness, Fitness[max], select the best solution for (k = 0; k < scale; k++) {Fitness[k] = evaluate (opopulation[k));
					if (Vpd[k] > Fitness[k]) {vpd[k] = fitness[k];
					Copyarraynum (Opopulation[k], pd[k]);
				Bestnum=k;
					} if (Vpgd > Vpd[k]) {System.out.println ("Best Length" +vpgd+ "algebra:" +BESTT);
					Bestt = t;
					VPGD = Vpd[k];
				Copyarraynum (Pd[k], PGD);
		}}} public void Solve () {int i;

		int k;
		Initgroup ();

		Initlistv ();

		Each particle remembers its best solution Copyarray (opopulation, Pd);
			Calculate initialization population Fitness, Fitness[max], select the best solution for (k = 0; k < scale; k++) {Fitness[k] = evaluate (opopulation[k));
			VPD[K] = fitness[k]; if (Vpgd > Vpd[k]) {VPGD = vpd[k];
				Copyarraynum (Pd[k], PGD);
			Bestnum=k;
		}//Print System.out.println ("Initial particle swarm ...");
			for (k = 0; k < scale; k++) {for (i = 0; i < Citynum; i++) {System.out.print (Opopulation[k][i] + ",");
			} System.out.println ();

			SYSTEM.OUT.PRINTLN ("----" + fitness[k]);
			/* Arraylist<so> Li = listv.get (k);
			int L = li.size ();
			for (i = 0; i < L; i++) {Li.get (i). print ();
			} System.out.println ("----");

		*///Evolution evolution ();
		Print System.out.println ("Last particle swarm ...");
			for (k = 0; k < scale; k++) {for (i = 0; i < Citynum; i++) {System.out.print (Opopulation[k][i] + ",");
			} System.out.println ();

			SYSTEM.OUT.PRINTLN ("----" + fitness[k]);
			/* Arraylist<so> Li = listv.get (k);
			int L = li.size ();
			for (i = 0; i < L; i++) {Li.get (i). print ();
			} System.out.println ("----");
		*/} System.out.println ("The best length appears algebra:");
		System.out.println (BESTT); System.out. println ("best Length");
		System.out.println (VPGD);
		SYSTEM.OUT.PRINTLN ("Best path:");
		for (i = 0; i < Citynum i++) {System.out.print (Pgd[i] + ",");
		}/** * @param args * @throws ioexception/public static void main (string[] args) throws IOException {

		System.out.println ("Start ...");
		PSO PSO = new PSO (5000, 0.5f);
		Pso.init ("C://data.txt");
	Pso.solve ();
 }
}

Run Results screenshot:


summing up the results of this experiment, in fact, I personally can not accept, but at the moment I can only put the problem due to the paper's iterative formula, but the paper was a long time, it tried 14 points, here are 48, the gap is certainly there, perhaps there are some adjustments, The effect will be better, but at present I am limited time, not too late to in-depth experiments, only interested people to carry out in-depth stripping.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.