-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
265 lines (246 loc) · 8.97 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace TSP_EA
{
class CityPoint
{
public int ID { get; set; }
public int X { get; set; }
public int Y { get; set; }
}
class Distance_Cities
{
private List<CityPoint> Cordination = new List<CityPoint>();
private static int[,] Distance_Matrix = new int[127, 127];
public Distance_Cities()
{
string line;
StreamReader file = new StreamReader("TSPDATA.txt");
while ((line = file.ReadLine()) != null)
{
string[] subs = line.Split(' ');
CityPoint ct = new CityPoint();
List<string> ne = new List<string>();
foreach (var s in subs)
{
if (s != "")
ne.Add(s);
}
ct.ID = Convert.ToInt16(ne[0]);
ct.X = Convert.ToInt16(ne[1]);
ct.Y = Convert.ToInt16(ne[2]);
Cordination.Add(ct);
}
}
public void SetDistanceMatrix()
{
for (int i = 0; i < 127; i++)
{
for (int j = 0; j < 127 ; j++)
{
if(i!=j)
Distance_Matrix[i, j] = (int)Math.Sqrt(Math.Pow((Cordination[i].X - Cordination[j].X), 2) + Math.Pow((Cordination[i].Y - Cordination[j].Y), 2));
}
}
}
public int GetDistanceTwoPoints(int i, int j)
{
return Distance_Matrix[i-1, j-1];
}
}
class Individual
{
#region properties
public List<int> Chromosome { get; set; }
public float Fitness { get; set; }
public float Length { set; get; }
#endregion
#region methods
public void SetChromosome()
{
//randomly
Chromosome = new List<int>();
for (int i = 1; i < 128; i++)
Chromosome.Add(i);
new Random().Shuffle(Chromosome);
}
public void SetFitness()
{
Distance_Cities distances = new Distance_Cities();
for (int i = 0; i < 126; i++)
Length += distances.GetDistanceTwoPoints(Chromosome[i],Chromosome[i+1]);
Fitness =(float) 100000 /(float)Length;
}
#endregion
}
class EvolutionaryAlgorithm
{
#region properties
private int Size;
private int EliteSize;
public List<Individual> Population;
public List<Individual> MatingPool = new List<Individual>();
public List<Individual> OffSprings= new List<Individual>();
public List<float> MyRouletteWheel=new List<float>();
#endregion
#region methods
public EvolutionaryAlgorithm(int _size,int _elitesize)
{
Size = _size;
EliteSize = _elitesize;
}
public void Initialization()
{
Population = new List<Individual>();
for (int i = 0; i < Size; i++)
{
var ind = new Individual();
ind.SetChromosome();
ind.SetFitness();
Population.Add(ind);
}
}
public void SetRouletteWheel()
{
MyRouletteWheel.Clear();
MyRouletteWheel = new List<float>() { 0};
var sum = Population.Sum(o => o.Fitness);
Population.ForEach(i =>
MyRouletteWheel.Add(i.Fitness / sum+MyRouletteWheel.Last()));
}
public void ParentSelection()
{
var rng = new Random();
MatingPool.Clear();
for (int j=0;j<Size-EliteSize;j++)
{
int k = 0;
var p = rng.NextDouble();
while (p> MyRouletteWheel[k])
{
k++;
}
MatingPool.Add(Population[k - 1]);
}
MatingPool.AddRange(Population.OrderByDescending(o => o.Fitness).Take(EliteSize));
}
public void SurvivorSelection()
{
new Random().Shuffle(OffSprings);
Population = OffSprings;
}
public void Mutation(double MutationRate)
{
for (int i = 0; i < OffSprings.Count-EliteSize; i++)
{
if (MutationRate < new Random().NextDouble())
{
int FirstIndex = new Random().Next(127);
int SecoundIndex = new Random().Next(127);
while (FirstIndex == SecoundIndex)
{
SecoundIndex = new Random().Next(127);
}
var temp = OffSprings[i].Chromosome[FirstIndex];
OffSprings[i].Chromosome[FirstIndex] = OffSprings[i].Chromosome[SecoundIndex];
OffSprings[i].Chromosome[SecoundIndex] = temp;
OffSprings[i].SetFitness();
}
}
}
public void Recombination()
{
OffSprings = new List<Individual>();
for (int i = 0; i + 1 < MatingPool.Count-EliteSize; i = i + 2)
{
OffSprings.AddRange(CrossOver(MatingPool[i], MatingPool[i + 1]));
}
OffSprings.AddRange(MatingPool.Skip(MatingPool.Count - EliteSize));
}
public List<Individual> CrossOver(Individual A, Individual B)
{
Random rnd = new Random();
Individual C = new Individual();
Individual D = new Individual();
int P1 = rnd.Next(127);
int P2 = P1;
while (P1==P2)
P2 = rnd.Next(127);
int StartPoint= Math.Min(P1, P2);
int EndPoint = Math.Max(P1, P2);
C.Chromosome = A.Chromosome.Take(EndPoint).Skip(StartPoint).ToList();
D.Chromosome = B.Chromosome.Take(EndPoint).Skip(StartPoint).ToList();
for (int i = EndPoint; i < 127; i++)
{
if (!C.Chromosome.Contains(B.Chromosome[i]))
C.Chromosome.Add(B.Chromosome[i]);
if (!D.Chromosome.Contains(A.Chromosome[i]))
D.Chromosome.Add(A.Chromosome[i]);
}
for (int i = 0; i < EndPoint; i++)
{
if (!C.Chromosome.Contains(B.Chromosome[i]))
C.Chromosome.Add(B.Chromosome[i]);
if (!D.Chromosome.Contains(A.Chromosome[i]))
D.Chromosome.Add(A.Chromosome[i]);
}
C.Chromosome = C.Chromosome.Skip(A.Chromosome.Count - StartPoint)
.Concat(C.Chromosome.Take(A.Chromosome.Count - StartPoint).ToList()).ToList();
D.Chromosome = D.Chromosome.Skip(B.Chromosome.Count - StartPoint)
.Concat(D.Chromosome.Take(B.Chromosome.Count - StartPoint).ToList()).ToList();
C.SetFitness();
D.SetFitness();
return new List<Individual>() { C, D };
}
public void PrintMyPopulation()
{
Console.WriteLine("best fitness=" + Population.Max(i=>i.Fitness));
Console.WriteLine("AVG fitness=" + Population.Average(i => i.Fitness));
Console.WriteLine("best Length=" + Population.Min(i => i.Length));
Console.WriteLine("AVG Length=" + Population.Average(i => i.Length));
Console.WriteLine("best path =");
foreach (var gen in Population.OrderBy(p => p.Fitness).First().Chromosome)
Console.Write("," +gen);
}
#endregion
}
class Program
{
static void Main(string[] args)
{
Distance_Cities ct = new Distance_Cities();
ct.SetDistanceMatrix();
Console.WriteLine("Initialization==> ");
EvolutionaryAlgorithm MyEA = new EvolutionaryAlgorithm(1000,50);
MyEA.Initialization();
MyEA.PrintMyPopulation();
int i = 1;
for (; i<400; i++)
{
Console.WriteLine("\n Generation==> " + i);
MyEA.SetRouletteWheel();
MyEA.ParentSelection();
MyEA.Recombination();
MyEA.Mutation(0.8);
MyEA.SurvivorSelection();
MyEA.PrintMyPopulation();
}
}
}
static class RandomExtensions
{
public static void Shuffle<T>(this Random rng, List<T> array)
{
int n = array.Count;
while (n > 1)
{
int k = rng.Next(n--);
T temp = array[n];
array[n] = array[k];
array[k] = temp;
}
}
}
}