More header fixage, 'using' statement removal.
[PaGMO.git] / main.cpp
blob71c07fbd22ef54f21511f6c008482f476fec5cf3
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 tandemProb 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 = 100; //number of trials
64 int niterTot = 10000; //generations per algorithm call
65 int niterRange = 20;
66 int niterTemp = 1;
67 double T0 = 1;
68 double Tcoeff = 0.77;
69 double StartStep =1;
71 //stopping criteria
72 int itermax = 120; //Maximum number of iterations allowed (i.e. output printed on the screen)
74 //Experiment Outputs
75 double mean = 0, dev= 0, max = 0, min = 200000000;
76 vector <double> results;
78 //Instanciate the algorithm
79 //Adaptive Simulated Annealing
80 ASAalgorithm ASA;
81 ASA.initASA(niterTot,niterTemp,niterRange,LB.size(),T0,Tcoeff,StartStep, rng.next());
83 //Pruned bounds
85 for (int i=0;i<trials;i++){
86 cout << "\nTrial number #" << i+1 << endl;
87 //we create a random population
88 pop.createRandomPopulation(LB,UB,NP, rng);
89 pop.evaluatePopulation(problem);
90 int iter = 0;
92 time(&start);
93 while( iter < itermax){
94 iter ++;
95 //we print the best
96 cout << "Initial fitness: " << pop.extractBestIndividual().getFitness() << endl;
97 //we evolve it
98 start1=clock();
99 pop = ASA.evolve(pop[0],problem);
100 end1=clock();
101 dif = (double)(end1-start1) / (double)CLOCKS_PER_SEC;
102 //we print the result
103 cout << "Final fitness: " << pop.extractBestIndividual().getFitness() << endl;
104 cout << "Worst fitness: " << pop.extractWorstIndividual().getFitness() << endl;
105 cout << "Mean : " << pop.evaluateMean() << endl;
106 cout << "Std : " << pop.evaluateStd() << endl;
107 cout << "\t\tSeconds elapsed: " << dif << endl;
109 time(&end);
110 results.push_back(pop.extractBestIndividual().getFitness());
111 dif = difftime(end,start);
112 cout << "\nSeconds elapsed: " << dif << endl<<endl;
113 for (int i=0;i<D;i++){
114 logfile << pop.extractBestIndividual()[i] << " ";
116 logfile << exp(-pop.extractBestIndividual().getFitness()) <<endl;
119 //evaluate experiment results
120 for (int i=0;i<trials;i++){
121 mean += results[i];
122 if (results[i] > max) max = results[i];
123 if (results[i] < min) min = results[i];
125 mean /= trials;
127 for (int i=0;i<trials;i++){
128 dev += (mean-results[i])*(mean-results[i]);
130 dev = sqrt(dev/trials);
132 for (int i=0;i<trials;i++){
133 cout << "\nTrial #" << i << ": " << results[i] << endl;
137 //print results
138 cout << "\nMean: " << mean << endl;
139 cout << "Std: " << dev << endl;
140 cout << "Max: " << max << endl;
141 cout << "Min: " << min << endl;
143 //Lines to test ASA
144 break;
146 case 2: //PSO sequential experiment
148 //Experiment Settings
149 int NP = 20; //population size
150 int trials = 100; //number of trials
151 int gen = 500; //generations per algorithm call
152 double omega = 0.6;
153 double eta1 = 2;
154 double eta2 = 2;
155 int vcoeff = 1;
157 //stopping criteria
158 int itermax = 120; //Maximum number of iterations allowed (i.e. output printed on the screen)
159 double stdmin = 1e-5; //Standard deviation of the population that determines a stop
161 //Experiment Outputs
162 double mean = 0, dev= 0, max = 0, min = 200000000;
163 vector <double> results;
165 //Instanciate the algorithm
166 PSOalgorithm PSO;
167 PSO.initPSO(gen,LB.size(),omega,eta1,eta2,vcoeff, rng.next());
169 for (int i=0;i<trials;i++){
170 cout << "\nTrial number #" << i+1 << endl;
171 //we create a random population
172 pop.createRandomPopulation(LB,UB,NP, rng);
173 pop.evaluatePopulation(problem);
174 int iter = 0;
176 time(&start);
177 while(iter < itermax){
178 iter ++;
179 //we print the best
180 cout << "Initial fitness: " << pop.extractBestIndividual().getFitness() << endl;
181 //we evolve it
182 start1=clock();
183 pop = PSO.evolve(pop,problem);
184 end1=clock();
185 dif = (double)(end1-start1) / (double)CLOCKS_PER_SEC;
186 //we print the result
187 cout << "Final fitness: " << pop.extractBestIndividual().getFitness() << endl;
188 cout << "Worst fitness: " << pop.extractWorstIndividual().getFitness() << endl;
189 cout << "Mean : " << pop.evaluateMean() << endl;
190 cout << "Std : " << pop.evaluateStd() << endl;
191 cout << "\t\tSeconds elapsed: " << dif << endl;
193 time(&end);
194 results.push_back(pop.extractBestIndividual().getFitness());
195 dif = difftime(end,start);
196 cout << "\nSeconds elapsed: " << dif << endl<<endl;
199 //evaluate experiment results
200 for (int i=0;i<trials;i++){
201 mean += results[i];
202 if (results[i] > max) max = results[i];
203 if (results[i] < min) min = results[i];
205 mean /= trials;
207 for (int i=0;i<trials;i++){
208 dev += (mean-results[i])*(mean-results[i]);
210 dev = sqrt(dev/trials);
212 for (int i=0;i<trials;i++){
213 cout << "\nTrial #" << i << ": " << results[i] << endl;
217 //print results
218 cout << "\nMean: " << mean << endl;
219 cout << "Std: " << dev << endl;
220 cout << "Max: " << max << endl;
221 cout << "Min: " << min << endl;
223 break;
225 case 3: //MPSO sequential experiment
227 //Experiment Settings
228 int NP = 20; //population size
229 int trials = 100; //number of trials
230 int gen = 500; //generations per algorithm call
231 double omega = 0.65;
232 double eta1 = 2.0;
233 double eta2 = 2.0;
234 int vcoeff = 1;
235 int nswarms = 4;
237 //stopping criteria
238 int itermax = 100; //Maximum number of iterations allowed (i.e. output printed on the screen)
239 double stdmin = 1e-5; //Standard deviation of the population that determines a stop
241 //Experiment Outputs
242 double mean = 0, dev= 0, max = 0, min = 200000000;
243 vector <double> results;
245 //Instanciate the algorithm
246 MPSOalgorithm MPSO;
247 MPSO.initMPSO(gen,LB.size(),omega,eta1,eta2,vcoeff,nswarms, rng.next());
249 for (int i=0;i<trials;i++){
250 cout << "\nTrial number #" << i+1 << endl;
251 //we create a random population
252 pop.createRandomPopulation(LB,UB,NP, rng);
253 pop.evaluatePopulation(problem);
254 int iter = 0;
256 time(&start);
257 while(iter < itermax){
258 iter ++;
259 //we print the best
260 cout << "Initial fitness: " << pop.extractBestIndividual().getFitness() << endl;
261 //we evolve it
262 start1=clock();
263 pop = MPSO.evolve(pop,problem);
264 end1=clock();
265 dif = (double)(end1-start1) / (double)CLOCKS_PER_SEC;
266 //we print the result
267 cout << "Final fitness: " << pop.extractBestIndividual().getFitness() << endl;
268 cout << "Worst fitness: " << pop.extractWorstIndividual().getFitness() << endl;
269 cout << "Mean : " << pop.evaluateMean() << endl;
270 cout << "Std : " << pop.evaluateStd() << endl;
271 cout << "\t\tSeconds elapsed: " << dif << endl;
273 time(&end);
274 results.push_back(pop.extractBestIndividual().getFitness());
275 dif = difftime(end,start);
276 cout << "\nSeconds elapsed: " << dif << endl<<endl;
279 //evaluate experiment results
280 for (int i=0;i<trials;i++){
281 mean += results[i];
282 if (results[i] > max) max = results[i];
283 if (results[i] < min) min = results[i];
285 mean /= trials;
287 for (int i=0;i<trials;i++){
288 dev += (mean-results[i])*(mean-results[i]);
290 dev = sqrt(dev/trials);
292 for (int i=0;i<trials;i++){
293 cout << "\nTrial #" << i << ": " << results[i] << endl;
297 //print results
298 cout << "\nMean: " << mean << endl;
299 cout << "Std: " << dev << endl;
300 cout << "Max: " << max << endl;
301 cout << "Min: " << min << endl;
303 break;
307 case 4: //Sequential Differential Evolution Experiment
309 //Experiment Settings
310 int NP = 20; //population size for each island
311 int trials = 100; //number of trials
312 int gen = 500; //generations per algorithm call
313 double F = 0.8; //F in DE
314 double CR = 0.8; //CR in DE
315 int strategy = 2; //DE startegy
317 //stopping criteria
318 int itermax = 120; //Maximum number of iterations allowed (i.e. output printed on the screen)
320 //Experiment Outputs
321 double mean = 0, dev= 0, max = 0, min = 200000000;
322 vector <double> results;
324 //Instanciate the algorithm
325 DEalgorithm DE;
326 DE.initDE(gen,LB.size(),F,CR,strategy, rng.next());
328 for (int i=0;i<trials;i++){
329 cout << "\nTrial number #" << i+1 << endl;
330 //we create a random population
333 pop.createRandomPopulation(LB,UB,NP, rng);
334 pop.evaluatePopulation(problem);
335 int iter = 0;
337 time(&start);
338 while( iter < itermax){
339 iter ++;
340 //we print the best
341 cout << "Initial fitness: " << pop.extractBestIndividual().getFitness() << endl;
342 //we evolve it
343 start1=clock();
344 pop = DE.evolve(pop,problem);
345 end1=clock();
346 dif = (double)(end1-start1) / (double)CLOCKS_PER_SEC;
347 //we print the result
348 cout << "Final fitness: " << pop.extractBestIndividual().getFitness() << endl;
349 cout << "Worst fitness: " << pop.extractWorstIndividual().getFitness() << endl;
350 cout << "Mean : " << pop.evaluateMean() << endl;
351 cout << "Std : " << pop.evaluateStd() << endl;
352 cout << "\t\tSeconds elapsed: " << dif << endl;
354 time(&end);
355 //if (iter<itermax){
356 //results.push_back(iter*NP*gen);
357 results.push_back(pop.extractBestIndividual().getFitness());
359 dif = difftime(end,start);
360 cout << "\nSeconds elapsed: " << dif << endl<<endl;
361 for (int i=0;i<D;i++){
362 logfile << pop.extractBestIndividual()[i] << " ";
364 logfile << exp(-pop.extractBestIndividual().getFitness()) <<endl;
367 //evaluate experiment results
368 for (unsigned int i=0;i<results.size();i++){
369 mean += results[i];
370 if (results[i] > max) max = results[i];
371 if (results[i] < min) min = results[i];
373 mean /= results.size();
375 for (unsigned int i=0;i<results.size();i++){
376 dev += (mean-results[i])*(mean-results[i]);
378 dev = sqrt(dev/results.size());
380 for (unsigned int i=0;i<results.size();i++){
381 cout << "\nTrial #" << i << ": " << results[i] << endl;
384 //print results
385 cout << "\nMean: " << mean << endl;
386 cout << "Std: " << dev << endl;
387 cout << "Max: " << max << endl;
388 cout << "Min: " << min << endl;
389 cout << "Success: " << results.size() << endl;
391 break;
395 case 5: //SGA experiment
397 //Experiment Settings
398 int NP = 20; //population size
399 int trials = 100; //number of trials
400 int gen = 500; //generations per algorithm call
401 double CR = 0.7;
402 double M = 0.2;
403 int insert_best = 1;
405 //stopping criteria
406 int itermax = 120; //Maximum number of iterations allowed (i.e. output printed on the screen)
408 //Experiment Outputs
409 double mean = 0, dev= 0, max = 0, min = 200000000;
410 vector <double> results;
412 //Instanciate the algorithm
413 //Simple Genetic Algorithm
414 SGAalgorithm SGA;
415 SGA.initSGA(gen,LB.size(),CR,M,insert_best, rng.next());
417 for (int i=0;i<trials;i++){
418 cout << "\nTrial number #" << i+1 << endl;
419 //we create a random population
420 pop.createRandomPopulation(LB,UB,NP, rng);
421 pop.evaluatePopulation(problem);
422 int iter = 0;
424 time(&start);
425 while( iter < itermax){
426 iter ++;
427 //we print the best
428 cout << "Initial fitness: " << pop.extractBestIndividual().getFitness() << endl;
429 //we evolve it
430 start1=clock();
431 pop = SGA.evolve(pop,problem);
432 end1=clock();
433 dif = (double)(end1-start1) / (double)CLOCKS_PER_SEC;
434 //we print the result
435 cout << "Final fitness: " << pop.extractBestIndividual().getFitness() << endl;
436 cout << "Worst fitness: " << pop.extractWorstIndividual().getFitness() << endl;
437 cout << "Mean : " << pop.evaluateMean() << endl;
438 cout << "Std : " << pop.evaluateStd() << endl;
439 cout << "\t\tSeconds elapsed: " << dif << endl;
441 time(&end);
442 results.push_back(pop.extractBestIndividual().getFitness());
443 dif = difftime(end,start);
444 cout << "\nSeconds elapsed: " << dif << endl<<endl;
447 //evaluate experiment results
448 for (int i=0;i<trials;i++){
449 mean += results[i];
450 if (results[i] > max) max = results[i];
451 if (results[i] < min) min = results[i];
453 mean /= trials;
455 for (int i=0;i<trials;i++){
456 dev += (mean-results[i])*(mean-results[i]);
458 dev = sqrt(dev/trials);
460 for (int i=0;i<trials;i++){
461 cout << "\nTrial #" << i << ": " << results[i] << endl;
465 //print results
466 cout << "\nMean: " << mean << endl;
467 cout << "Std: " << dev << endl;
468 cout << "Max: " << max << endl;
469 cout << "Min: " << min << endl;
471 //Lines to test SGA
472 break;
474 case 6: //Parallel asynchronous island model
477 //Experiment Settings
478 int NP = 1; //population size for each island
479 int trials = 20; //number of trials
480 int gen = 500; //generations per algorithm call
481 double F = 0.8; //F in DE
482 double CR = 0.8; //CR in DE
483 int strategy = 2; //DE startegy
484 int islandsN = 5; //Number of Islands
486 //stopping criteria
487 int itermax = 120; //Maximum number of iterations allowed (i.e. output printed on the screen)
489 //Experiment Outputs
490 double mean = 0, dev= 0, max = 0, min = 200000000;
491 vector <double> results;
493 //Main cycle creating threads
494 for (int i=0;i<trials;i++){
495 cout << "\nTrial number #" << i+1 << endl;
496 //We create a random population in each island (this is done by the main thread - i.e. no parallelization here)
497 vector<Population> IslandPop(islandsN);
498 vector<GOProblem*> parallelProblems(islandsN);
499 for (int i=0;i<islandsN;i++){
500 parallelProblems[i] = new tandemProb();
502 IslandPop[i].createRandomPopulation(LB,UB,NP, rng);
503 IslandPop[i].evaluatePopulation(*parallelProblems[i]);
506 //We instanciate the objects needed for pthreads allocating memory for the threads array
507 pthread_t *threads;
508 threads = new pthread_t [islandsN];
509 pthread_mutex_t mutex;
510 pthread_cond_t exitcond;
511 pthread_mutex_init(&mutex, NULL);
512 pthread_cond_init (&exitcond, NULL);
514 //We allocate memory for the isActive array containing the status ofeach thread and we initialise it to false (no threads opened)
515 bool *isActive;
516 isActive = new bool[islandsN];
517 for (int i=0;i<islandsN;i++) isActive[i]=false; //all threads are inactive
519 //We allocate memory and initialise the data threadParam array containing the information to be passed to the different threads
520 threadParam* data;
521 data = new threadParam [islandsN];
522 for (int i=0;i<islandsN;i++){
523 data[i].threadID = i;
525 data[i].problem = parallelProblems[i];
526 data[i].Ptr_pop = &IslandPop[i]; //Each Island has a different population
529 data[i].NP = NP;
530 data[i].generations = gen;
532 //Initialise DE specific data
533 data[i].strategy = 1;
534 data[i].F = F;
535 data[i].CR = CR;
537 //Initialise PSO/MPSO specific data
538 data[i].omega = 0.65;
539 data[i].eta1 = 2.0;
540 data[i].eta2 = 2.0;
541 data[i].vcoeff = 1;
542 data[i].nswarms = 4;
544 //Initialise SGA specific data
545 data[i].CRsga = 0.95;
546 data[i].M = 0.2;
547 data[i].insert_best =1;
549 //Initialise ASA specific data
550 data[i].Ts = 1;
551 data[i].Tf = data[i].Ts/1000;
552 data[i].isActive = &isActive[i];
553 data[i].TPmutex = &mutex;
554 data[i].exit = &exitcond;
556 data[i].Ptr_log = &logfile;
559 int iter=0;
560 int rc;
561 int IslandType = 0;
562 double loweststd = 1000000;
564 pthread_mutex_lock (&mutex);
565 time(&start);
566 while(iter < itermax){
567 for (int i=0;i<islandsN;i++){
568 if ( !*(data[i].isActive) ){
569 //Create again the i-th thread to simulate an Island
570 IslandType = 3;
571 if (IslandType == 0){
572 data[i].randomSeed = rng.next();
573 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;
574 rc = pthread_create(&threads[i], NULL, PSOthread, (void *)&data[i]);
576 else if (IslandType == 1){
577 data[i].randomSeed = rng.next();
578 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;
579 rc = pthread_create(&threads[i], NULL, MPSOthread, (void *)&data[i]);
581 else if (IslandType == 2){
582 data[i].randomSeed = rng.next();
583 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;
584 rc = pthread_create(&threads[i], NULL, SGAthread, (void *)&data[i]);
586 else if (IslandType == 3){
587 data[i].randomSeed = rng.next();
588 data[i].generations=10000;
589 data[i].NP = 1;
590 cout << "\t\t\tASA:\t\t Ts: "<< data[i].Ts << "\t\tTf: " << data[i].Tf << "\t\tGenerations: " << data[i].generations << endl;
591 rc = pthread_create(&threads[i], NULL, ASAthread, (void *)&data[i]);
593 else {
594 data[i].randomSeed = rng.next();
595 data[i].strategy = strategy;
596 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;
597 rc = pthread_create(&threads[i], NULL, DEthread, (void *)&data[i]);
599 if (rc){
600 //Problem creating the thread
601 printf("ERROR; return code from pthread_create() is %d\n", rc);
602 exit(-1);
604 else{
605 //Thread Successfully Created
606 iter += 1;
607 *(data[i].isActive) = true;
608 //thread is detached as it will never be joined
609 //(on OSx Leopard this avoids that at a certain point
610 //threads cannot be created anymore resulting in rc=35)
611 pthread_detach(threads[i]);
614 //evaluate highest standard deviation across Islands
615 //loweststd = IslandPop[0].evaluateStd();
616 loweststd = IslandPop[0].extractBestIndividual().getFitness();
617 for (int i2=1;i2<islandsN;i2++){
618 if (loweststd < IslandPop[i2].extractBestIndividual().getFitness()) loweststd = IslandPop[i2].extractBestIndividual().getFitness();
621 //log islands best and std
622 for (int i2=0;i2<islandsN;i2++){
623 cout << "CPU#:" << i2 << ": " << IslandPop[i2].extractBestIndividual().getFitness() << " " << IslandPop[i2].evaluateStd() << endl;
625 cout << "HighestStd: " << loweststd << endl;
626 cout << "Iter: " << iter+1 << endl;
627 cout << "\nmain():" << endl << "\t\t\tcreating thread, ID " << i << endl;
629 //ring topology migration
630 if (Pk::nextDouble(rng) < 0.2){
631 IslandPop[(i+1) % islandsN].substituteIndividual(IslandPop[i].extractBestIndividual(), rng.next() % data[i].NP);
636 pthread_cond_wait(&exitcond, &mutex);
638 pthread_mutex_unlock (&mutex);
639 //The main cycle has finished: we wait for all threads to finish
640 for (int i=0; i<islandsN;i++){
641 while (*data[i].isActive); //infinite loop if a thread never ends
644 //we clean the thread objects and deallocate memory
645 pthread_mutex_destroy(&mutex);
646 pthread_cond_destroy(&exitcond);
647 delete[] data;
648 delete[] threads;
649 delete[] isActive;
650 time(&end);
651 dif = difftime(end,start);
652 cout << "\nSeconds elapsed: " << dif << endl<<endl;
654 double res=IslandPop[0].extractBestIndividual().getFitness();
655 for (int i=1;i<islandsN;i++){
656 if (res > IslandPop[i].extractBestIndividual().getFitness()) res = IslandPop[i].extractBestIndividual().getFitness();
658 //if (iter<itermax){
659 results.push_back(res);
662 for (int i = 0; i < islandsN; i++) {
663 delete parallelProblems[i];
667 //evaluate experiment results
668 for (unsigned int i=0;i<results.size();i++){
669 mean += results[i];
670 if (results[i] > max) max = results[i];
671 if (results[i] < min) min = results[i];
673 mean /= results.size();
675 for (unsigned int i=0;i<results.size();i++){
676 dev += (mean-results[i])*(mean-results[i]);
678 dev = sqrt(dev/results.size());
680 for (unsigned int i=0;i<results.size();i++){
681 cout << "\nTrial #" << i << ": " << results[i] << endl;
684 //print results
685 cout << "\nMean: " << mean << endl;
686 cout << "Std: " << dev << endl;
687 cout << "Max: " << max << endl;
688 cout << "Min: " << min << endl;
689 cout << "Success: " << results.size() << endl;
691 break;
693 case 9:
695 Individual x;
696 x.createRandomIndividual(LB,UB,rng);
697 cout << x << endl;
698 x[0]=666;
699 cout << x << endl;
701 Population pop;
702 pop.createRandomPopulation(LB,UB,5,rng);
703 pop.evaluatePopulation(problem);
704 cout << pop[3] << endl;
705 pop[3][0]=666;
706 cout << pop[3] << endl;
707 cout << pop << endl;
710 break;
712 default:
714 int NUM_THREADS=2;
715 //We create a random population and evaluate its fitness (this is done by the main thread - i.e. no parallelization here)
716 pop.createRandomPopulation(LB,UB,20*5, rng);
717 pop.evaluatePopulation(problem);
719 //We instanciate the objects needed for pthreads allocating memory for the threads array
720 pthread_t *threads;
721 threads = new pthread_t [NUM_THREADS];
722 //pthread_attr_t attr;
723 //pthread_attr_init(&attr);
724 //pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
725 pthread_mutex_t mutex;
726 pthread_cond_t exitcond;
727 pthread_mutex_init(&mutex, NULL);
728 pthread_cond_init (&exitcond, NULL);
733 //We allocate memory for the isActive array containing the status ofeach thread and we initialise it to false (no threads opened)
734 bool *isActive;
735 isActive = new bool[NUM_THREADS]; //all threads are inactive
736 for (int i=0;i<NUM_THREADS;i++) {isActive[i]=false;}
738 //We allocate memory and initialise the data threadParam array containing the information to be passed to the different threads
739 threadParam *data;
740 data = new threadParam [NUM_THREADS];
741 for (int i=0;i<NUM_THREADS;i++){
742 data[i].threadID = i;
744 data[i].problem = &problem;
745 data[i].Ptr_pop = &pop;
747 data[i].generations = 500;
749 //Initialise DE specific data
750 data[i].strategy = 2;
751 data[i].F = 0.8;
752 data[i].CR = 0.8;
754 //Initialise PSO specific data
755 data[i].omega = 0.5;
756 data[i].eta1 = 2.0;
757 data[i].eta2 = 2.0;
758 data[i].vcoeff = 1000;
760 data[i].isActive = &isActive[i];
761 data[i].TPmutex = &mutex;
762 data[i].exit = &exitcond;
764 data[i].Ptr_log = &logfile;
767 //Main cycle creating threads
768 int globalCount=0;
769 int count1=0,count2=0;
770 int rc;
771 int algorithmchoice = 0;
773 pthread_mutex_lock (&mutex);
774 time(&start);
775 while (globalCount<120){
776 //while(pop.extractBestIndividual().getFitness()!=0){
777 for (int i=0;i<NUM_THREADS;i++){
778 if ( !*(data[i].isActive) ){
779 cout << "main():" << endl << "\t\t\tcreating thread, ID " << i << endl;
780 algorithmchoice = 4;//r250()%10;
781 if (algorithmchoice == 0){
782 count1++;
783 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;
784 rc = pthread_create(&threads[i], NULL, PSOthread, (void *)&data[i]);
786 else {
787 data[i].strategy = i+1;
788 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;
789 rc = pthread_create(&threads[i], NULL, DEthread, (void *)&data[i]);
790 count2++;
793 if (rc){
794 printf("ERROR; return code from pthread_create() is %d\n", rc);
795 exit(-1);
797 else{
798 globalCount += 1;
799 *(data[i].isActive) = true;
803 pthread_cond_wait(&exitcond, &mutex);
805 pthread_mutex_unlock (&mutex);
807 //The main cycle has finished: we wait for all threads to finish
808 for (int i=0; i<NUM_THREADS;i++){
809 pthread_join(threads[i],NULL);
812 //we clean the thread objects and deallocate memory
813 pthread_mutex_destroy(&mutex);
814 //pthread_attr_destroy(&attr);
815 pthread_cond_destroy(&exitcond);
816 delete[] data;
817 delete[] threads;
818 delete[] isActive;
819 time(&end);
820 dif = difftime(end,start);
821 cout << "\nSeconds elapsed: " << dif << endl<<endl;
822 cout << "\nCount1: " << count1 << endl;
823 cout << "\nCount2: " << count2 << endl;
826 break;
827 }//end case
829 } //end while
832 //The following lines are commented out as they implement exactly the DiGMO random strategy in a random
833 //way. This creates a very unefficient cooperation between the algorithms as it does not have the implicit
834 //learning of the best strategy. This is the mechanism that allow, in the distributed version of the algorithm,
835 //the same individual to be evolved by different algorithms and only the most succesful one to be selected
837 //It seems that the reinsertion strategy (only improved individuals substitute their old versions) together with
838 //the contemporary evolution of the same individuals is key to the efficiency of algorithm cooperation (mimicking co-evolution)
839 //In a sequential version this can be enforced by evolving with DE, PSO and SA and only at the end perform reinsertion
840 //as in the uncommented lines above
842 /*algorithmchoice = r250()%3;
843 if ( algorithmchoice == 0 ){
844 deme=pop.extractRandomDeme(20,picks);
845 //we print the best
846 cout << "Using DE" << endl;
847 cout << "Initial fitness: " << deme.extractBestIndividual().getFitness() << endl;
848 //DE.initDE(50,LB.size(),dr250(),dr250(),(int)dr250()*11+1);
849 deme = DE.evolve(deme,&rosenbrock,LB,UB);
852 else if ( algorithmchoice == 1 ){
853 deme=pop.extractRandomDeme(20,picks);
854 //deme.resetVelocities(LB,UB);
855 //we print the best
856 cout << "Using PSO" << endl;
857 cout << "Initial fitness: " << deme.extractBestIndividual().getFitness() << endl;
858 //PSO.initPSO(500,LB.size(),(dr250()+1)/2,4.0*dr250(),4.0*dr250(),(int)dr250()*10000);
859 deme = PSO.evolve(deme,&rosenbrock,LB,UB);
862 else if ( algorithmchoice == 2 ){
863 deme=pop.extractRandomDeme(1,picks);
864 //deme.resetVelocities(LB,UB);
865 //we print the best
866 cout << "Using ASA" << endl;
867 cout << "Initial fitness: " << deme.extractBestIndividual().getFitness() << endl;
868 //ASA.initASA(10000,1,8,LB.size(),dr250(),dr250(),1.0);
869 deme = ASA.evolve(deme[0],&rosenbrock,LB,UB);
872 //we print the result
873 cout << "Final fitness: " << deme.extractBestIndividual().getFitness() << endl;
874 //we insert it in the main population
875 pop.insertDeme(deme,picks);
876 picks.clear();*/
879 cout << "\nBest fitness found: " << pop.extractBestIndividual().getFitness() << endl;
881 return 0;