-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmyAlgorithm.cpp
428 lines (362 loc) · 12.7 KB
/
myAlgorithm.cpp
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
#include "myAlgorithm.h"
#include <cstdlib>
#include <ctime>
const int tabRandDiff[] = {1, 1, 2}; // 1 is twice as likely to be chosen than 2
const double MAXSPEED = 1.6; // MAXSPEED > 1
const double SCALE_MIN = 1.0; // SCALE_MIN >= 1
const double SCALE_MAX = 200.0; // SCALE_MAX > SCALE_MIN && SCALE_MAX > 100
const double PM = 0.1; // Mutation rate
const int SIZE_CHOICE_INTERVAL = 6; // Size of tabChoiceInterval
const int tabChoiceInterval[SIZE_CHOICE_INTERVAL] = {3, 3, 3, 2, 1, 0}; // Choice 3 is twice as likely to be chosen
MyAlgorithm::MyAlgorithm(Problem& pbm, SetUpParams& setup) :
_solutions(setup.population_size()),
_setup(setup), _upper_cost(), _lower_cost(),
_results(), _best_solution(NULL), _pbm(pbm)
{
for (unsigned i = 0; i < _solutions.size(); ++i)
_solutions[i] = new Solution(pbm);
_results.reserve(_setup.population_size());
}
MyAlgorithm::~MyAlgorithm()
{
for (unsigned i = 0; i < _solutions.size(); ++i)
delete _solutions[i];
delete _best_solution;
}
double generateDouble(double min = 0.0, double max = 1.0)
{
return (rand() * 1.0 / (1.0 * RAND_MAX)) * (max - min) + min;
}
void MyAlgorithm::initialize()
{
for (unsigned i = 0; i < _solutions.size(); ++i)
_solutions[i]->initialize(); //Solution::initialize();
}
void MyAlgorithm::evaluateFitness()
{
for (unsigned i = 0; i < _solutions.size(); ++i)
_solutions[i]->fitness();
}
const vector<Solution*>& MyAlgorithm::solutions() const
{
return _solutions;
}
vector<double> MyAlgorithm::MeanPerColumn() const
{
vector<double> Means(_setup.solution_size(), 0.0);
for (unsigned k =0 ; k < _solutions.size(); ++k)
{
if (_solutions[k] != _best_solution)
{
vector<double>& S = _solutions[k]->solution();
for (unsigned i = 0; i < S.size(); ++i)
Means[i] += S[i];
}
}
for (unsigned i = 0; i < Means.size(); ++i)
Means[i] /= _setup.population_size() - 1;
return Means;
}
void MyAlgorithm::determineBestSolution()
{
if (_solutions.size())
{
int k = rand() % _setup.population_size();
double minimum = _solutions[k]->get_fitness();
_best_solution = _solutions[k];
for (unsigned i = 0; i < _solutions.size(); ++i)
{
if ((_solutions[i]->get_fitness()) < (minimum))
{
minimum = _solutions[i]->get_fitness();
_best_solution = _solutions[i];
}
}
}
}
void MyAlgorithm::UpdateBestSolutionOverall(Solution* &OverallBestSolution)
{
if (!OverallBestSolution)
OverallBestSolution = new Solution(*_best_solution);
else if ((OverallBestSolution->get_fitness()) > (_best_solution->get_fitness()))
*OverallBestSolution = *_best_solution;
}
Solution& MyAlgorithm::best_solution() const
{
return *_best_solution;
}
double MyAlgorithm::Difference_Mean(int j, const vector<double>& Means, double r) const
{
double Xbest = _best_solution->solution()[j];
double Tf = tabRandDiff[rand() % 3]; // 'One' is twice as likely to be chosen as '2'
double M = Means[j];
return r * (Xbest - Tf * M);
}
double MyAlgorithm::valueAdaptedToPbmInterval(double original, double current)
{
double val;
if (current <= _pbm.max_intervalle())
{
if(current >= _pbm.min_intervalle())
{
val = current;
}
else
{
int tamp = original - _pbm.min_intervalle();
val = original - tamp * (rand() * 1.0 / RAND_MAX);
}
}
else
{
int tamp = _pbm.max_intervalle() - original;
val = original + tamp * (rand() * 1.0 / RAND_MAX);
}
return val;
}
void MyAlgorithm::changeSolutionWithinInterval(vector<double>& tabNewP, int j, double add)
{
tabNewP[j] = valueAdaptedToPbmInterval(tabNewP[j], tabNewP[j] + add);
}
void MyAlgorithm::changeSolutionWithinIntervalAfterFactor(vector<double>& tabNewP, int j, double factor)
{
tabNewP[j] = valueAdaptedToPbmInterval(tabNewP[j], tabNewP[j] * factor);
}
unsigned int minimumOfArray(double* t, int d)
{
unsigned int pos = 0;
for (int i = 1; i < d; ++i)
if ((t[i]) < (t[pos])) pos = i;
return pos;
}
double GenerateScale(int choiceInterval = -1)
{
double SCALE;
if (choiceInterval == -1) choiceInterval = rand() % 4;
if (choiceInterval == 0) SCALE = generateDouble(SCALE_MIN, SCALE_MAX);
else if (choiceInterval == 1) SCALE = generateDouble(SCALE_MIN, SCALE_MAX / 10.0);
else if (choiceInterval == 2) SCALE = generateDouble(SCALE_MIN, SCALE_MAX / 100.0);
else
{
double d = pow(10.0, rand() % 8 + 1); //increase the '8' for more precision after the comma
SCALE = generateDouble(SCALE_MIN, SCALE_MIN + generateDouble(1.0 / d, 10.0 / d));
}
return SCALE;
}
double GenerateScaleWithType(int choiceInterval = -1, int type = -1)
{
if (type == -1) type = rand() % 4;
switch (type)
{
case 0: return 1.0 / GenerateScale(choiceInterval);
break;
case 1: return -1.0 / GenerateScale(choiceInterval);
break;
case 2: return GenerateScale(choiceInterval);
break;
default: return -GenerateScale(choiceInterval);
break;
}
}
void MyAlgorithm::speedControl(const vector<double> &oldS,
vector<double> &newS) const
{
for (unsigned i = 0; i < oldS.size(); ++i)
{
double signe;
if (newS[i] / oldS[i] >= 0.0) signe = 1.0;
else signe = -1.0;
if (abs(newS[i]) > abs(oldS[i] * MAXSPEED))
newS[i] = signe * oldS[i] * MAXSPEED;
else if (abs(newS[i]) < abs(oldS[i] / MAXSPEED))
newS[i] = signe * oldS[i] / MAXSPEED;
}
}
const vector<double>& MyAlgorithm::results() const
{
return _results;
}
double MyAlgorithm::meanResults() const
{
double sum = 0.0;
for (unsigned i = 0; i < _results.size(); ++i)
sum += _results[i];
return sum / _results.size();
}
double MyAlgorithm::sdResults() const
{
double mean = meanResults(), sum = 0.0;
for (unsigned i = 0; i < _results.size(); ++i)
sum += (_results[i] - mean) * (_results[i] - mean);
return sqrt( sum / _results.size() );
}
void MyAlgorithm::outputSummary(ostream& output)
{
output << "Fonction : " << _pbm.name() << endl;
output << "Intervalle de recherche : " << "[" << _pbm.min_intervalle() << ", " << _pbm.max_intervalle() << "]" << endl;
output << "Meilleure fitness : " << _best_solution->get_fitness() << " ---> Solution :" << endl;
output << *_best_solution << endl;
output << "Appels a la fonction par run : " << _pbm.callsToFunction() / _setup.independent_runs() << endl;
output << "Moyenne : " << meanResults() << " Ecart-type : " << sdResults() << endl;
}
void MyAlgorithm::learnFromTeacher(int k, const vector<double>& Means, double r)
{
Solution* newSolution = new Solution(*_solutions[k]);
vector<double>& tabNewSolution(newSolution->solution());
for (unsigned j = 0; j < _setup.solution_size(); ++j)
{
double diffMean = Difference_Mean(j, Means, r);
changeSolutionWithinInterval(tabNewSolution, j, diffMean);
}
speedControl(_solutions[k]->solution(), tabNewSolution);
newSolution->fitness();
if ((newSolution->get_fitness()) < (_solutions[k]->get_fitness()))
{
delete _solutions[k];
_solutions[k] = newSolution;
}
else delete newSolution;
}
void MyAlgorithm::TeachingPhase(double r)
{
vector<double> Means = MeanPerColumn();
for (unsigned k = 0; k < _setup.population_size(); ++k)
{
if (_solutions[k] != _best_solution)
learnFromTeacher(k, Means, r);
}
}
void MyAlgorithm::learnFromPeer(int P, int Q, double r)
{
Solution* newP = new Solution(*_solutions[P]);
vector<double>& tabNewP(newP->solution());
vector<double>& tabQ(_solutions[Q]->solution());
if ((_solutions[Q]->get_fitness()) < (newP->get_fitness()))
{
for (unsigned j = 0; j < _setup.solution_size(); ++j)
{
double add = r * (tabQ[j] - tabNewP[j]);
changeSolutionWithinInterval(tabNewP, j, add);
}
}
else
{
for (unsigned j = 0; j < _setup.solution_size(); ++j)
{
double add = r * (tabNewP[j] - tabQ[j]);
changeSolutionWithinInterval(tabNewP, j, add);
}
}
newP->fitness();
if ((newP->get_fitness()) < (_solutions[P]->get_fitness()))
{
delete _solutions[P];
_solutions[P] = newP;
}
else delete newP;
}
void MyAlgorithm::LearningPhase(double r)
{
for (unsigned k = 0; k < _setup.population_size(); ++k)
{
int Q = rand() % _setup.population_size();
learnFromPeer(k, Q, r);
}
}
void MyAlgorithm::TutorPhase()
{
double SCALE = GenerateScale(tabChoiceInterval[rand() % SIZE_CHOICE_INTERVAL]);
const int ScaleTabSIZE = 4;
double tabRandSCALE[] = {SCALE, 1.0 / SCALE, -1.0 / SCALE, -SCALE};
vector<double>& trainee(_best_solution->solution());
double values[ScaleTabSIZE + 1];
double fitness[ScaleTabSIZE + 1];
for (unsigned j = 0; j < _setup.solution_size(); ++j)
{
values[0] = trainee[j];
for (int i = 1; i < ScaleTabSIZE + 1; ++i)
values[i] = valueAdaptedToPbmInterval(values[0], tabRandSCALE[i - 1] * values[0]);
fitness[0] = _best_solution->get_fitness();
for (int i = 1; i < ScaleTabSIZE + 1; ++i)
{
trainee[j] = values[i];
_best_solution->fitness();
fitness[i] = _best_solution->get_fitness();
}
int posMinFitness = minimumOfArray(fitness, ScaleTabSIZE + 1);
trainee[j] = values[posMinFitness];
_best_solution->set_fitness(fitness[posMinFitness]);
}
}
void MyAlgorithm::solutionTranported(int pos)
{
//int choiceInterval = rand() % 4;
//int type = rand() % 4;
Solution* newS = new Solution(*_solutions[pos]);
vector<double>& tabNewS(newS->solution());
for (unsigned j = 0; j < _setup.solution_size(); ++j)
{
if (generateDouble() < PM)
{
double factor = GenerateScaleWithType(/*choiceInterval, type*/);
changeSolutionWithinIntervalAfterFactor(tabNewS, j, factor);
}
}
newS->fitness();
if ((newS->get_fitness()) < (_solutions[pos]->get_fitness()))
{
delete _solutions[pos];
_solutions[pos] = newS;
}
else delete newS;
}
void MyAlgorithm::TransportationPhase()
{
for (unsigned k = 0; k < _setup.population_size(); ++k)
solutionTranported(k);
}
void MyAlgorithm::evolution(int iter, Viewer& fenetre)
{
int i = 0;
while (i < iter && _best_solution->get_fitness() != 0.0)
{
double r = generateDouble();
/******* !!! Le coeur de l'algorithme: *******/
TutorPhase();
TeachingPhase(r);
TransportationPhase();
LearningPhase(r);
determineBestSolution();
/** Affichage graphique */
fenetre.add(_best_solution->get_fitness());
fenetre.clear();
fenetre.afficheInit();
/** Fin */
cout << "\nFitness: " << _best_solution->get_fitness() << endl;
cout << *_best_solution << endl;
++i;
}
}
void MyAlgorithm::run(Viewer& fenetre)
{
srand(static_cast<unsigned int>(time(NULL)));
Solution* OverallBestSolution = NULL;
for (unsigned i = 0; i < _setup.independent_runs(); ++i)
{
initialize();
evaluateFitness();
determineBestSolution();
evolution(_setup.nb_evolution_steps(), fenetre);
_results.push_back(_best_solution->get_fitness());
UpdateBestSolutionOverall(OverallBestSolution);
}
_best_solution = OverallBestSolution;
cout << "\n---------------------------------------------------------\n";
cout << "Fitness de la meilleure solution : " << _best_solution->get_fitness() << endl;
cout << *_best_solution << "\n" << endl;
cout << "Moyenne : " << meanResults() << " Ecart-type : " << sdResults() << "\n" << endl;
cout << _setup << endl;
cout << "Il y a eut " << _pbm.callsToFunction() / _setup.independent_runs() << " calculs de fitness par run" << endl;
cout << "Probleme optimise : la fonction " << _pbm.name() << endl;
cout << "---------------------------------------------------------\n";
}