Make DiGMO problem use boost.thread instead of pthreads.
[PaGMO.git] / main.cpp
blobfa77e2d819cecca6f5e1230b55862af0827eb67f
1 #include <boost/thread/condition_variable.hpp>
2 #include <boost/thread/locks.hpp>
3 #include <boost/thread/mutex.hpp>
4 #include <iostream>
5 #include <fstream>
6 #include <iomanip>
7 #include <vector>
8 #include <ctime> //for time()
9 #include "population.h"
10 #include "ASA.h"
11 #include "PSO.h"
12 #include "DE.h"
13 #include "SGA.h"
14 #include "MPSO.h"
15 #include "LOCAL.h"
16 #include "TrajectoryProblems.h"
17 #include "ClassicProblems.h"
18 #include <pthread.h>
19 #include "SolversThreads.h"
20 #include "PkRandom.h"
22 using namespace std;
24 typedef boost::unique_lock<boost::mutex> lock_type;
26 int main(){
28 int D =0; //Problem dimension will be assigned later
29 int choice=0; //User choice
30 cout.precision(9);
32 //We prepare the pseudorandom sequence (TODO: check the randomnumbers of different threads are different)
34 Pk::Random32 rng(time(0));
36 //we set the problem
37 typedef messengerfullProb problem_type;
38 problem_type problem;
39 //we extract its information into local variables
40 const vector<double>& LB = problem.getLB();
41 const vector<double>& UB = problem.getUB();
42 D = problem.getDimension();
44 //we declare populations and individuals
45 Population demeDE,demePSO,demeASA,demeLOCA,demeSGA,pop;
46 Individual x;
47 vector <int> picksDE,picksPSO,picksASA,picksLOCAL,picksSGA;
49 time_t start,end,start1,end1;
50 double dif;
52 //We create and open the logfile
53 ofstream logfile("log.txt");
57 while (choice != -1) {
59 //we choose the algorithm
61 cout << "Choose: 1-ASA, 2-PSO, 3-MPSO, 4-DE, 5-SGA, 6-IslandModel(ring), 7-DiGMO(simulator): ";
62 cin >> choice;
64 switch (choice){
65 case 1:
67 //Experiment Settings
68 int NP = 1; //population size
69 int trials = 300; //number of trials
70 int niterTot = 10000; //generations per algorithm call
71 int niterRange = 20;
72 int niterTemp = 1;
73 double T0 = 10;
74 double Tf = T0/1000;
75 double Tcoeff = 0.85;
76 double StartStep =1;
78 //stopping criteria
79 int itermax = 120; //Maximum number of iterations allowed (i.e. output printed on the screen)
81 //Experiment Outputs
82 double mean = 0, dev= 0, max = 0, min = 200000000;
83 vector <double> results;
85 //Instanciate the algorithm
86 //Adaptive Simulated Annealing
87 ASAalgorithm ASA;
88 //ASA.initASA(niterTot,niterTemp,niterRange,LB.size(),T0,Tcoeff,StartStep, rng.next());
89 ASA.initASA(niterTot,LB.size(),T0,Tf, rng.next());
91 //Pruned bounds
93 for (int i=0;i<trials;i++){
94 cout << "\nTrial number #" << i+1 << endl;
95 //we create a random population
96 pop.createRandomPopulation(LB,UB,NP, rng);
97 pop.evaluatePopulation(problem);
98 int iter = 0;
100 time(&start);
101 while( iter < itermax){
102 iter ++;
103 //we print the best
104 cout << "Initial fitness: " << pop.extractBestIndividual().getFitness() << endl;
105 //we evolve it
106 start1=clock();
107 if (pop.extractBestIndividual().getFitness() < 5){
108 ASA.initASA(niterTot,LB.size(),1,0.01, rng.next());
110 pop = ASA.evolve(pop[0],problem);
111 end1=clock();
112 dif = (double)(end1-start1) / (double)CLOCKS_PER_SEC;
113 //we print the result
114 cout << "Final fitness: " << pop.extractBestIndividual().getFitness() << endl;
115 cout << "Worst fitness: " << pop.extractWorstIndividual().getFitness() << endl;
116 cout << "Mean : " << pop.evaluateMean() << endl;
117 cout << "Std : " << pop.evaluateStd() << endl;
118 cout << "\t\tSeconds elapsed: " << dif << endl;
120 time(&end);
121 results.push_back(pop.extractBestIndividual().getFitness());
122 dif = difftime(end,start);
123 cout << "\nSeconds elapsed: " << dif << endl<<endl;
124 for (int i=0;i<D;i++){
125 logfile << pop.extractBestIndividual()[i] << " ";
127 logfile << exp(-pop.extractBestIndividual().getFitness()) <<endl;
130 //evaluate experiment results
131 for (int i=0;i<trials;i++){
132 mean += results[i];
133 if (results[i] > max) max = results[i];
134 if (results[i] < min) min = results[i];
136 mean /= trials;
138 for (int i=0;i<trials;i++){
139 dev += (mean-results[i])*(mean-results[i]);
141 dev = sqrt(dev/trials);
143 for (int i=0;i<trials;i++){
144 cout << "\nTrial #" << i << ": " << results[i] << endl;
148 //print results
149 cout << "\nMean: " << mean << endl;
150 cout << "Std: " << dev << endl;
151 cout << "Max: " << max << endl;
152 cout << "Min: " << min << endl;
154 //Lines to test ASA
155 break;
157 case 2: //PSO sequential experiment
159 //Experiment Settings
160 int NP = 20; //population size
161 int trials = 100; //number of trials
162 int gen = 500; //generations per algorithm call
163 double omega = 0.6;
164 double eta1 = 2;
165 double eta2 = 2;
166 int vcoeff = 1;
168 //stopping criteria
169 int itermax = 120; //Maximum number of iterations allowed (i.e. output printed on the screen)
170 double stdmin = 1e-5; //Standard deviation of the population that determines a stop
172 //Experiment Outputs
173 double mean = 0, dev= 0, max = 0, min = 200000000;
174 vector <double> results;
176 //Instanciate the algorithm
177 PSOalgorithm PSO;
178 PSO.initPSO(gen,LB.size(),omega,eta1,eta2,vcoeff, rng.next());
180 for (int i=0;i<trials;i++){
181 cout << "\nTrial number #" << i+1 << endl;
182 //we create a random population
183 pop.createRandomPopulation(LB,UB,NP, rng);
184 pop.evaluatePopulation(problem);
185 int iter = 0;
187 time(&start);
188 while(iter < itermax){
189 iter ++;
190 //we print the best
191 cout << "Initial fitness: " << pop.extractBestIndividual().getFitness() << endl;
192 //we evolve it
193 start1=clock();
194 pop = PSO.evolve(pop,problem);
195 end1=clock();
196 dif = (double)(end1-start1) / (double)CLOCKS_PER_SEC;
197 //we print the result
198 cout << "Final fitness: " << pop.extractBestIndividual().getFitness() << endl;
199 cout << "Worst fitness: " << pop.extractWorstIndividual().getFitness() << endl;
200 cout << "Mean : " << pop.evaluateMean() << endl;
201 cout << "Std : " << pop.evaluateStd() << endl;
202 cout << "\t\tSeconds elapsed: " << dif << endl;
204 time(&end);
205 results.push_back(pop.extractBestIndividual().getFitness());
206 dif = difftime(end,start);
207 cout << "\nSeconds elapsed: " << dif << endl<<endl;
210 //evaluate experiment results
211 for (int i=0;i<trials;i++){
212 mean += results[i];
213 if (results[i] > max) max = results[i];
214 if (results[i] < min) min = results[i];
216 mean /= trials;
218 for (int i=0;i<trials;i++){
219 dev += (mean-results[i])*(mean-results[i]);
221 dev = sqrt(dev/trials);
223 for (int i=0;i<trials;i++){
224 cout << "\nTrial #" << i << ": " << results[i] << endl;
228 //print results
229 cout << "\nMean: " << mean << endl;
230 cout << "Std: " << dev << endl;
231 cout << "Max: " << max << endl;
232 cout << "Min: " << min << endl;
234 break;
236 case 3: //MPSO sequential experiment
238 //Experiment Settings
239 int NP = 20; //population size
240 int trials = 100; //number of trials
241 int gen = 500; //generations per algorithm call
242 double omega = 0.65;
243 double eta1 = 2.0;
244 double eta2 = 2.0;
245 int vcoeff = 1;
246 int nswarms = 4;
248 //stopping criteria
249 int itermax = 100; //Maximum number of iterations allowed (i.e. output printed on the screen)
250 double stdmin = 1e-5; //Standard deviation of the population that determines a stop
252 //Experiment Outputs
253 double mean = 0, dev= 0, max = 0, min = 200000000;
254 vector <double> results;
256 //Instanciate the algorithm
257 MPSOalgorithm MPSO;
258 MPSO.initMPSO(gen,LB.size(),omega,eta1,eta2,vcoeff,nswarms, rng.next());
260 for (int i=0;i<trials;i++){
261 cout << "\nTrial number #" << i+1 << endl;
262 //we create a random population
263 pop.createRandomPopulation(LB,UB,NP, rng);
264 pop.evaluatePopulation(problem);
265 int iter = 0;
267 time(&start);
268 while(iter < itermax){
269 iter ++;
270 //we print the best
271 cout << "Initial fitness: " << pop.extractBestIndividual().getFitness() << endl;
272 //we evolve it
273 start1=clock();
274 pop = MPSO.evolve(pop,problem);
275 end1=clock();
276 dif = (double)(end1-start1) / (double)CLOCKS_PER_SEC;
277 //we print the result
278 cout << "Final fitness: " << pop.extractBestIndividual().getFitness() << endl;
279 cout << "Worst fitness: " << pop.extractWorstIndividual().getFitness() << endl;
280 cout << "Mean : " << pop.evaluateMean() << endl;
281 cout << "Std : " << pop.evaluateStd() << endl;
282 cout << "\t\tSeconds elapsed: " << dif << endl;
284 time(&end);
285 results.push_back(pop.extractBestIndividual().getFitness());
286 dif = difftime(end,start);
287 cout << "\nSeconds elapsed: " << dif << endl<<endl;
290 //evaluate experiment results
291 for (int i=0;i<trials;i++){
292 mean += results[i];
293 if (results[i] > max) max = results[i];
294 if (results[i] < min) min = results[i];
296 mean /= trials;
298 for (int i=0;i<trials;i++){
299 dev += (mean-results[i])*(mean-results[i]);
301 dev = sqrt(dev/trials);
303 for (int i=0;i<trials;i++){
304 cout << "\nTrial #" << i << ": " << results[i] << endl;
308 //print results
309 cout << "\nMean: " << mean << endl;
310 cout << "Std: " << dev << endl;
311 cout << "Max: " << max << endl;
312 cout << "Min: " << min << endl;
314 break;
318 case 4: //Sequential Differential Evolution Experiment
320 //Experiment Settings
321 int NP = 20; //population size for each island
322 int trials = 100; //number of trials
323 int gen = 500; //generations per algorithm call
324 double F = 0.8; //F in DE
325 double CR = 0.8; //CR in DE
326 int strategy = 2; //DE startegy
328 //stopping criteria
329 int itermax = 120; //Maximum number of iterations allowed (i.e. output printed on the screen)
331 //Experiment Outputs
332 double mean = 0, dev= 0, max = 0, min = 200000000;
333 vector <double> results;
335 //Instanciate the algorithm
336 DEalgorithm DE;
337 DE.initDE(gen,LB.size(),F,CR,strategy, rng.next());
339 for (int i=0;i<trials;i++){
340 cout << "\nTrial number #" << i+1 << endl;
341 //we create a random population
344 pop.createRandomPopulation(LB,UB,NP, rng);
345 pop.evaluatePopulation(problem);
346 int iter = 0;
348 time(&start);
349 while( iter < itermax){
350 iter ++;
351 //we print the best
352 cout << "Initial fitness: " << pop.extractBestIndividual().getFitness() << endl;
353 //we evolve it
354 start1=clock();
355 pop = DE.evolve(pop,problem);
356 end1=clock();
357 dif = (double)(end1-start1) / (double)CLOCKS_PER_SEC;
358 //we print the result
359 cout << "Final fitness: " << pop.extractBestIndividual().getFitness() << endl;
360 cout << "Worst fitness: " << pop.extractWorstIndividual().getFitness() << endl;
361 cout << "Mean : " << pop.evaluateMean() << endl;
362 cout << "Std : " << pop.evaluateStd() << endl;
363 cout << "\t\tSeconds elapsed: " << dif << endl;
365 time(&end);
366 //if (iter<itermax){
367 //results.push_back(iter*NP*gen);
368 results.push_back(pop.extractBestIndividual().getFitness());
370 dif = difftime(end,start);
371 cout << "\nSeconds elapsed: " << dif << endl<<endl;
372 for (int i=0;i<D;i++){
373 logfile << pop.extractBestIndividual()[i] << " ";
375 logfile << exp(-pop.extractBestIndividual().getFitness()) <<endl;
378 //evaluate experiment results
379 for (unsigned int i=0;i<results.size();i++){
380 mean += results[i];
381 if (results[i] > max) max = results[i];
382 if (results[i] < min) min = results[i];
384 mean /= results.size();
386 for (unsigned int i=0;i<results.size();i++){
387 dev += (mean-results[i])*(mean-results[i]);
389 dev = sqrt(dev/results.size());
391 for (unsigned int i=0;i<results.size();i++){
392 cout << "\nTrial #" << i << ": " << results[i] << endl;
395 //print results
396 cout << "\nMean: " << mean << endl;
397 cout << "Std: " << dev << endl;
398 cout << "Max: " << max << endl;
399 cout << "Min: " << min << endl;
400 cout << "Success: " << results.size() << endl;
402 break;
406 case 5: //SGA experiment
408 //Experiment Settings
409 int NP = 20; //population size
410 int trials = 100; //number of trials
411 int gen = 500; //generations per algorithm call
412 double CR = 0.7;
413 double M = 0.2;
414 int insert_best = 1;
416 //stopping criteria
417 int itermax = 120; //Maximum number of iterations allowed (i.e. output printed on the screen)
419 //Experiment Outputs
420 double mean = 0, dev= 0, max = 0, min = 200000000;
421 vector <double> results;
423 //Instanciate the algorithm
424 //Simple Genetic Algorithm
425 SGAalgorithm SGA;
426 SGA.initSGA(gen,LB.size(),CR,M,insert_best, rng.next());
428 for (int i=0;i<trials;i++){
429 cout << "\nTrial number #" << i+1 << endl;
430 //we create a random population
431 pop.createRandomPopulation(LB,UB,NP, rng);
432 pop.evaluatePopulation(problem);
433 int iter = 0;
435 time(&start);
436 while( iter < itermax){
437 iter ++;
438 //we print the best
439 cout << "Initial fitness: " << pop.extractBestIndividual().getFitness() << endl;
440 //we evolve it
441 start1=clock();
442 pop = SGA.evolve(pop,problem);
443 end1=clock();
444 dif = (double)(end1-start1) / (double)CLOCKS_PER_SEC;
445 //we print the result
446 cout << "Final fitness: " << pop.extractBestIndividual().getFitness() << endl;
447 cout << "Worst fitness: " << pop.extractWorstIndividual().getFitness() << endl;
448 cout << "Mean : " << pop.evaluateMean() << endl;
449 cout << "Std : " << pop.evaluateStd() << endl;
450 cout << "\t\tSeconds elapsed: " << dif << endl;
452 time(&end);
453 results.push_back(pop.extractBestIndividual().getFitness());
454 dif = difftime(end,start);
455 cout << "\nSeconds elapsed: " << dif << endl<<endl;
458 //evaluate experiment results
459 for (int i=0;i<trials;i++){
460 mean += results[i];
461 if (results[i] > max) max = results[i];
462 if (results[i] < min) min = results[i];
464 mean /= trials;
466 for (int i=0;i<trials;i++){
467 dev += (mean-results[i])*(mean-results[i]);
469 dev = sqrt(dev/trials);
471 for (int i=0;i<trials;i++){
472 cout << "\nTrial #" << i << ": " << results[i] << endl;
476 //print results
477 cout << "\nMean: " << mean << endl;
478 cout << "Std: " << dev << endl;
479 cout << "Max: " << max << endl;
480 cout << "Min: " << min << endl;
482 //Lines to test SGA
483 break;
485 case 6: //Parallel asynchronous island model
488 //Experiment Settings
489 int NP = 1; //population size for each island
490 int trials = 20; //number of trials
491 int gen = 500; //generations per algorithm call
492 double F = 0.8; //F in DE
493 double CR = 0.8; //CR in DE
494 int strategy = 2; //DE startegy
495 int islandsN = 6; //Number of Islands
497 //stopping criteria
498 int itermax = 120; //Maximum number of iterations allowed (i.e. output printed on the screen)
500 //Experiment Outputs
501 double mean = 0, dev= 0, max = 0, min = 200000000;
502 vector <double> results;
504 //Main cycle creating threads
505 for (int i=0;i<trials;i++){
506 cout << "\nTrial number #" << i+1 << endl;
507 //We create a random population in each island (this is done by the main thread - i.e. no parallelization here)
508 vector<Population> IslandPop(islandsN);
509 vector<GOProblem*> parallelProblems(islandsN);
510 for (int i=0;i<islandsN;i++){
511 parallelProblems[i] = new problem_type();
513 IslandPop[i].createRandomPopulation(LB,UB,NP, rng);
514 IslandPop[i].evaluatePopulation(*parallelProblems[i]);
517 //We instanciate the objects needed for pthreads allocating memory for the threads array
518 pthread_t *threads;
519 threads = new pthread_t [islandsN];
520 boost::mutex mutex;
521 boost::condition_variable exitcond;
523 //We allocate memory for the isActive array containing the status ofeach thread and we initialise it to false (no threads opened)
524 bool *isActive;
525 isActive = new bool[islandsN];
526 for (int i=0;i<islandsN;i++) isActive[i]=false; //all threads are inactive
528 //We allocate memory and initialise the data threadParam array containing the information to be passed to the different threads
529 threadParam* data;
530 data = new threadParam [islandsN];
531 for (int i=0;i<islandsN;i++){
532 data[i].threadID = i;
534 data[i].problem = parallelProblems[i];
535 data[i].Ptr_pop = &IslandPop[i]; //Each Island has a different population
538 data[i].NP = NP;
539 data[i].generations = gen;
541 //Initialise DE specific data
542 data[i].strategy = 1;
543 data[i].F = F;
544 data[i].CR = CR;
546 //Initialise PSO/MPSO specific data
547 data[i].omega = 0.65;
548 data[i].eta1 = 2.0;
549 data[i].eta2 = 2.0;
550 data[i].vcoeff = 1;
551 data[i].nswarms = 4;
553 //Initialise SGA specific data
554 data[i].CRsga = 0.95;
555 data[i].M = 0.2;
556 data[i].insert_best =1;
558 //Initialise ASA specific data
559 data[i].Ts = 1;
560 data[i].Tf = data[i].Ts/1000;
561 data[i].isActive = &isActive[i];
562 data[i].TPmutex = &mutex;
563 data[i].exit = &exitcond;
565 data[i].Ptr_log = &logfile;
568 int iter=0;
569 int rc;
570 int IslandType = 0;
571 double loweststd = 1000000;
574 lock_type lock(mutex);
575 time(&start);
576 while(iter < itermax){
577 for (int i=0;i<islandsN;i++){
578 if ( !*(data[i].isActive) ){
579 //Create again the i-th thread to simulate an Island
580 IslandType = 3;
581 if (IslandType == 0){
582 data[i].randomSeed = rng.next();
583 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;
584 rc = pthread_create(&threads[i], NULL, PSOthread, (void *)&data[i]);
586 else if (IslandType == 1){
587 data[i].randomSeed = rng.next();
588 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;
589 rc = pthread_create(&threads[i], NULL, MPSOthread, (void *)&data[i]);
591 else if (IslandType == 2){
592 data[i].randomSeed = rng.next();
593 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;
594 rc = pthread_create(&threads[i], NULL, SGAthread, (void *)&data[i]);
596 else if (IslandType == 3){
597 data[i].randomSeed = rng.next();
598 data[i].generations=10000;
599 data[i].NP = 1;
600 cout << "\t\t\tASA:\t\t Ts: "<< data[i].Ts << "\t\tTf: " << data[i].Tf << "\t\tGenerations: " << data[i].generations << endl;
601 rc = pthread_create(&threads[i], NULL, ASAthread, (void *)&data[i]);
603 else {
604 data[i].randomSeed = rng.next();
605 data[i].strategy = strategy;
606 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;
607 rc = pthread_create(&threads[i], NULL, DEthread, (void *)&data[i]);
609 if (rc){
610 //Problem creating the thread
611 printf("ERROR; return code from pthread_create() is %d\n", rc);
612 exit(-1);
614 else{
615 //Thread Successfully Created
616 iter += 1;
617 *(data[i].isActive) = true;
618 //thread is detached as it will never be joined
619 //(on OSx Leopard this avoids that at a certain point
620 //threads cannot be created anymore resulting in rc=35)
621 pthread_detach(threads[i]);
624 //evaluate highest standard deviation across Islands
625 //loweststd = IslandPop[0].evaluateStd();
626 loweststd = IslandPop[0].extractBestIndividual().getFitness();
627 for (int i2=1;i2<islandsN;i2++){
628 if (loweststd < IslandPop[i2].extractBestIndividual().getFitness()) loweststd = IslandPop[i2].extractBestIndividual().getFitness();
631 //log islands best and std
632 for (int i2=0;i2<islandsN;i2++){
633 cout << "CPU#:" << i2 << ": " << IslandPop[i2].extractBestIndividual().getFitness() << " " << IslandPop[i2].evaluateStd() << endl;
635 cout << "HighestStd: " << loweststd << endl;
636 cout << "Iter: " << iter+1 << endl;
637 cout << "\nmain():" << endl << "\t\t\tcreating thread, ID " << i << endl;
639 //ring topology migration
640 if (Pk::nextDouble(rng) < 0.2){
641 IslandPop[(i+1) % islandsN].substituteIndividual(IslandPop[i].extractBestIndividual(), rng.next() % data[i].NP);
646 exitcond.wait(lock);
649 //The main cycle has finished: we wait for all threads to finish
650 for (int i=0; i<islandsN;i++){
651 while (*data[i].isActive); //infinite loop if a thread never ends
654 //deallocate memory
655 delete[] data;
656 delete[] threads;
657 delete[] isActive;
658 time(&end);
659 dif = difftime(end,start);
660 cout << "\nSeconds elapsed: " << dif << endl<<endl;
662 double res=IslandPop[0].extractBestIndividual().getFitness();
663 for (int i=1;i<islandsN;i++){
664 if (res > IslandPop[i].extractBestIndividual().getFitness()) res = IslandPop[i].extractBestIndividual().getFitness();
666 //if (iter<itermax){
667 results.push_back(res);
670 for (int i = 0; i < islandsN; i++) {
671 delete parallelProblems[i];
675 //evaluate experiment results
676 for (unsigned int i=0;i<results.size();i++){
677 mean += results[i];
678 if (results[i] > max) max = results[i];
679 if (results[i] < min) min = results[i];
681 mean /= results.size();
683 for (unsigned int i=0;i<results.size();i++){
684 dev += (mean-results[i])*(mean-results[i]);
686 dev = sqrt(dev/results.size());
688 for (unsigned int i=0;i<results.size();i++){
689 cout << "\nTrial #" << i << ": " << results[i] << endl;
692 //print results
693 cout << "\nMean: " << mean << endl;
694 cout << "Std: " << dev << endl;
695 cout << "Max: " << max << endl;
696 cout << "Min: " << min << endl;
697 cout << "Success: " << results.size() << endl;
699 break;
701 case 7:
704 //Experiment Settings
705 int NP = 200; //main population size
706 int trials = 20; //number of trials
707 int gen = 500; //generations per algorithm call
708 double F = 0.8; //F in DE
709 double CR = 0.8; //CR in DE
710 int strategy = 2; //DE startegy
711 int islandsN = 1; //Number of Islands
713 //stopping criteria
714 int itermax = 120; //Maximum number of iterations allowed (i.e. output printed on the screen)
716 //Experiment Outputs
717 double mean = 0, dev= 0, max = 0, min = 200000000;
718 vector <double> results;
720 //Main cycle creating threads
721 for (int i=0;i<trials;i++){
722 cout << "\nTrial number #" << i+1 << endl;
723 //We create a random population in each island (this is done by the main thread - i.e. no parallelization here)
724 Population IslandPop;
725 vector<GOProblem*> parallelProblems(islandsN);
726 for (int i=0;i<islandsN;i++) { parallelProblems[i] = new problem_type(); } //It is necessary to create a different object per CPU as to make sure to access different memory
727 //locations when the problem is mga or mga-1dsm for th r,v,and DV variables in the mgaproblem structures
728 IslandPop.createRandomPopulation(LB,UB,NP, rng);
729 IslandPop.evaluatePopulation(*parallelProblems[0]); //all the problems are identical.... evaluation is done for the [0] one.
732 //We instanciate the objects needed for pthreads allocating memory for the threads array
733 pthread_t *threads;
734 threads = new pthread_t [islandsN];
735 boost::mutex mutex;
736 boost::condition_variable exitcond;
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[islandsN];
741 for (int i=0;i<islandsN;i++) isActive[i]=false; //all threads are inactive
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 [islandsN];
746 for (int i=0;i<islandsN;i++){
747 data[i].threadID = i;
749 data[i].problem = parallelProblems[i];
750 data[i].Ptr_pop = &IslandPop; //Only one population in DiGMO
753 data[i].NP = 20;
754 data[i].generations = gen;
756 //Initialise DE specific data
757 data[i].strategy = 1;
758 data[i].F = F;
759 data[i].CR = CR;
761 //Initialise PSO/MPSO specific data
762 data[i].omega = 0.65;
763 data[i].eta1 = 2.0;
764 data[i].eta2 = 2.0;
765 data[i].vcoeff = 1;
766 data[i].nswarms = 4;
768 //Initialise SGA specific data
769 data[i].CRsga = 0.95;
770 data[i].M = 0.2;
771 data[i].insert_best =1;
773 //Initialise ASA specific data
774 data[i].Ts = 1;
775 data[i].Tf = data[i].Ts/1000;
776 data[i].isActive = &isActive[i];
777 data[i].TPmutex = &mutex;
778 data[i].exit = &exitcond;
780 data[i].Ptr_log = &logfile;
783 int iter=0;
784 int rc;
785 int IslandType = 0;
786 double loweststd = 1000000;
789 lock_type lock(mutex);
790 time(&start);
791 while(iter < itermax){
792 for (int i=0;i<islandsN;i++){
793 if ( !*(data[i].isActive) ){
794 //Create again the i-th thread to simulate an Island
795 IslandType = 4;
796 if (IslandType == 0){
797 data[i].randomSeed = rng.next();
798 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;
799 rc = pthread_create(&threads[i], NULL, PSOthread, (void *)&data[i]);
801 else if (IslandType == 1){
802 data[i].randomSeed = rng.next();
803 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;
804 rc = pthread_create(&threads[i], NULL, MPSOthread, (void *)&data[i]);
806 else if (IslandType == 2){
807 data[i].randomSeed = rng.next();
808 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;
809 rc = pthread_create(&threads[i], NULL, SGAthread, (void *)&data[i]);
811 else if (IslandType == 3){
812 data[i].randomSeed = rng.next();
813 data[i].generations=10000;
814 data[i].NP = 1;
815 cout << "\t\t\tASA:\t\t Ts: "<< data[i].Ts << "\t\tTf: " << data[i].Tf << "\t\tGenerations: " << data[i].generations << endl;
816 rc = pthread_create(&threads[i], NULL, ASAthread, (void *)&data[i]);
818 else {
819 data[i].randomSeed = rng.next();
820 data[i].strategy = strategy;
821 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;
822 rc = pthread_create(&threads[i], NULL, DEthread, (void *)&data[i]);
824 if (rc){
825 //Problem creating the thread
826 printf("ERROR; return code from pthread_create() is %d\n", rc);
827 exit(-1);
829 else{
830 //Thread Successfully Created
831 iter += 1;
832 *(data[i].isActive) = true;
833 //thread is detached as it will never be joined
834 //(on OSx Leopard this avoids that at a certain point
835 //threads cannot be created anymore resulting in rc=35)
836 pthread_detach(threads[i]);
839 //evaluate standard deviation in main population
840 //loweststd = IslandPop[0].evaluateStd();
841 loweststd = IslandPop.evaluateStd();
843 //log islands best and std
844 for (int i2=0;i2<islandsN;i2++){
845 cout << "CPU#:" << i2 << ": " << IslandPop.extractBestIndividual().getFitness() << " " << IslandPop.evaluateStd() << endl;
847 cout << "HighestStd: " << loweststd << endl;
848 cout << "Iter: " << iter+1 << endl;
849 cout << "\nmain():" << endl << "\t\t\tcreating thread, ID " << i << endl;
851 //ring topology migration
856 exitcond.wait(lock);
859 //The main cycle has finished: we wait for all threads to finish
860 for (int i=0; i<islandsN;i++){
861 while (*data[i].isActive); //infinite loop if a thread never ends
864 //deallocate memory
865 delete[] data;
866 delete[] threads;
867 delete[] isActive;
868 time(&end);
869 dif = difftime(end,start);
870 cout << "\nSeconds elapsed: " << dif << endl<<endl;
872 double res=IslandPop.extractBestIndividual().getFitness();
873 //if (iter<itermax){
874 results.push_back(res);
877 for (int i = 0; i < islandsN; i++) {
878 delete parallelProblems[i];
882 //evaluate experiment results
883 for (unsigned int i=0;i<results.size();i++){
884 mean += results[i];
885 if (results[i] > max) max = results[i];
886 if (results[i] < min) min = results[i];
888 mean /= results.size();
890 for (unsigned int i=0;i<results.size();i++){
891 dev += (mean-results[i])*(mean-results[i]);
893 dev = sqrt(dev/results.size());
895 for (unsigned int i=0;i<results.size();i++){
896 cout << "\nTrial #" << i << ": " << results[i] << endl;
899 //print results
900 cout << "\nMean: " << mean << endl;
901 cout << "Std: " << dev << endl;
902 cout << "Max: " << max << endl;
903 cout << "Min: " << min << endl;
904 cout << "Success: " << results.size() << endl;
906 break;
908 }//end case
910 } //end while
916 cout << "\nBest fitness found: " << pop.extractBestIndividual().getFitness() << endl;
918 return 0;