Update from Dario, SVN rev. 116.
[PaGMO.git] / main.cpp
blob1d3de081e1126e35c178852139dfb8f0bd273eb5
1 #include <iostream>
2 #include <fstream>
3 #include <iomanip>
4 #include <vector>
5 #include <ctime> //for time()
6 #include "population.h"
7 #include "ASA.h"
8 #include "PSO.h"
9 #include "DE.h"
10 #include "SGA.h"
11 #include "MPSO.h"
12 #include "LOCAL.h"
13 #include "TrajectoryProblems.h"
14 #include "ClassicProblems.h"
15 #include <pthread.h>
16 #include "SolversThreads.h"
17 #include "PkRandom.h"
19 using namespace std;
21 int main(){
23 int D =0; //Problem dimension will be assigned later
24 int choice=0; //User choice
25 cout.precision(9);
27 //We prepare the pseudorandom sequence (TODO: check the randomnumbers of different threads are different)
29 Pk::Random32 rng(time(0));
31 //we set the problem
32 messengerfullProb problem;
33 //we extract its information into local variables
34 const vector<double>& LB = problem.getLB();
35 const vector<double>& UB = problem.getUB();
36 D = problem.getDimension();
38 //we declare populations and individuals
39 Population demeDE,demePSO,demeASA,demeLOCA,demeSGA,pop;
40 Individual x;
41 vector <int> picksDE,picksPSO,picksASA,picksLOCAL,picksSGA;
43 time_t start,end,start1,end1;
44 double dif;
46 //We create and open the logfile
47 ofstream logfile("log.txt");
51 while (choice != -1) {
53 //we choose the algorithm
55 cout << "Choose: 1-ASA, 2-PSO, 3-MPSO, 4-DE, 5-SGA, 6-IslandModel(ring), Default-DiGMO: ";
56 cin >> choice;
58 switch (choice){
59 case 1:
61 //Experiment Settings
62 int NP = 1; //population size
63 int trials = 300; //number of trials
64 int niterTot = 10000; //generations per algorithm call
65 int niterRange = 20;
66 int niterTemp = 1;
67 double T0 = 10;
68 double Tf = T0/1000;
69 double Tcoeff = 0.85;
70 double StartStep =1;
72 //stopping criteria
73 int itermax = 120; //Maximum number of iterations allowed (i.e. output printed on the screen)
75 //Experiment Outputs
76 double mean = 0, dev= 0, max = 0, min = 200000000;
77 vector <double> results;
79 //Instanciate the algorithm
80 //Adaptive Simulated Annealing
81 ASAalgorithm ASA;
82 //ASA.initASA(niterTot,niterTemp,niterRange,LB.size(),T0,Tcoeff,StartStep, rng.next());
83 ASA.initASA(niterTot,LB.size(),T0,Tf, rng.next());
85 //Pruned bounds
87 for (int i=0;i<trials;i++){
88 cout << "\nTrial number #" << i+1 << endl;
89 //we create a random population
90 pop.createRandomPopulation(LB,UB,NP, rng);
91 pop.evaluatePopulation(problem);
92 int iter = 0;
94 time(&start);
95 while( iter < itermax){
96 iter ++;
97 //we print the best
98 cout << "Initial fitness: " << pop.extractBestIndividual().getFitness() << endl;
99 //we evolve it
100 start1=clock();
101 if (pop.extractBestIndividual().getFitness() < 5){
102 ASA.initASA(niterTot,LB.size(),1,0.01, rng.next());
104 pop = ASA.evolve(pop[0],problem);
105 end1=clock();
106 dif = (double)(end1-start1) / (double)CLOCKS_PER_SEC;
107 //we print the result
108 cout << "Final fitness: " << pop.extractBestIndividual().getFitness() << endl;
109 cout << "Worst fitness: " << pop.extractWorstIndividual().getFitness() << endl;
110 cout << "Mean : " << pop.evaluateMean() << endl;
111 cout << "Std : " << pop.evaluateStd() << endl;
112 cout << "\t\tSeconds elapsed: " << dif << endl;
114 time(&end);
115 results.push_back(pop.extractBestIndividual().getFitness());
116 dif = difftime(end,start);
117 cout << "\nSeconds elapsed: " << dif << endl<<endl;
118 for (int i=0;i<D;i++){
119 logfile << pop.extractBestIndividual()[i] << " ";
121 logfile << exp(-pop.extractBestIndividual().getFitness()) <<endl;
124 //evaluate experiment results
125 for (int i=0;i<trials;i++){
126 mean += results[i];
127 if (results[i] > max) max = results[i];
128 if (results[i] < min) min = results[i];
130 mean /= trials;
132 for (int i=0;i<trials;i++){
133 dev += (mean-results[i])*(mean-results[i]);
135 dev = sqrt(dev/trials);
137 for (int i=0;i<trials;i++){
138 cout << "\nTrial #" << i << ": " << results[i] << endl;
142 //print results
143 cout << "\nMean: " << mean << endl;
144 cout << "Std: " << dev << endl;
145 cout << "Max: " << max << endl;
146 cout << "Min: " << min << endl;
148 //Lines to test ASA
149 break;
151 case 2: //PSO sequential experiment
153 //Experiment Settings
154 int NP = 20; //population size
155 int trials = 100; //number of trials
156 int gen = 500; //generations per algorithm call
157 double omega = 0.6;
158 double eta1 = 2;
159 double eta2 = 2;
160 int vcoeff = 1;
162 //stopping criteria
163 int itermax = 120; //Maximum number of iterations allowed (i.e. output printed on the screen)
164 double stdmin = 1e-5; //Standard deviation of the population that determines a stop
166 //Experiment Outputs
167 double mean = 0, dev= 0, max = 0, min = 200000000;
168 vector <double> results;
170 //Instanciate the algorithm
171 PSOalgorithm PSO;
172 PSO.initPSO(gen,LB.size(),omega,eta1,eta2,vcoeff, rng.next());
174 for (int i=0;i<trials;i++){
175 cout << "\nTrial number #" << i+1 << endl;
176 //we create a random population
177 pop.createRandomPopulation(LB,UB,NP, rng);
178 pop.evaluatePopulation(problem);
179 int iter = 0;
181 time(&start);
182 while(iter < itermax){
183 iter ++;
184 //we print the best
185 cout << "Initial fitness: " << pop.extractBestIndividual().getFitness() << endl;
186 //we evolve it
187 start1=clock();
188 pop = PSO.evolve(pop,problem);
189 end1=clock();
190 dif = (double)(end1-start1) / (double)CLOCKS_PER_SEC;
191 //we print the result
192 cout << "Final fitness: " << pop.extractBestIndividual().getFitness() << endl;
193 cout << "Worst fitness: " << pop.extractWorstIndividual().getFitness() << endl;
194 cout << "Mean : " << pop.evaluateMean() << endl;
195 cout << "Std : " << pop.evaluateStd() << endl;
196 cout << "\t\tSeconds elapsed: " << dif << endl;
198 time(&end);
199 results.push_back(pop.extractBestIndividual().getFitness());
200 dif = difftime(end,start);
201 cout << "\nSeconds elapsed: " << dif << endl<<endl;
204 //evaluate experiment results
205 for (int i=0;i<trials;i++){
206 mean += results[i];
207 if (results[i] > max) max = results[i];
208 if (results[i] < min) min = results[i];
210 mean /= trials;
212 for (int i=0;i<trials;i++){
213 dev += (mean-results[i])*(mean-results[i]);
215 dev = sqrt(dev/trials);
217 for (int i=0;i<trials;i++){
218 cout << "\nTrial #" << i << ": " << results[i] << endl;
222 //print results
223 cout << "\nMean: " << mean << endl;
224 cout << "Std: " << dev << endl;
225 cout << "Max: " << max << endl;
226 cout << "Min: " << min << endl;
228 break;
230 case 3: //MPSO sequential experiment
232 //Experiment Settings
233 int NP = 20; //population size
234 int trials = 100; //number of trials
235 int gen = 500; //generations per algorithm call
236 double omega = 0.65;
237 double eta1 = 2.0;
238 double eta2 = 2.0;
239 int vcoeff = 1;
240 int nswarms = 4;
242 //stopping criteria
243 int itermax = 100; //Maximum number of iterations allowed (i.e. output printed on the screen)
244 double stdmin = 1e-5; //Standard deviation of the population that determines a stop
246 //Experiment Outputs
247 double mean = 0, dev= 0, max = 0, min = 200000000;
248 vector <double> results;
250 //Instanciate the algorithm
251 MPSOalgorithm MPSO;
252 MPSO.initMPSO(gen,LB.size(),omega,eta1,eta2,vcoeff,nswarms, rng.next());
254 for (int i=0;i<trials;i++){
255 cout << "\nTrial number #" << i+1 << endl;
256 //we create a random population
257 pop.createRandomPopulation(LB,UB,NP, rng);
258 pop.evaluatePopulation(problem);
259 int iter = 0;
261 time(&start);
262 while(iter < itermax){
263 iter ++;
264 //we print the best
265 cout << "Initial fitness: " << pop.extractBestIndividual().getFitness() << endl;
266 //we evolve it
267 start1=clock();
268 pop = MPSO.evolve(pop,problem);
269 end1=clock();
270 dif = (double)(end1-start1) / (double)CLOCKS_PER_SEC;
271 //we print the result
272 cout << "Final fitness: " << pop.extractBestIndividual().getFitness() << endl;
273 cout << "Worst fitness: " << pop.extractWorstIndividual().getFitness() << endl;
274 cout << "Mean : " << pop.evaluateMean() << endl;
275 cout << "Std : " << pop.evaluateStd() << endl;
276 cout << "\t\tSeconds elapsed: " << dif << endl;
278 time(&end);
279 results.push_back(pop.extractBestIndividual().getFitness());
280 dif = difftime(end,start);
281 cout << "\nSeconds elapsed: " << dif << endl<<endl;
284 //evaluate experiment results
285 for (int i=0;i<trials;i++){
286 mean += results[i];
287 if (results[i] > max) max = results[i];
288 if (results[i] < min) min = results[i];
290 mean /= trials;
292 for (int i=0;i<trials;i++){
293 dev += (mean-results[i])*(mean-results[i]);
295 dev = sqrt(dev/trials);
297 for (int i=0;i<trials;i++){
298 cout << "\nTrial #" << i << ": " << results[i] << endl;
302 //print results
303 cout << "\nMean: " << mean << endl;
304 cout << "Std: " << dev << endl;
305 cout << "Max: " << max << endl;
306 cout << "Min: " << min << endl;
308 break;
312 case 4: //Sequential Differential Evolution Experiment
314 //Experiment Settings
315 int NP = 20; //population size for each island
316 int trials = 100; //number of trials
317 int gen = 500; //generations per algorithm call
318 double F = 0.8; //F in DE
319 double CR = 0.8; //CR in DE
320 int strategy = 2; //DE startegy
322 //stopping criteria
323 int itermax = 120; //Maximum number of iterations allowed (i.e. output printed on the screen)
325 //Experiment Outputs
326 double mean = 0, dev= 0, max = 0, min = 200000000;
327 vector <double> results;
329 //Instanciate the algorithm
330 DEalgorithm DE;
331 DE.initDE(gen,LB.size(),F,CR,strategy, rng.next());
333 for (int i=0;i<trials;i++){
334 cout << "\nTrial number #" << i+1 << endl;
335 //we create a random population
338 pop.createRandomPopulation(LB,UB,NP, rng);
339 pop.evaluatePopulation(problem);
340 int iter = 0;
342 time(&start);
343 while( iter < itermax){
344 iter ++;
345 //we print the best
346 cout << "Initial fitness: " << pop.extractBestIndividual().getFitness() << endl;
347 //we evolve it
348 start1=clock();
349 pop = DE.evolve(pop,problem);
350 end1=clock();
351 dif = (double)(end1-start1) / (double)CLOCKS_PER_SEC;
352 //we print the result
353 cout << "Final fitness: " << pop.extractBestIndividual().getFitness() << endl;
354 cout << "Worst fitness: " << pop.extractWorstIndividual().getFitness() << endl;
355 cout << "Mean : " << pop.evaluateMean() << endl;
356 cout << "Std : " << pop.evaluateStd() << endl;
357 cout << "\t\tSeconds elapsed: " << dif << endl;
359 time(&end);
360 //if (iter<itermax){
361 //results.push_back(iter*NP*gen);
362 results.push_back(pop.extractBestIndividual().getFitness());
364 dif = difftime(end,start);
365 cout << "\nSeconds elapsed: " << dif << endl<<endl;
366 for (int i=0;i<D;i++){
367 logfile << pop.extractBestIndividual()[i] << " ";
369 logfile << exp(-pop.extractBestIndividual().getFitness()) <<endl;
372 //evaluate experiment results
373 for (unsigned int i=0;i<results.size();i++){
374 mean += results[i];
375 if (results[i] > max) max = results[i];
376 if (results[i] < min) min = results[i];
378 mean /= results.size();
380 for (unsigned int i=0;i<results.size();i++){
381 dev += (mean-results[i])*(mean-results[i]);
383 dev = sqrt(dev/results.size());
385 for (unsigned int i=0;i<results.size();i++){
386 cout << "\nTrial #" << i << ": " << results[i] << endl;
389 //print results
390 cout << "\nMean: " << mean << endl;
391 cout << "Std: " << dev << endl;
392 cout << "Max: " << max << endl;
393 cout << "Min: " << min << endl;
394 cout << "Success: " << results.size() << endl;
396 break;
400 case 5: //SGA experiment
402 //Experiment Settings
403 int NP = 20; //population size
404 int trials = 100; //number of trials
405 int gen = 500; //generations per algorithm call
406 double CR = 0.7;
407 double M = 0.2;
408 int insert_best = 1;
410 //stopping criteria
411 int itermax = 120; //Maximum number of iterations allowed (i.e. output printed on the screen)
413 //Experiment Outputs
414 double mean = 0, dev= 0, max = 0, min = 200000000;
415 vector <double> results;
417 //Instanciate the algorithm
418 //Simple Genetic Algorithm
419 SGAalgorithm SGA;
420 SGA.initSGA(gen,LB.size(),CR,M,insert_best, rng.next());
422 for (int i=0;i<trials;i++){
423 cout << "\nTrial number #" << i+1 << endl;
424 //we create a random population
425 pop.createRandomPopulation(LB,UB,NP, rng);
426 pop.evaluatePopulation(problem);
427 int iter = 0;
429 time(&start);
430 while( iter < itermax){
431 iter ++;
432 //we print the best
433 cout << "Initial fitness: " << pop.extractBestIndividual().getFitness() << endl;
434 //we evolve it
435 start1=clock();
436 pop = SGA.evolve(pop,problem);
437 end1=clock();
438 dif = (double)(end1-start1) / (double)CLOCKS_PER_SEC;
439 //we print the result
440 cout << "Final fitness: " << pop.extractBestIndividual().getFitness() << endl;
441 cout << "Worst fitness: " << pop.extractWorstIndividual().getFitness() << endl;
442 cout << "Mean : " << pop.evaluateMean() << endl;
443 cout << "Std : " << pop.evaluateStd() << endl;
444 cout << "\t\tSeconds elapsed: " << dif << endl;
446 time(&end);
447 results.push_back(pop.extractBestIndividual().getFitness());
448 dif = difftime(end,start);
449 cout << "\nSeconds elapsed: " << dif << endl<<endl;
452 //evaluate experiment results
453 for (int i=0;i<trials;i++){
454 mean += results[i];
455 if (results[i] > max) max = results[i];
456 if (results[i] < min) min = results[i];
458 mean /= trials;
460 for (int i=0;i<trials;i++){
461 dev += (mean-results[i])*(mean-results[i]);
463 dev = sqrt(dev/trials);
465 for (int i=0;i<trials;i++){
466 cout << "\nTrial #" << i << ": " << results[i] << endl;
470 //print results
471 cout << "\nMean: " << mean << endl;
472 cout << "Std: " << dev << endl;
473 cout << "Max: " << max << endl;
474 cout << "Min: " << min << endl;
476 //Lines to test SGA
477 break;
479 case 6: //Parallel asynchronous island model
482 //Experiment Settings
483 int NP = 1; //population size for each island
484 int trials = 20; //number of trials
485 int gen = 500; //generations per algorithm call
486 double F = 0.8; //F in DE
487 double CR = 0.8; //CR in DE
488 int strategy = 2; //DE startegy
489 int islandsN = 1; //Number of Islands
491 //stopping criteria
492 int itermax = 120; //Maximum number of iterations allowed (i.e. output printed on the screen)
494 //Experiment Outputs
495 double mean = 0, dev= 0, max = 0, min = 200000000;
496 vector <double> results;
498 //Main cycle creating threads
499 for (int i=0;i<trials;i++){
500 cout << "\nTrial number #" << i+1 << endl;
501 //We create a random population in each island (this is done by the main thread - i.e. no parallelization here)
502 vector<Population> IslandPop(islandsN);
503 vector<GOProblem*> parallelProblems(islandsN);
504 for (int i=0;i<islandsN;i++){
505 parallelProblems[i] = new tandemProb();
507 IslandPop[i].createRandomPopulation(LB,UB,NP, rng);
508 IslandPop[i].evaluatePopulation(*parallelProblems[i]);
511 //We instanciate the objects needed for pthreads allocating memory for the threads array
512 pthread_t *threads;
513 threads = new pthread_t [islandsN];
514 pthread_mutex_t mutex;
515 pthread_cond_t exitcond;
516 pthread_mutex_init(&mutex, NULL);
517 pthread_cond_init (&exitcond, NULL);
519 //We allocate memory for the isActive array containing the status ofeach thread and we initialise it to false (no threads opened)
520 bool *isActive;
521 isActive = new bool[islandsN];
522 for (int i=0;i<islandsN;i++) isActive[i]=false; //all threads are inactive
524 //We allocate memory and initialise the data threadParam array containing the information to be passed to the different threads
525 threadParam* data;
526 data = new threadParam [islandsN];
527 for (int i=0;i<islandsN;i++){
528 data[i].threadID = i;
530 data[i].problem = parallelProblems[i];
531 data[i].Ptr_pop = &IslandPop[i]; //Each Island has a different population
534 data[i].NP = NP;
535 data[i].generations = gen;
537 //Initialise DE specific data
538 data[i].strategy = 1;
539 data[i].F = F;
540 data[i].CR = CR;
542 //Initialise PSO/MPSO specific data
543 data[i].omega = 0.65;
544 data[i].eta1 = 2.0;
545 data[i].eta2 = 2.0;
546 data[i].vcoeff = 1;
547 data[i].nswarms = 4;
549 //Initialise SGA specific data
550 data[i].CRsga = 0.95;
551 data[i].M = 0.2;
552 data[i].insert_best =1;
554 //Initialise ASA specific data
555 data[i].Ts = 1;
556 data[i].Tf = data[i].Ts/1000;
557 data[i].isActive = &isActive[i];
558 data[i].TPmutex = &mutex;
559 data[i].exit = &exitcond;
561 data[i].Ptr_log = &logfile;
564 int iter=0;
565 int rc;
566 int IslandType = 0;
567 double loweststd = 1000000;
569 pthread_mutex_lock (&mutex);
570 time(&start);
571 while(iter < itermax){
572 for (int i=0;i<islandsN;i++){
573 if ( !*(data[i].isActive) ){
574 //Create again the i-th thread to simulate an Island
575 IslandType = 3;
576 if (IslandType == 0){
577 data[i].randomSeed = rng.next();
578 cout << "\t\t\tPSO:\t\t omega: "<< data[i].omega << "\t\teta1: " << data[i].eta1 << "\t\teta2: " << data[i].eta2 << "\t\tVcoeff: " << data[i].vcoeff << "\t\tGenerations: " << data[i].generations << endl;
579 rc = pthread_create(&threads[i], NULL, PSOthread, (void *)&data[i]);
581 else if (IslandType == 1){
582 data[i].randomSeed = rng.next();
583 cout << "\t\t\tMPSO:\t\t omega: "<< data[i].omega << "\t\teta1: " << data[i].eta1 << "\t\teta2: " << data[i].eta2 << "\t\tVcoeff: " << data[i].vcoeff << "\t\tNswamrs: " << data[i].nswarms<< "\t\tGenerations: " << data[i].generations << endl;
584 rc = pthread_create(&threads[i], NULL, MPSOthread, (void *)&data[i]);
586 else if (IslandType == 2){
587 data[i].randomSeed = rng.next();
588 cout << "\t\t\tSGA:\t\t CR: "<< data[i].CRsga << "\t\tM: " << data[i].M << "\t\tInsertBest: " << data[i].insert_best << "\t\tGenerations: " << data[i].generations << endl;
589 rc = pthread_create(&threads[i], NULL, SGAthread, (void *)&data[i]);
591 else if (IslandType == 3){
592 data[i].randomSeed = rng.next();
593 data[i].generations=10000;
594 data[i].NP = 1;
595 cout << "\t\t\tASA:\t\t Ts: "<< data[i].Ts << "\t\tTf: " << data[i].Tf << "\t\tGenerations: " << data[i].generations << endl;
596 rc = pthread_create(&threads[i], NULL, ASAthread, (void *)&data[i]);
598 else {
599 data[i].randomSeed = rng.next();
600 data[i].strategy = strategy;
601 cout << "\t\t\tDE: \t\t F: "<< data[i].F << "\t\tCR: " << data[i].CR << "\t\tStrategy: " << data[i].strategy << "\t\tGenerations: " << data[i].generations << endl;
602 rc = pthread_create(&threads[i], NULL, DEthread, (void *)&data[i]);
604 if (rc){
605 //Problem creating the thread
606 printf("ERROR; return code from pthread_create() is %d\n", rc);
607 exit(-1);
609 else{
610 //Thread Successfully Created
611 iter += 1;
612 *(data[i].isActive) = true;
613 //thread is detached as it will never be joined
614 //(on OSx Leopard this avoids that at a certain point
615 //threads cannot be created anymore resulting in rc=35)
616 pthread_detach(threads[i]);
619 //evaluate highest standard deviation across Islands
620 //loweststd = IslandPop[0].evaluateStd();
621 loweststd = IslandPop[0].extractBestIndividual().getFitness();
622 for (int i2=1;i2<islandsN;i2++){
623 if (loweststd < IslandPop[i2].extractBestIndividual().getFitness()) loweststd = IslandPop[i2].extractBestIndividual().getFitness();
626 //log islands best and std
627 for (int i2=0;i2<islandsN;i2++){
628 cout << "CPU#:" << i2 << ": " << IslandPop[i2].extractBestIndividual().getFitness() << " " << IslandPop[i2].evaluateStd() << endl;
630 cout << "HighestStd: " << loweststd << endl;
631 cout << "Iter: " << iter+1 << endl;
632 cout << "\nmain():" << endl << "\t\t\tcreating thread, ID " << i << endl;
634 //ring topology migration
635 if (Pk::nextDouble(rng) < 0.2){
636 IslandPop[(i+1) % islandsN].substituteIndividual(IslandPop[i].extractBestIndividual(), rng.next() % data[i].NP);
641 pthread_cond_wait(&exitcond, &mutex);
643 pthread_mutex_unlock (&mutex);
644 //The main cycle has finished: we wait for all threads to finish
645 for (int i=0; i<islandsN;i++){
646 while (*data[i].isActive); //infinite loop if a thread never ends
649 //we clean the thread objects and deallocate memory
650 pthread_mutex_destroy(&mutex);
651 pthread_cond_destroy(&exitcond);
652 delete[] data;
653 delete[] threads;
654 delete[] isActive;
655 time(&end);
656 dif = difftime(end,start);
657 cout << "\nSeconds elapsed: " << dif << endl<<endl;
659 double res=IslandPop[0].extractBestIndividual().getFitness();
660 for (int i=1;i<islandsN;i++){
661 if (res > IslandPop[i].extractBestIndividual().getFitness()) res = IslandPop[i].extractBestIndividual().getFitness();
663 //if (iter<itermax){
664 results.push_back(res);
667 for (int i = 0; i < islandsN; i++) {
668 delete parallelProblems[i];
672 //evaluate experiment results
673 for (unsigned int i=0;i<results.size();i++){
674 mean += results[i];
675 if (results[i] > max) max = results[i];
676 if (results[i] < min) min = results[i];
678 mean /= results.size();
680 for (unsigned int i=0;i<results.size();i++){
681 dev += (mean-results[i])*(mean-results[i]);
683 dev = sqrt(dev/results.size());
685 for (unsigned int i=0;i<results.size();i++){
686 cout << "\nTrial #" << i << ": " << results[i] << endl;
689 //print results
690 cout << "\nMean: " << mean << endl;
691 cout << "Std: " << dev << endl;
692 cout << "Max: " << max << endl;
693 cout << "Min: " << min << endl;
694 cout << "Success: " << results.size() << endl;
696 break;
698 case 9:
700 Individual x;
701 x.createRandomIndividual(LB,UB,rng);
702 cout << x << endl;
703 x[0]=666;
704 cout << x << endl;
706 Population pop;
707 pop.createRandomPopulation(LB,UB,5,rng);
708 pop.evaluatePopulation(problem);
709 cout << pop[3] << endl;
710 pop[3][0]=666;
711 cout << pop[3] << endl;
712 cout << pop << endl;
715 break;
717 default:
719 int NUM_THREADS=2;
720 //We create a random population and evaluate its fitness (this is done by the main thread - i.e. no parallelization here)
721 pop.createRandomPopulation(LB,UB,20*5, rng);
722 pop.evaluatePopulation(problem);
724 //We instanciate the objects needed for pthreads allocating memory for the threads array
725 pthread_t *threads;
726 threads = new pthread_t [NUM_THREADS];
727 //pthread_attr_t attr;
728 //pthread_attr_init(&attr);
729 //pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
730 pthread_mutex_t mutex;
731 pthread_cond_t exitcond;
732 pthread_mutex_init(&mutex, NULL);
733 pthread_cond_init (&exitcond, NULL);
738 //We allocate memory for the isActive array containing the status ofeach thread and we initialise it to false (no threads opened)
739 bool *isActive;
740 isActive = new bool[NUM_THREADS]; //all threads are inactive
741 for (int i=0;i<NUM_THREADS;i++) {isActive[i]=false;}
743 //We allocate memory and initialise the data threadParam array containing the information to be passed to the different threads
744 threadParam *data;
745 data = new threadParam [NUM_THREADS];
746 for (int i=0;i<NUM_THREADS;i++){
747 data[i].threadID = i;
749 data[i].problem = &problem;
750 data[i].Ptr_pop = &pop;
752 data[i].generations = 500;
754 //Initialise DE specific data
755 data[i].strategy = 2;
756 data[i].F = 0.8;
757 data[i].CR = 0.8;
759 //Initialise PSO specific data
760 data[i].omega = 0.5;
761 data[i].eta1 = 2.0;
762 data[i].eta2 = 2.0;
763 data[i].vcoeff = 1000;
765 data[i].isActive = &isActive[i];
766 data[i].TPmutex = &mutex;
767 data[i].exit = &exitcond;
769 data[i].Ptr_log = &logfile;
772 //Main cycle creating threads
773 int globalCount=0;
774 int count1=0,count2=0;
775 int rc;
776 int algorithmchoice = 0;
778 pthread_mutex_lock (&mutex);
779 time(&start);
780 while (globalCount<120){
781 //while(pop.extractBestIndividual().getFitness()!=0){
782 for (int i=0;i<NUM_THREADS;i++){
783 if ( !*(data[i].isActive) ){
784 cout << "main():" << endl << "\t\t\tcreating thread, ID " << i << endl;
785 algorithmchoice = 4;//r250()%10;
786 if (algorithmchoice == 0){
787 count1++;
788 cout << "\t\t\tPSO:\t\t omega: "<< data[i].omega << "\t\teta1: " << data[i].eta1 << "\t\teta2: " << data[i].eta2 << "\t\tVcoeff: " << data[i].vcoeff << "\t\tGenerations: " << data[i].generations << endl;
789 rc = pthread_create(&threads[i], NULL, PSOthread, (void *)&data[i]);
791 else {
792 data[i].strategy = i+1;
793 cout << "\t\t\tDE: \t\t F: "<< data[i].F << "\t\tCR: " << data[i].CR << "\t\tStrategy: " << data[i].strategy << "\t\tGenerations: " << data[i].generations << endl;
794 rc = pthread_create(&threads[i], NULL, DEthread, (void *)&data[i]);
795 count2++;
798 if (rc){
799 printf("ERROR; return code from pthread_create() is %d\n", rc);
800 exit(-1);
802 else{
803 globalCount += 1;
804 *(data[i].isActive) = true;
808 pthread_cond_wait(&exitcond, &mutex);
810 pthread_mutex_unlock (&mutex);
812 //The main cycle has finished: we wait for all threads to finish
813 for (int i=0; i<NUM_THREADS;i++){
814 pthread_join(threads[i],NULL);
817 //we clean the thread objects and deallocate memory
818 pthread_mutex_destroy(&mutex);
819 //pthread_attr_destroy(&attr);
820 pthread_cond_destroy(&exitcond);
821 delete[] data;
822 delete[] threads;
823 delete[] isActive;
824 time(&end);
825 dif = difftime(end,start);
826 cout << "\nSeconds elapsed: " << dif << endl<<endl;
827 cout << "\nCount1: " << count1 << endl;
828 cout << "\nCount2: " << count2 << endl;
831 break;
832 }//end case
834 } //end while
837 //The following lines are commented out as they implement exactly the DiGMO random strategy in a random
838 //way. This creates a very unefficient cooperation between the algorithms as it does not have the implicit
839 //learning of the best strategy. This is the mechanism that allow, in the distributed version of the algorithm,
840 //the same individual to be evolved by different algorithms and only the most succesful one to be selected
842 //It seems that the reinsertion strategy (only improved individuals substitute their old versions) together with
843 //the contemporary evolution of the same individuals is key to the efficiency of algorithm cooperation (mimicking co-evolution)
844 //In a sequential version this can be enforced by evolving with DE, PSO and SA and only at the end perform reinsertion
845 //as in the uncommented lines above
847 /*algorithmchoice = r250()%3;
848 if ( algorithmchoice == 0 ){
849 deme=pop.extractRandomDeme(20,picks);
850 //we print the best
851 cout << "Using DE" << endl;
852 cout << "Initial fitness: " << deme.extractBestIndividual().getFitness() << endl;
853 //DE.initDE(50,LB.size(),dr250(),dr250(),(int)dr250()*11+1);
854 deme = DE.evolve(deme,&rosenbrock,LB,UB);
857 else if ( algorithmchoice == 1 ){
858 deme=pop.extractRandomDeme(20,picks);
859 //deme.resetVelocities(LB,UB);
860 //we print the best
861 cout << "Using PSO" << endl;
862 cout << "Initial fitness: " << deme.extractBestIndividual().getFitness() << endl;
863 //PSO.initPSO(500,LB.size(),(dr250()+1)/2,4.0*dr250(),4.0*dr250(),(int)dr250()*10000);
864 deme = PSO.evolve(deme,&rosenbrock,LB,UB);
867 else if ( algorithmchoice == 2 ){
868 deme=pop.extractRandomDeme(1,picks);
869 //deme.resetVelocities(LB,UB);
870 //we print the best
871 cout << "Using ASA" << endl;
872 cout << "Initial fitness: " << deme.extractBestIndividual().getFitness() << endl;
873 //ASA.initASA(10000,1,8,LB.size(),dr250(),dr250(),1.0);
874 deme = ASA.evolve(deme[0],&rosenbrock,LB,UB);
877 //we print the result
878 cout << "Final fitness: " << deme.extractBestIndividual().getFitness() << endl;
879 //we insert it in the main population
880 pop.insertDeme(deme,picks);
881 picks.clear();*/
884 cout << "\nBest fitness found: " << pop.extractBestIndividual().getFitness() << endl;
886 return 0;