Update from Dario, SVN rev. 115.
[PaGMO.git] / main.cpp
blob441b2533425cbe7574913e405448c6862974d8e3
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 = 5;
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 pop = ASA.evolve(pop[0],problem);
102 end1=clock();
103 dif = (double)(end1-start1) / (double)CLOCKS_PER_SEC;
104 //we print the result
105 cout << "Final fitness: " << pop.extractBestIndividual().getFitness() << endl;
106 cout << "Worst fitness: " << pop.extractWorstIndividual().getFitness() << endl;
107 cout << "Mean : " << pop.evaluateMean() << endl;
108 cout << "Std : " << pop.evaluateStd() << endl;
109 cout << "\t\tSeconds elapsed: " << dif << endl;
111 time(&end);
112 results.push_back(pop.extractBestIndividual().getFitness());
113 dif = difftime(end,start);
114 cout << "\nSeconds elapsed: " << dif << endl<<endl;
115 for (int i=0;i<D;i++){
116 logfile << pop.extractBestIndividual()[i] << " ";
118 logfile << exp(-pop.extractBestIndividual().getFitness()) <<endl;
121 //evaluate experiment results
122 for (int i=0;i<trials;i++){
123 mean += results[i];
124 if (results[i] > max) max = results[i];
125 if (results[i] < min) min = results[i];
127 mean /= trials;
129 for (int i=0;i<trials;i++){
130 dev += (mean-results[i])*(mean-results[i]);
132 dev = sqrt(dev/trials);
134 for (int i=0;i<trials;i++){
135 cout << "\nTrial #" << i << ": " << results[i] << endl;
139 //print results
140 cout << "\nMean: " << mean << endl;
141 cout << "Std: " << dev << endl;
142 cout << "Max: " << max << endl;
143 cout << "Min: " << min << endl;
145 //Lines to test ASA
146 break;
148 case 2: //PSO sequential experiment
150 //Experiment Settings
151 int NP = 20; //population size
152 int trials = 100; //number of trials
153 int gen = 500; //generations per algorithm call
154 double omega = 0.6;
155 double eta1 = 2;
156 double eta2 = 2;
157 int vcoeff = 1;
159 //stopping criteria
160 int itermax = 120; //Maximum number of iterations allowed (i.e. output printed on the screen)
161 double stdmin = 1e-5; //Standard deviation of the population that determines a stop
163 //Experiment Outputs
164 double mean = 0, dev= 0, max = 0, min = 200000000;
165 vector <double> results;
167 //Instanciate the algorithm
168 PSOalgorithm PSO;
169 PSO.initPSO(gen,LB.size(),omega,eta1,eta2,vcoeff, rng.next());
171 for (int i=0;i<trials;i++){
172 cout << "\nTrial number #" << i+1 << endl;
173 //we create a random population
174 pop.createRandomPopulation(LB,UB,NP, rng);
175 pop.evaluatePopulation(problem);
176 int iter = 0;
178 time(&start);
179 while(iter < itermax){
180 iter ++;
181 //we print the best
182 cout << "Initial fitness: " << pop.extractBestIndividual().getFitness() << endl;
183 //we evolve it
184 start1=clock();
185 pop = PSO.evolve(pop,problem);
186 end1=clock();
187 dif = (double)(end1-start1) / (double)CLOCKS_PER_SEC;
188 //we print the result
189 cout << "Final fitness: " << pop.extractBestIndividual().getFitness() << endl;
190 cout << "Worst fitness: " << pop.extractWorstIndividual().getFitness() << endl;
191 cout << "Mean : " << pop.evaluateMean() << endl;
192 cout << "Std : " << pop.evaluateStd() << endl;
193 cout << "\t\tSeconds elapsed: " << dif << endl;
195 time(&end);
196 results.push_back(pop.extractBestIndividual().getFitness());
197 dif = difftime(end,start);
198 cout << "\nSeconds elapsed: " << dif << endl<<endl;
201 //evaluate experiment results
202 for (int i=0;i<trials;i++){
203 mean += results[i];
204 if (results[i] > max) max = results[i];
205 if (results[i] < min) min = results[i];
207 mean /= trials;
209 for (int i=0;i<trials;i++){
210 dev += (mean-results[i])*(mean-results[i]);
212 dev = sqrt(dev/trials);
214 for (int i=0;i<trials;i++){
215 cout << "\nTrial #" << i << ": " << results[i] << endl;
219 //print results
220 cout << "\nMean: " << mean << endl;
221 cout << "Std: " << dev << endl;
222 cout << "Max: " << max << endl;
223 cout << "Min: " << min << endl;
225 break;
227 case 3: //MPSO sequential experiment
229 //Experiment Settings
230 int NP = 20; //population size
231 int trials = 100; //number of trials
232 int gen = 500; //generations per algorithm call
233 double omega = 0.65;
234 double eta1 = 2.0;
235 double eta2 = 2.0;
236 int vcoeff = 1;
237 int nswarms = 4;
239 //stopping criteria
240 int itermax = 100; //Maximum number of iterations allowed (i.e. output printed on the screen)
241 double stdmin = 1e-5; //Standard deviation of the population that determines a stop
243 //Experiment Outputs
244 double mean = 0, dev= 0, max = 0, min = 200000000;
245 vector <double> results;
247 //Instanciate the algorithm
248 MPSOalgorithm MPSO;
249 MPSO.initMPSO(gen,LB.size(),omega,eta1,eta2,vcoeff,nswarms, rng.next());
251 for (int i=0;i<trials;i++){
252 cout << "\nTrial number #" << i+1 << endl;
253 //we create a random population
254 pop.createRandomPopulation(LB,UB,NP, rng);
255 pop.evaluatePopulation(problem);
256 int iter = 0;
258 time(&start);
259 while(iter < itermax){
260 iter ++;
261 //we print the best
262 cout << "Initial fitness: " << pop.extractBestIndividual().getFitness() << endl;
263 //we evolve it
264 start1=clock();
265 pop = MPSO.evolve(pop,problem);
266 end1=clock();
267 dif = (double)(end1-start1) / (double)CLOCKS_PER_SEC;
268 //we print the result
269 cout << "Final fitness: " << pop.extractBestIndividual().getFitness() << endl;
270 cout << "Worst fitness: " << pop.extractWorstIndividual().getFitness() << endl;
271 cout << "Mean : " << pop.evaluateMean() << endl;
272 cout << "Std : " << pop.evaluateStd() << endl;
273 cout << "\t\tSeconds elapsed: " << dif << endl;
275 time(&end);
276 results.push_back(pop.extractBestIndividual().getFitness());
277 dif = difftime(end,start);
278 cout << "\nSeconds elapsed: " << dif << endl<<endl;
281 //evaluate experiment results
282 for (int i=0;i<trials;i++){
283 mean += results[i];
284 if (results[i] > max) max = results[i];
285 if (results[i] < min) min = results[i];
287 mean /= trials;
289 for (int i=0;i<trials;i++){
290 dev += (mean-results[i])*(mean-results[i]);
292 dev = sqrt(dev/trials);
294 for (int i=0;i<trials;i++){
295 cout << "\nTrial #" << i << ": " << results[i] << endl;
299 //print results
300 cout << "\nMean: " << mean << endl;
301 cout << "Std: " << dev << endl;
302 cout << "Max: " << max << endl;
303 cout << "Min: " << min << endl;
305 break;
309 case 4: //Sequential Differential Evolution Experiment
311 //Experiment Settings
312 int NP = 20; //population size for each island
313 int trials = 100; //number of trials
314 int gen = 500; //generations per algorithm call
315 double F = 0.8; //F in DE
316 double CR = 0.8; //CR in DE
317 int strategy = 2; //DE startegy
319 //stopping criteria
320 int itermax = 120; //Maximum number of iterations allowed (i.e. output printed on the screen)
322 //Experiment Outputs
323 double mean = 0, dev= 0, max = 0, min = 200000000;
324 vector <double> results;
326 //Instanciate the algorithm
327 DEalgorithm DE;
328 DE.initDE(gen,LB.size(),F,CR,strategy, rng.next());
330 for (int i=0;i<trials;i++){
331 cout << "\nTrial number #" << i+1 << endl;
332 //we create a random population
335 pop.createRandomPopulation(LB,UB,NP, rng);
336 pop.evaluatePopulation(problem);
337 int iter = 0;
339 time(&start);
340 while( iter < itermax){
341 iter ++;
342 //we print the best
343 cout << "Initial fitness: " << pop.extractBestIndividual().getFitness() << endl;
344 //we evolve it
345 start1=clock();
346 pop = DE.evolve(pop,problem);
347 end1=clock();
348 dif = (double)(end1-start1) / (double)CLOCKS_PER_SEC;
349 //we print the result
350 cout << "Final fitness: " << pop.extractBestIndividual().getFitness() << endl;
351 cout << "Worst fitness: " << pop.extractWorstIndividual().getFitness() << endl;
352 cout << "Mean : " << pop.evaluateMean() << endl;
353 cout << "Std : " << pop.evaluateStd() << endl;
354 cout << "\t\tSeconds elapsed: " << dif << endl;
356 time(&end);
357 //if (iter<itermax){
358 //results.push_back(iter*NP*gen);
359 results.push_back(pop.extractBestIndividual().getFitness());
361 dif = difftime(end,start);
362 cout << "\nSeconds elapsed: " << dif << endl<<endl;
363 for (int i=0;i<D;i++){
364 logfile << pop.extractBestIndividual()[i] << " ";
366 logfile << exp(-pop.extractBestIndividual().getFitness()) <<endl;
369 //evaluate experiment results
370 for (unsigned int i=0;i<results.size();i++){
371 mean += results[i];
372 if (results[i] > max) max = results[i];
373 if (results[i] < min) min = results[i];
375 mean /= results.size();
377 for (unsigned int i=0;i<results.size();i++){
378 dev += (mean-results[i])*(mean-results[i]);
380 dev = sqrt(dev/results.size());
382 for (unsigned int i=0;i<results.size();i++){
383 cout << "\nTrial #" << i << ": " << results[i] << endl;
386 //print results
387 cout << "\nMean: " << mean << endl;
388 cout << "Std: " << dev << endl;
389 cout << "Max: " << max << endl;
390 cout << "Min: " << min << endl;
391 cout << "Success: " << results.size() << endl;
393 break;
397 case 5: //SGA experiment
399 //Experiment Settings
400 int NP = 20; //population size
401 int trials = 100; //number of trials
402 int gen = 500; //generations per algorithm call
403 double CR = 0.7;
404 double M = 0.2;
405 int insert_best = 1;
407 //stopping criteria
408 int itermax = 120; //Maximum number of iterations allowed (i.e. output printed on the screen)
410 //Experiment Outputs
411 double mean = 0, dev= 0, max = 0, min = 200000000;
412 vector <double> results;
414 //Instanciate the algorithm
415 //Simple Genetic Algorithm
416 SGAalgorithm SGA;
417 SGA.initSGA(gen,LB.size(),CR,M,insert_best, rng.next());
419 for (int i=0;i<trials;i++){
420 cout << "\nTrial number #" << i+1 << endl;
421 //we create a random population
422 pop.createRandomPopulation(LB,UB,NP, rng);
423 pop.evaluatePopulation(problem);
424 int iter = 0;
426 time(&start);
427 while( iter < itermax){
428 iter ++;
429 //we print the best
430 cout << "Initial fitness: " << pop.extractBestIndividual().getFitness() << endl;
431 //we evolve it
432 start1=clock();
433 pop = SGA.evolve(pop,problem);
434 end1=clock();
435 dif = (double)(end1-start1) / (double)CLOCKS_PER_SEC;
436 //we print the result
437 cout << "Final fitness: " << pop.extractBestIndividual().getFitness() << endl;
438 cout << "Worst fitness: " << pop.extractWorstIndividual().getFitness() << endl;
439 cout << "Mean : " << pop.evaluateMean() << endl;
440 cout << "Std : " << pop.evaluateStd() << endl;
441 cout << "\t\tSeconds elapsed: " << dif << endl;
443 time(&end);
444 results.push_back(pop.extractBestIndividual().getFitness());
445 dif = difftime(end,start);
446 cout << "\nSeconds elapsed: " << dif << endl<<endl;
449 //evaluate experiment results
450 for (int i=0;i<trials;i++){
451 mean += results[i];
452 if (results[i] > max) max = results[i];
453 if (results[i] < min) min = results[i];
455 mean /= trials;
457 for (int i=0;i<trials;i++){
458 dev += (mean-results[i])*(mean-results[i]);
460 dev = sqrt(dev/trials);
462 for (int i=0;i<trials;i++){
463 cout << "\nTrial #" << i << ": " << results[i] << endl;
467 //print results
468 cout << "\nMean: " << mean << endl;
469 cout << "Std: " << dev << endl;
470 cout << "Max: " << max << endl;
471 cout << "Min: " << min << endl;
473 //Lines to test SGA
474 break;
476 case 6: //Parallel asynchronous island model
479 //Experiment Settings
480 int NP = 1; //population size for each island
481 int trials = 20; //number of trials
482 int gen = 500; //generations per algorithm call
483 double F = 0.8; //F in DE
484 double CR = 0.8; //CR in DE
485 int strategy = 2; //DE startegy
486 int islandsN = 1; //Number of Islands
488 //stopping criteria
489 int itermax = 120; //Maximum number of iterations allowed (i.e. output printed on the screen)
491 //Experiment Outputs
492 double mean = 0, dev= 0, max = 0, min = 200000000;
493 vector <double> results;
495 //Main cycle creating threads
496 for (int i=0;i<trials;i++){
497 cout << "\nTrial number #" << i+1 << endl;
498 //We create a random population in each island (this is done by the main thread - i.e. no parallelization here)
499 vector<Population> IslandPop(islandsN);
500 vector<GOProblem*> parallelProblems(islandsN);
501 for (int i=0;i<islandsN;i++){
502 parallelProblems[i] = new tandemProb();
504 IslandPop[i].createRandomPopulation(LB,UB,NP, rng);
505 IslandPop[i].evaluatePopulation(*parallelProblems[i]);
508 //We instanciate the objects needed for pthreads allocating memory for the threads array
509 pthread_t *threads;
510 threads = new pthread_t [islandsN];
511 pthread_mutex_t mutex;
512 pthread_cond_t exitcond;
513 pthread_mutex_init(&mutex, NULL);
514 pthread_cond_init (&exitcond, NULL);
516 //We allocate memory for the isActive array containing the status ofeach thread and we initialise it to false (no threads opened)
517 bool *isActive;
518 isActive = new bool[islandsN];
519 for (int i=0;i<islandsN;i++) isActive[i]=false; //all threads are inactive
521 //We allocate memory and initialise the data threadParam array containing the information to be passed to the different threads
522 threadParam* data;
523 data = new threadParam [islandsN];
524 for (int i=0;i<islandsN;i++){
525 data[i].threadID = i;
527 data[i].problem = parallelProblems[i];
528 data[i].Ptr_pop = &IslandPop[i]; //Each Island has a different population
531 data[i].NP = NP;
532 data[i].generations = gen;
534 //Initialise DE specific data
535 data[i].strategy = 1;
536 data[i].F = F;
537 data[i].CR = CR;
539 //Initialise PSO/MPSO specific data
540 data[i].omega = 0.65;
541 data[i].eta1 = 2.0;
542 data[i].eta2 = 2.0;
543 data[i].vcoeff = 1;
544 data[i].nswarms = 4;
546 //Initialise SGA specific data
547 data[i].CRsga = 0.95;
548 data[i].M = 0.2;
549 data[i].insert_best =1;
551 //Initialise ASA specific data
552 data[i].Ts = 1;
553 data[i].Tf = data[i].Ts/1000;
554 data[i].isActive = &isActive[i];
555 data[i].TPmutex = &mutex;
556 data[i].exit = &exitcond;
558 data[i].Ptr_log = &logfile;
561 int iter=0;
562 int rc;
563 int IslandType = 0;
564 double loweststd = 1000000;
566 pthread_mutex_lock (&mutex);
567 time(&start);
568 while(iter < itermax){
569 for (int i=0;i<islandsN;i++){
570 if ( !*(data[i].isActive) ){
571 //Create again the i-th thread to simulate an Island
572 IslandType = 3;
573 if (IslandType == 0){
574 data[i].randomSeed = rng.next();
575 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;
576 rc = pthread_create(&threads[i], NULL, PSOthread, (void *)&data[i]);
578 else if (IslandType == 1){
579 data[i].randomSeed = rng.next();
580 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;
581 rc = pthread_create(&threads[i], NULL, MPSOthread, (void *)&data[i]);
583 else if (IslandType == 2){
584 data[i].randomSeed = rng.next();
585 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;
586 rc = pthread_create(&threads[i], NULL, SGAthread, (void *)&data[i]);
588 else if (IslandType == 3){
589 data[i].randomSeed = rng.next();
590 data[i].generations=10000;
591 data[i].NP = 1;
592 cout << "\t\t\tASA:\t\t Ts: "<< data[i].Ts << "\t\tTf: " << data[i].Tf << "\t\tGenerations: " << data[i].generations << endl;
593 rc = pthread_create(&threads[i], NULL, ASAthread, (void *)&data[i]);
595 else {
596 data[i].randomSeed = rng.next();
597 data[i].strategy = strategy;
598 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;
599 rc = pthread_create(&threads[i], NULL, DEthread, (void *)&data[i]);
601 if (rc){
602 //Problem creating the thread
603 printf("ERROR; return code from pthread_create() is %d\n", rc);
604 exit(-1);
606 else{
607 //Thread Successfully Created
608 iter += 1;
609 *(data[i].isActive) = true;
610 //thread is detached as it will never be joined
611 //(on OSx Leopard this avoids that at a certain point
612 //threads cannot be created anymore resulting in rc=35)
613 pthread_detach(threads[i]);
616 //evaluate highest standard deviation across Islands
617 //loweststd = IslandPop[0].evaluateStd();
618 loweststd = IslandPop[0].extractBestIndividual().getFitness();
619 for (int i2=1;i2<islandsN;i2++){
620 if (loweststd < IslandPop[i2].extractBestIndividual().getFitness()) loweststd = IslandPop[i2].extractBestIndividual().getFitness();
623 //log islands best and std
624 for (int i2=0;i2<islandsN;i2++){
625 cout << "CPU#:" << i2 << ": " << IslandPop[i2].extractBestIndividual().getFitness() << " " << IslandPop[i2].evaluateStd() << endl;
627 cout << "HighestStd: " << loweststd << endl;
628 cout << "Iter: " << iter+1 << endl;
629 cout << "\nmain():" << endl << "\t\t\tcreating thread, ID " << i << endl;
631 //ring topology migration
632 if (Pk::nextDouble(rng) < 0.2){
633 IslandPop[(i+1) % islandsN].substituteIndividual(IslandPop[i].extractBestIndividual(), rng.next() % data[i].NP);
638 pthread_cond_wait(&exitcond, &mutex);
640 pthread_mutex_unlock (&mutex);
641 //The main cycle has finished: we wait for all threads to finish
642 for (int i=0; i<islandsN;i++){
643 while (*data[i].isActive); //infinite loop if a thread never ends
646 //we clean the thread objects and deallocate memory
647 pthread_mutex_destroy(&mutex);
648 pthread_cond_destroy(&exitcond);
649 delete[] data;
650 delete[] threads;
651 delete[] isActive;
652 time(&end);
653 dif = difftime(end,start);
654 cout << "\nSeconds elapsed: " << dif << endl<<endl;
656 double res=IslandPop[0].extractBestIndividual().getFitness();
657 for (int i=1;i<islandsN;i++){
658 if (res > IslandPop[i].extractBestIndividual().getFitness()) res = IslandPop[i].extractBestIndividual().getFitness();
660 //if (iter<itermax){
661 results.push_back(res);
664 for (int i = 0; i < islandsN; i++) {
665 delete parallelProblems[i];
669 //evaluate experiment results
670 for (unsigned int i=0;i<results.size();i++){
671 mean += results[i];
672 if (results[i] > max) max = results[i];
673 if (results[i] < min) min = results[i];
675 mean /= results.size();
677 for (unsigned int i=0;i<results.size();i++){
678 dev += (mean-results[i])*(mean-results[i]);
680 dev = sqrt(dev/results.size());
682 for (unsigned int i=0;i<results.size();i++){
683 cout << "\nTrial #" << i << ": " << results[i] << endl;
686 //print results
687 cout << "\nMean: " << mean << endl;
688 cout << "Std: " << dev << endl;
689 cout << "Max: " << max << endl;
690 cout << "Min: " << min << endl;
691 cout << "Success: " << results.size() << endl;
693 break;
695 case 9:
697 Individual x;
698 x.createRandomIndividual(LB,UB,rng);
699 cout << x << endl;
700 x[0]=666;
701 cout << x << endl;
703 Population pop;
704 pop.createRandomPopulation(LB,UB,5,rng);
705 pop.evaluatePopulation(problem);
706 cout << pop[3] << endl;
707 pop[3][0]=666;
708 cout << pop[3] << endl;
709 cout << pop << endl;
712 break;
714 default:
716 int NUM_THREADS=2;
717 //We create a random population and evaluate its fitness (this is done by the main thread - i.e. no parallelization here)
718 pop.createRandomPopulation(LB,UB,20*5, rng);
719 pop.evaluatePopulation(problem);
721 //We instanciate the objects needed for pthreads allocating memory for the threads array
722 pthread_t *threads;
723 threads = new pthread_t [NUM_THREADS];
724 //pthread_attr_t attr;
725 //pthread_attr_init(&attr);
726 //pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
727 pthread_mutex_t mutex;
728 pthread_cond_t exitcond;
729 pthread_mutex_init(&mutex, NULL);
730 pthread_cond_init (&exitcond, NULL);
735 //We allocate memory for the isActive array containing the status ofeach thread and we initialise it to false (no threads opened)
736 bool *isActive;
737 isActive = new bool[NUM_THREADS]; //all threads are inactive
738 for (int i=0;i<NUM_THREADS;i++) {isActive[i]=false;}
740 //We allocate memory and initialise the data threadParam array containing the information to be passed to the different threads
741 threadParam *data;
742 data = new threadParam [NUM_THREADS];
743 for (int i=0;i<NUM_THREADS;i++){
744 data[i].threadID = i;
746 data[i].problem = &problem;
747 data[i].Ptr_pop = &pop;
749 data[i].generations = 500;
751 //Initialise DE specific data
752 data[i].strategy = 2;
753 data[i].F = 0.8;
754 data[i].CR = 0.8;
756 //Initialise PSO specific data
757 data[i].omega = 0.5;
758 data[i].eta1 = 2.0;
759 data[i].eta2 = 2.0;
760 data[i].vcoeff = 1000;
762 data[i].isActive = &isActive[i];
763 data[i].TPmutex = &mutex;
764 data[i].exit = &exitcond;
766 data[i].Ptr_log = &logfile;
769 //Main cycle creating threads
770 int globalCount=0;
771 int count1=0,count2=0;
772 int rc;
773 int algorithmchoice = 0;
775 pthread_mutex_lock (&mutex);
776 time(&start);
777 while (globalCount<120){
778 //while(pop.extractBestIndividual().getFitness()!=0){
779 for (int i=0;i<NUM_THREADS;i++){
780 if ( !*(data[i].isActive) ){
781 cout << "main():" << endl << "\t\t\tcreating thread, ID " << i << endl;
782 algorithmchoice = 4;//r250()%10;
783 if (algorithmchoice == 0){
784 count1++;
785 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;
786 rc = pthread_create(&threads[i], NULL, PSOthread, (void *)&data[i]);
788 else {
789 data[i].strategy = i+1;
790 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;
791 rc = pthread_create(&threads[i], NULL, DEthread, (void *)&data[i]);
792 count2++;
795 if (rc){
796 printf("ERROR; return code from pthread_create() is %d\n", rc);
797 exit(-1);
799 else{
800 globalCount += 1;
801 *(data[i].isActive) = true;
805 pthread_cond_wait(&exitcond, &mutex);
807 pthread_mutex_unlock (&mutex);
809 //The main cycle has finished: we wait for all threads to finish
810 for (int i=0; i<NUM_THREADS;i++){
811 pthread_join(threads[i],NULL);
814 //we clean the thread objects and deallocate memory
815 pthread_mutex_destroy(&mutex);
816 //pthread_attr_destroy(&attr);
817 pthread_cond_destroy(&exitcond);
818 delete[] data;
819 delete[] threads;
820 delete[] isActive;
821 time(&end);
822 dif = difftime(end,start);
823 cout << "\nSeconds elapsed: " << dif << endl<<endl;
824 cout << "\nCount1: " << count1 << endl;
825 cout << "\nCount2: " << count2 << endl;
828 break;
829 }//end case
831 } //end while
834 //The following lines are commented out as they implement exactly the DiGMO random strategy in a random
835 //way. This creates a very unefficient cooperation between the algorithms as it does not have the implicit
836 //learning of the best strategy. This is the mechanism that allow, in the distributed version of the algorithm,
837 //the same individual to be evolved by different algorithms and only the most succesful one to be selected
839 //It seems that the reinsertion strategy (only improved individuals substitute their old versions) together with
840 //the contemporary evolution of the same individuals is key to the efficiency of algorithm cooperation (mimicking co-evolution)
841 //In a sequential version this can be enforced by evolving with DE, PSO and SA and only at the end perform reinsertion
842 //as in the uncommented lines above
844 /*algorithmchoice = r250()%3;
845 if ( algorithmchoice == 0 ){
846 deme=pop.extractRandomDeme(20,picks);
847 //we print the best
848 cout << "Using DE" << endl;
849 cout << "Initial fitness: " << deme.extractBestIndividual().getFitness() << endl;
850 //DE.initDE(50,LB.size(),dr250(),dr250(),(int)dr250()*11+1);
851 deme = DE.evolve(deme,&rosenbrock,LB,UB);
854 else if ( algorithmchoice == 1 ){
855 deme=pop.extractRandomDeme(20,picks);
856 //deme.resetVelocities(LB,UB);
857 //we print the best
858 cout << "Using PSO" << endl;
859 cout << "Initial fitness: " << deme.extractBestIndividual().getFitness() << endl;
860 //PSO.initPSO(500,LB.size(),(dr250()+1)/2,4.0*dr250(),4.0*dr250(),(int)dr250()*10000);
861 deme = PSO.evolve(deme,&rosenbrock,LB,UB);
864 else if ( algorithmchoice == 2 ){
865 deme=pop.extractRandomDeme(1,picks);
866 //deme.resetVelocities(LB,UB);
867 //we print the best
868 cout << "Using ASA" << endl;
869 cout << "Initial fitness: " << deme.extractBestIndividual().getFitness() << endl;
870 //ASA.initASA(10000,1,8,LB.size(),dr250(),dr250(),1.0);
871 deme = ASA.evolve(deme[0],&rosenbrock,LB,UB);
874 //we print the result
875 cout << "Final fitness: " << deme.extractBestIndividual().getFitness() << endl;
876 //we insert it in the main population
877 pop.insertDeme(deme,picks);
878 picks.clear();*/
881 cout << "\nBest fitness found: " << pop.extractBestIndividual().getFitness() << endl;
883 return 0;