Fix problem type in island model.
[PaGMO.git] / main.cpp
blob5ebc81c446096504fafb5d7a4947c927e4aa26f8
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 typedef messengerfullProb problem_type;
33 problem_type problem;
34 //we extract its information into local variables
35 const vector<double>& LB = problem.getLB();
36 const vector<double>& UB = problem.getUB();
37 D = problem.getDimension();
39 //we declare populations and individuals
40 Population demeDE,demePSO,demeASA,demeLOCA,demeSGA,pop;
41 Individual x;
42 vector <int> picksDE,picksPSO,picksASA,picksLOCAL,picksSGA;
44 time_t start,end,start1,end1;
45 double dif;
47 //We create and open the logfile
48 ofstream logfile("log.txt");
52 while (choice != -1) {
54 //we choose the algorithm
56 cout << "Choose: 1-ASA, 2-PSO, 3-MPSO, 4-DE, 5-SGA, 6-IslandModel(ring), Default-DiGMO: ";
57 cin >> choice;
59 switch (choice){
60 case 1:
62 //Experiment Settings
63 int NP = 1; //population size
64 int trials = 300; //number of trials
65 int niterTot = 10000; //generations per algorithm call
66 int niterRange = 20;
67 int niterTemp = 1;
68 double T0 = 10;
69 double Tf = T0/1000;
70 double Tcoeff = 0.85;
71 double StartStep =1;
73 //stopping criteria
74 int itermax = 120; //Maximum number of iterations allowed (i.e. output printed on the screen)
76 //Experiment Outputs
77 double mean = 0, dev= 0, max = 0, min = 200000000;
78 vector <double> results;
80 //Instanciate the algorithm
81 //Adaptive Simulated Annealing
82 ASAalgorithm ASA;
83 //ASA.initASA(niterTot,niterTemp,niterRange,LB.size(),T0,Tcoeff,StartStep, rng.next());
84 ASA.initASA(niterTot,LB.size(),T0,Tf, rng.next());
86 //Pruned bounds
88 for (int i=0;i<trials;i++){
89 cout << "\nTrial number #" << i+1 << endl;
90 //we create a random population
91 pop.createRandomPopulation(LB,UB,NP, rng);
92 pop.evaluatePopulation(problem);
93 int iter = 0;
95 time(&start);
96 while( iter < itermax){
97 iter ++;
98 //we print the best
99 cout << "Initial fitness: " << pop.extractBestIndividual().getFitness() << endl;
100 //we evolve it
101 start1=clock();
102 if (pop.extractBestIndividual().getFitness() < 5){
103 ASA.initASA(niterTot,LB.size(),1,0.01, rng.next());
105 pop = ASA.evolve(pop[0],problem);
106 end1=clock();
107 dif = (double)(end1-start1) / (double)CLOCKS_PER_SEC;
108 //we print the result
109 cout << "Final fitness: " << pop.extractBestIndividual().getFitness() << endl;
110 cout << "Worst fitness: " << pop.extractWorstIndividual().getFitness() << endl;
111 cout << "Mean : " << pop.evaluateMean() << endl;
112 cout << "Std : " << pop.evaluateStd() << endl;
113 cout << "\t\tSeconds elapsed: " << dif << endl;
115 time(&end);
116 results.push_back(pop.extractBestIndividual().getFitness());
117 dif = difftime(end,start);
118 cout << "\nSeconds elapsed: " << dif << endl<<endl;
119 for (int i=0;i<D;i++){
120 logfile << pop.extractBestIndividual()[i] << " ";
122 logfile << exp(-pop.extractBestIndividual().getFitness()) <<endl;
125 //evaluate experiment results
126 for (int i=0;i<trials;i++){
127 mean += results[i];
128 if (results[i] > max) max = results[i];
129 if (results[i] < min) min = results[i];
131 mean /= trials;
133 for (int i=0;i<trials;i++){
134 dev += (mean-results[i])*(mean-results[i]);
136 dev = sqrt(dev/trials);
138 for (int i=0;i<trials;i++){
139 cout << "\nTrial #" << i << ": " << results[i] << endl;
143 //print results
144 cout << "\nMean: " << mean << endl;
145 cout << "Std: " << dev << endl;
146 cout << "Max: " << max << endl;
147 cout << "Min: " << min << endl;
149 //Lines to test ASA
150 break;
152 case 2: //PSO sequential experiment
154 //Experiment Settings
155 int NP = 20; //population size
156 int trials = 100; //number of trials
157 int gen = 500; //generations per algorithm call
158 double omega = 0.6;
159 double eta1 = 2;
160 double eta2 = 2;
161 int vcoeff = 1;
163 //stopping criteria
164 int itermax = 120; //Maximum number of iterations allowed (i.e. output printed on the screen)
165 double stdmin = 1e-5; //Standard deviation of the population that determines a stop
167 //Experiment Outputs
168 double mean = 0, dev= 0, max = 0, min = 200000000;
169 vector <double> results;
171 //Instanciate the algorithm
172 PSOalgorithm PSO;
173 PSO.initPSO(gen,LB.size(),omega,eta1,eta2,vcoeff, rng.next());
175 for (int i=0;i<trials;i++){
176 cout << "\nTrial number #" << i+1 << endl;
177 //we create a random population
178 pop.createRandomPopulation(LB,UB,NP, rng);
179 pop.evaluatePopulation(problem);
180 int iter = 0;
182 time(&start);
183 while(iter < itermax){
184 iter ++;
185 //we print the best
186 cout << "Initial fitness: " << pop.extractBestIndividual().getFitness() << endl;
187 //we evolve it
188 start1=clock();
189 pop = PSO.evolve(pop,problem);
190 end1=clock();
191 dif = (double)(end1-start1) / (double)CLOCKS_PER_SEC;
192 //we print the result
193 cout << "Final fitness: " << pop.extractBestIndividual().getFitness() << endl;
194 cout << "Worst fitness: " << pop.extractWorstIndividual().getFitness() << endl;
195 cout << "Mean : " << pop.evaluateMean() << endl;
196 cout << "Std : " << pop.evaluateStd() << endl;
197 cout << "\t\tSeconds elapsed: " << dif << endl;
199 time(&end);
200 results.push_back(pop.extractBestIndividual().getFitness());
201 dif = difftime(end,start);
202 cout << "\nSeconds elapsed: " << dif << endl<<endl;
205 //evaluate experiment results
206 for (int i=0;i<trials;i++){
207 mean += results[i];
208 if (results[i] > max) max = results[i];
209 if (results[i] < min) min = results[i];
211 mean /= trials;
213 for (int i=0;i<trials;i++){
214 dev += (mean-results[i])*(mean-results[i]);
216 dev = sqrt(dev/trials);
218 for (int i=0;i<trials;i++){
219 cout << "\nTrial #" << i << ": " << results[i] << endl;
223 //print results
224 cout << "\nMean: " << mean << endl;
225 cout << "Std: " << dev << endl;
226 cout << "Max: " << max << endl;
227 cout << "Min: " << min << endl;
229 break;
231 case 3: //MPSO sequential experiment
233 //Experiment Settings
234 int NP = 20; //population size
235 int trials = 100; //number of trials
236 int gen = 500; //generations per algorithm call
237 double omega = 0.65;
238 double eta1 = 2.0;
239 double eta2 = 2.0;
240 int vcoeff = 1;
241 int nswarms = 4;
243 //stopping criteria
244 int itermax = 100; //Maximum number of iterations allowed (i.e. output printed on the screen)
245 double stdmin = 1e-5; //Standard deviation of the population that determines a stop
247 //Experiment Outputs
248 double mean = 0, dev= 0, max = 0, min = 200000000;
249 vector <double> results;
251 //Instanciate the algorithm
252 MPSOalgorithm MPSO;
253 MPSO.initMPSO(gen,LB.size(),omega,eta1,eta2,vcoeff,nswarms, rng.next());
255 for (int i=0;i<trials;i++){
256 cout << "\nTrial number #" << i+1 << endl;
257 //we create a random population
258 pop.createRandomPopulation(LB,UB,NP, rng);
259 pop.evaluatePopulation(problem);
260 int iter = 0;
262 time(&start);
263 while(iter < itermax){
264 iter ++;
265 //we print the best
266 cout << "Initial fitness: " << pop.extractBestIndividual().getFitness() << endl;
267 //we evolve it
268 start1=clock();
269 pop = MPSO.evolve(pop,problem);
270 end1=clock();
271 dif = (double)(end1-start1) / (double)CLOCKS_PER_SEC;
272 //we print the result
273 cout << "Final fitness: " << pop.extractBestIndividual().getFitness() << endl;
274 cout << "Worst fitness: " << pop.extractWorstIndividual().getFitness() << endl;
275 cout << "Mean : " << pop.evaluateMean() << endl;
276 cout << "Std : " << pop.evaluateStd() << endl;
277 cout << "\t\tSeconds elapsed: " << dif << endl;
279 time(&end);
280 results.push_back(pop.extractBestIndividual().getFitness());
281 dif = difftime(end,start);
282 cout << "\nSeconds elapsed: " << dif << endl<<endl;
285 //evaluate experiment results
286 for (int i=0;i<trials;i++){
287 mean += results[i];
288 if (results[i] > max) max = results[i];
289 if (results[i] < min) min = results[i];
291 mean /= trials;
293 for (int i=0;i<trials;i++){
294 dev += (mean-results[i])*(mean-results[i]);
296 dev = sqrt(dev/trials);
298 for (int i=0;i<trials;i++){
299 cout << "\nTrial #" << i << ": " << results[i] << endl;
303 //print results
304 cout << "\nMean: " << mean << endl;
305 cout << "Std: " << dev << endl;
306 cout << "Max: " << max << endl;
307 cout << "Min: " << min << endl;
309 break;
313 case 4: //Sequential Differential Evolution Experiment
315 //Experiment Settings
316 int NP = 20; //population size for each island
317 int trials = 100; //number of trials
318 int gen = 500; //generations per algorithm call
319 double F = 0.8; //F in DE
320 double CR = 0.8; //CR in DE
321 int strategy = 2; //DE startegy
323 //stopping criteria
324 int itermax = 120; //Maximum number of iterations allowed (i.e. output printed on the screen)
326 //Experiment Outputs
327 double mean = 0, dev= 0, max = 0, min = 200000000;
328 vector <double> results;
330 //Instanciate the algorithm
331 DEalgorithm DE;
332 DE.initDE(gen,LB.size(),F,CR,strategy, rng.next());
334 for (int i=0;i<trials;i++){
335 cout << "\nTrial number #" << i+1 << endl;
336 //we create a random population
339 pop.createRandomPopulation(LB,UB,NP, rng);
340 pop.evaluatePopulation(problem);
341 int iter = 0;
343 time(&start);
344 while( iter < itermax){
345 iter ++;
346 //we print the best
347 cout << "Initial fitness: " << pop.extractBestIndividual().getFitness() << endl;
348 //we evolve it
349 start1=clock();
350 pop = DE.evolve(pop,problem);
351 end1=clock();
352 dif = (double)(end1-start1) / (double)CLOCKS_PER_SEC;
353 //we print the result
354 cout << "Final fitness: " << pop.extractBestIndividual().getFitness() << endl;
355 cout << "Worst fitness: " << pop.extractWorstIndividual().getFitness() << endl;
356 cout << "Mean : " << pop.evaluateMean() << endl;
357 cout << "Std : " << pop.evaluateStd() << endl;
358 cout << "\t\tSeconds elapsed: " << dif << endl;
360 time(&end);
361 //if (iter<itermax){
362 //results.push_back(iter*NP*gen);
363 results.push_back(pop.extractBestIndividual().getFitness());
365 dif = difftime(end,start);
366 cout << "\nSeconds elapsed: " << dif << endl<<endl;
367 for (int i=0;i<D;i++){
368 logfile << pop.extractBestIndividual()[i] << " ";
370 logfile << exp(-pop.extractBestIndividual().getFitness()) <<endl;
373 //evaluate experiment results
374 for (unsigned int i=0;i<results.size();i++){
375 mean += results[i];
376 if (results[i] > max) max = results[i];
377 if (results[i] < min) min = results[i];
379 mean /= results.size();
381 for (unsigned int i=0;i<results.size();i++){
382 dev += (mean-results[i])*(mean-results[i]);
384 dev = sqrt(dev/results.size());
386 for (unsigned int i=0;i<results.size();i++){
387 cout << "\nTrial #" << i << ": " << results[i] << endl;
390 //print results
391 cout << "\nMean: " << mean << endl;
392 cout << "Std: " << dev << endl;
393 cout << "Max: " << max << endl;
394 cout << "Min: " << min << endl;
395 cout << "Success: " << results.size() << endl;
397 break;
401 case 5: //SGA experiment
403 //Experiment Settings
404 int NP = 20; //population size
405 int trials = 100; //number of trials
406 int gen = 500; //generations per algorithm call
407 double CR = 0.7;
408 double M = 0.2;
409 int insert_best = 1;
411 //stopping criteria
412 int itermax = 120; //Maximum number of iterations allowed (i.e. output printed on the screen)
414 //Experiment Outputs
415 double mean = 0, dev= 0, max = 0, min = 200000000;
416 vector <double> results;
418 //Instanciate the algorithm
419 //Simple Genetic Algorithm
420 SGAalgorithm SGA;
421 SGA.initSGA(gen,LB.size(),CR,M,insert_best, rng.next());
423 for (int i=0;i<trials;i++){
424 cout << "\nTrial number #" << i+1 << endl;
425 //we create a random population
426 pop.createRandomPopulation(LB,UB,NP, rng);
427 pop.evaluatePopulation(problem);
428 int iter = 0;
430 time(&start);
431 while( iter < itermax){
432 iter ++;
433 //we print the best
434 cout << "Initial fitness: " << pop.extractBestIndividual().getFitness() << endl;
435 //we evolve it
436 start1=clock();
437 pop = SGA.evolve(pop,problem);
438 end1=clock();
439 dif = (double)(end1-start1) / (double)CLOCKS_PER_SEC;
440 //we print the result
441 cout << "Final fitness: " << pop.extractBestIndividual().getFitness() << endl;
442 cout << "Worst fitness: " << pop.extractWorstIndividual().getFitness() << endl;
443 cout << "Mean : " << pop.evaluateMean() << endl;
444 cout << "Std : " << pop.evaluateStd() << endl;
445 cout << "\t\tSeconds elapsed: " << dif << endl;
447 time(&end);
448 results.push_back(pop.extractBestIndividual().getFitness());
449 dif = difftime(end,start);
450 cout << "\nSeconds elapsed: " << dif << endl<<endl;
453 //evaluate experiment results
454 for (int i=0;i<trials;i++){
455 mean += results[i];
456 if (results[i] > max) max = results[i];
457 if (results[i] < min) min = results[i];
459 mean /= trials;
461 for (int i=0;i<trials;i++){
462 dev += (mean-results[i])*(mean-results[i]);
464 dev = sqrt(dev/trials);
466 for (int i=0;i<trials;i++){
467 cout << "\nTrial #" << i << ": " << results[i] << endl;
471 //print results
472 cout << "\nMean: " << mean << endl;
473 cout << "Std: " << dev << endl;
474 cout << "Max: " << max << endl;
475 cout << "Min: " << min << endl;
477 //Lines to test SGA
478 break;
480 case 6: //Parallel asynchronous island model
483 //Experiment Settings
484 int NP = 1; //population size for each island
485 int trials = 20; //number of trials
486 int gen = 500; //generations per algorithm call
487 double F = 0.8; //F in DE
488 double CR = 0.8; //CR in DE
489 int strategy = 2; //DE startegy
490 int islandsN = 1; //Number of Islands
492 //stopping criteria
493 int itermax = 120; //Maximum number of iterations allowed (i.e. output printed on the screen)
495 //Experiment Outputs
496 double mean = 0, dev= 0, max = 0, min = 200000000;
497 vector <double> results;
499 //Main cycle creating threads
500 for (int i=0;i<trials;i++){
501 cout << "\nTrial number #" << i+1 << endl;
502 //We create a random population in each island (this is done by the main thread - i.e. no parallelization here)
503 vector<Population> IslandPop(islandsN);
504 vector<GOProblem*> parallelProblems(islandsN);
505 for (int i=0;i<islandsN;i++){
506 parallelProblems[i] = new problem_type();
508 IslandPop[i].createRandomPopulation(LB,UB,NP, rng);
509 IslandPop[i].evaluatePopulation(*parallelProblems[i]);
512 //We instanciate the objects needed for pthreads allocating memory for the threads array
513 pthread_t *threads;
514 threads = new pthread_t [islandsN];
515 pthread_mutex_t mutex;
516 pthread_cond_t exitcond;
517 pthread_mutex_init(&mutex, NULL);
518 pthread_cond_init (&exitcond, NULL);
520 //We allocate memory for the isActive array containing the status ofeach thread and we initialise it to false (no threads opened)
521 bool *isActive;
522 isActive = new bool[islandsN];
523 for (int i=0;i<islandsN;i++) isActive[i]=false; //all threads are inactive
525 //We allocate memory and initialise the data threadParam array containing the information to be passed to the different threads
526 threadParam* data;
527 data = new threadParam [islandsN];
528 for (int i=0;i<islandsN;i++){
529 data[i].threadID = i;
531 data[i].problem = parallelProblems[i];
532 data[i].Ptr_pop = &IslandPop[i]; //Each Island has a different population
535 data[i].NP = NP;
536 data[i].generations = gen;
538 //Initialise DE specific data
539 data[i].strategy = 1;
540 data[i].F = F;
541 data[i].CR = CR;
543 //Initialise PSO/MPSO specific data
544 data[i].omega = 0.65;
545 data[i].eta1 = 2.0;
546 data[i].eta2 = 2.0;
547 data[i].vcoeff = 1;
548 data[i].nswarms = 4;
550 //Initialise SGA specific data
551 data[i].CRsga = 0.95;
552 data[i].M = 0.2;
553 data[i].insert_best =1;
555 //Initialise ASA specific data
556 data[i].Ts = 1;
557 data[i].Tf = data[i].Ts/1000;
558 data[i].isActive = &isActive[i];
559 data[i].TPmutex = &mutex;
560 data[i].exit = &exitcond;
562 data[i].Ptr_log = &logfile;
565 int iter=0;
566 int rc;
567 int IslandType = 0;
568 double loweststd = 1000000;
570 pthread_mutex_lock (&mutex);
571 time(&start);
572 while(iter < itermax){
573 for (int i=0;i<islandsN;i++){
574 if ( !*(data[i].isActive) ){
575 //Create again the i-th thread to simulate an Island
576 IslandType = 3;
577 if (IslandType == 0){
578 data[i].randomSeed = rng.next();
579 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;
580 rc = pthread_create(&threads[i], NULL, PSOthread, (void *)&data[i]);
582 else if (IslandType == 1){
583 data[i].randomSeed = rng.next();
584 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;
585 rc = pthread_create(&threads[i], NULL, MPSOthread, (void *)&data[i]);
587 else if (IslandType == 2){
588 data[i].randomSeed = rng.next();
589 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;
590 rc = pthread_create(&threads[i], NULL, SGAthread, (void *)&data[i]);
592 else if (IslandType == 3){
593 data[i].randomSeed = rng.next();
594 data[i].generations=10000;
595 data[i].NP = 1;
596 cout << "\t\t\tASA:\t\t Ts: "<< data[i].Ts << "\t\tTf: " << data[i].Tf << "\t\tGenerations: " << data[i].generations << endl;
597 rc = pthread_create(&threads[i], NULL, ASAthread, (void *)&data[i]);
599 else {
600 data[i].randomSeed = rng.next();
601 data[i].strategy = strategy;
602 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;
603 rc = pthread_create(&threads[i], NULL, DEthread, (void *)&data[i]);
605 if (rc){
606 //Problem creating the thread
607 printf("ERROR; return code from pthread_create() is %d\n", rc);
608 exit(-1);
610 else{
611 //Thread Successfully Created
612 iter += 1;
613 *(data[i].isActive) = true;
614 //thread is detached as it will never be joined
615 //(on OSx Leopard this avoids that at a certain point
616 //threads cannot be created anymore resulting in rc=35)
617 pthread_detach(threads[i]);
620 //evaluate highest standard deviation across Islands
621 //loweststd = IslandPop[0].evaluateStd();
622 loweststd = IslandPop[0].extractBestIndividual().getFitness();
623 for (int i2=1;i2<islandsN;i2++){
624 if (loweststd < IslandPop[i2].extractBestIndividual().getFitness()) loweststd = IslandPop[i2].extractBestIndividual().getFitness();
627 //log islands best and std
628 for (int i2=0;i2<islandsN;i2++){
629 cout << "CPU#:" << i2 << ": " << IslandPop[i2].extractBestIndividual().getFitness() << " " << IslandPop[i2].evaluateStd() << endl;
631 cout << "HighestStd: " << loweststd << endl;
632 cout << "Iter: " << iter+1 << endl;
633 cout << "\nmain():" << endl << "\t\t\tcreating thread, ID " << i << endl;
635 //ring topology migration
636 if (Pk::nextDouble(rng) < 0.2){
637 IslandPop[(i+1) % islandsN].substituteIndividual(IslandPop[i].extractBestIndividual(), rng.next() % data[i].NP);
642 pthread_cond_wait(&exitcond, &mutex);
644 pthread_mutex_unlock (&mutex);
645 //The main cycle has finished: we wait for all threads to finish
646 for (int i=0; i<islandsN;i++){
647 while (*data[i].isActive); //infinite loop if a thread never ends
650 //we clean the thread objects and deallocate memory
651 pthread_mutex_destroy(&mutex);
652 pthread_cond_destroy(&exitcond);
653 delete[] data;
654 delete[] threads;
655 delete[] isActive;
656 time(&end);
657 dif = difftime(end,start);
658 cout << "\nSeconds elapsed: " << dif << endl<<endl;
660 double res=IslandPop[0].extractBestIndividual().getFitness();
661 for (int i=1;i<islandsN;i++){
662 if (res > IslandPop[i].extractBestIndividual().getFitness()) res = IslandPop[i].extractBestIndividual().getFitness();
664 //if (iter<itermax){
665 results.push_back(res);
668 for (int i = 0; i < islandsN; i++) {
669 delete parallelProblems[i];
673 //evaluate experiment results
674 for (unsigned int i=0;i<results.size();i++){
675 mean += results[i];
676 if (results[i] > max) max = results[i];
677 if (results[i] < min) min = results[i];
679 mean /= results.size();
681 for (unsigned int i=0;i<results.size();i++){
682 dev += (mean-results[i])*(mean-results[i]);
684 dev = sqrt(dev/results.size());
686 for (unsigned int i=0;i<results.size();i++){
687 cout << "\nTrial #" << i << ": " << results[i] << endl;
690 //print results
691 cout << "\nMean: " << mean << endl;
692 cout << "Std: " << dev << endl;
693 cout << "Max: " << max << endl;
694 cout << "Min: " << min << endl;
695 cout << "Success: " << results.size() << endl;
697 break;
699 case 9:
701 Individual x;
702 x.createRandomIndividual(LB,UB,rng);
703 cout << x << endl;
704 x[0]=666;
705 cout << x << endl;
707 Population pop;
708 pop.createRandomPopulation(LB,UB,5,rng);
709 pop.evaluatePopulation(problem);
710 cout << pop[3] << endl;
711 pop[3][0]=666;
712 cout << pop[3] << endl;
713 cout << pop << endl;
716 break;
718 default:
720 int NUM_THREADS=2;
721 //We create a random population and evaluate its fitness (this is done by the main thread - i.e. no parallelization here)
722 pop.createRandomPopulation(LB,UB,20*5, rng);
723 pop.evaluatePopulation(problem);
725 //We instanciate the objects needed for pthreads allocating memory for the threads array
726 pthread_t *threads;
727 threads = new pthread_t [NUM_THREADS];
728 //pthread_attr_t attr;
729 //pthread_attr_init(&attr);
730 //pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
731 pthread_mutex_t mutex;
732 pthread_cond_t exitcond;
733 pthread_mutex_init(&mutex, NULL);
734 pthread_cond_init (&exitcond, NULL);
739 //We allocate memory for the isActive array containing the status ofeach thread and we initialise it to false (no threads opened)
740 bool *isActive;
741 isActive = new bool[NUM_THREADS]; //all threads are inactive
742 for (int i=0;i<NUM_THREADS;i++) {isActive[i]=false;}
744 //We allocate memory and initialise the data threadParam array containing the information to be passed to the different threads
745 threadParam *data;
746 data = new threadParam [NUM_THREADS];
747 for (int i=0;i<NUM_THREADS;i++){
748 data[i].threadID = i;
750 data[i].problem = &problem;
751 data[i].Ptr_pop = &pop;
753 data[i].generations = 500;
755 //Initialise DE specific data
756 data[i].strategy = 2;
757 data[i].F = 0.8;
758 data[i].CR = 0.8;
760 //Initialise PSO specific data
761 data[i].omega = 0.5;
762 data[i].eta1 = 2.0;
763 data[i].eta2 = 2.0;
764 data[i].vcoeff = 1000;
766 data[i].isActive = &isActive[i];
767 data[i].TPmutex = &mutex;
768 data[i].exit = &exitcond;
770 data[i].Ptr_log = &logfile;
773 //Main cycle creating threads
774 int globalCount=0;
775 int count1=0,count2=0;
776 int rc;
777 int algorithmchoice = 0;
779 pthread_mutex_lock (&mutex);
780 time(&start);
781 while (globalCount<120){
782 //while(pop.extractBestIndividual().getFitness()!=0){
783 for (int i=0;i<NUM_THREADS;i++){
784 if ( !*(data[i].isActive) ){
785 cout << "main():" << endl << "\t\t\tcreating thread, ID " << i << endl;
786 algorithmchoice = 4;//r250()%10;
787 if (algorithmchoice == 0){
788 count1++;
789 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;
790 rc = pthread_create(&threads[i], NULL, PSOthread, (void *)&data[i]);
792 else {
793 data[i].strategy = i+1;
794 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;
795 rc = pthread_create(&threads[i], NULL, DEthread, (void *)&data[i]);
796 count2++;
799 if (rc){
800 printf("ERROR; return code from pthread_create() is %d\n", rc);
801 exit(-1);
803 else{
804 globalCount += 1;
805 *(data[i].isActive) = true;
809 pthread_cond_wait(&exitcond, &mutex);
811 pthread_mutex_unlock (&mutex);
813 //The main cycle has finished: we wait for all threads to finish
814 for (int i=0; i<NUM_THREADS;i++){
815 pthread_join(threads[i],NULL);
818 //we clean the thread objects and deallocate memory
819 pthread_mutex_destroy(&mutex);
820 //pthread_attr_destroy(&attr);
821 pthread_cond_destroy(&exitcond);
822 delete[] data;
823 delete[] threads;
824 delete[] isActive;
825 time(&end);
826 dif = difftime(end,start);
827 cout << "\nSeconds elapsed: " << dif << endl<<endl;
828 cout << "\nCount1: " << count1 << endl;
829 cout << "\nCount2: " << count2 << endl;
832 break;
833 }//end case
835 } //end while
838 //The following lines are commented out as they implement exactly the DiGMO random strategy in a random
839 //way. This creates a very unefficient cooperation between the algorithms as it does not have the implicit
840 //learning of the best strategy. This is the mechanism that allow, in the distributed version of the algorithm,
841 //the same individual to be evolved by different algorithms and only the most succesful one to be selected
843 //It seems that the reinsertion strategy (only improved individuals substitute their old versions) together with
844 //the contemporary evolution of the same individuals is key to the efficiency of algorithm cooperation (mimicking co-evolution)
845 //In a sequential version this can be enforced by evolving with DE, PSO and SA and only at the end perform reinsertion
846 //as in the uncommented lines above
848 /*algorithmchoice = r250()%3;
849 if ( algorithmchoice == 0 ){
850 deme=pop.extractRandomDeme(20,picks);
851 //we print the best
852 cout << "Using DE" << endl;
853 cout << "Initial fitness: " << deme.extractBestIndividual().getFitness() << endl;
854 //DE.initDE(50,LB.size(),dr250(),dr250(),(int)dr250()*11+1);
855 deme = DE.evolve(deme,&rosenbrock,LB,UB);
858 else if ( algorithmchoice == 1 ){
859 deme=pop.extractRandomDeme(20,picks);
860 //deme.resetVelocities(LB,UB);
861 //we print the best
862 cout << "Using PSO" << endl;
863 cout << "Initial fitness: " << deme.extractBestIndividual().getFitness() << endl;
864 //PSO.initPSO(500,LB.size(),(dr250()+1)/2,4.0*dr250(),4.0*dr250(),(int)dr250()*10000);
865 deme = PSO.evolve(deme,&rosenbrock,LB,UB);
868 else if ( algorithmchoice == 2 ){
869 deme=pop.extractRandomDeme(1,picks);
870 //deme.resetVelocities(LB,UB);
871 //we print the best
872 cout << "Using ASA" << endl;
873 cout << "Initial fitness: " << deme.extractBestIndividual().getFitness() << endl;
874 //ASA.initASA(10000,1,8,LB.size(),dr250(),dr250(),1.0);
875 deme = ASA.evolve(deme[0],&rosenbrock,LB,UB);
878 //we print the result
879 cout << "Final fitness: " << deme.extractBestIndividual().getFitness() << endl;
880 //we insert it in the main population
881 pop.insertDeme(deme,picks);
882 picks.clear();*/
885 cout << "\nBest fitness found: " << pop.extractBestIndividual().getFitness() << endl;
887 return 0;