Création d'un compte pour un collaborateur extérieur au laboratoire depuis l'intranet ICube : https://intranet.icube.unistra.fr/fr/labs/member/profile

CUDA.tpl 49.5 KB
Newer Older
maitre's avatar
maitre committed
1
2
3
4
5
6
7
8
9
\TEMPLATE_START/**
 This is program entry for CUDA template for EASEA

*/
\ANALYSE_PARAMETERS
using namespace std;
#include <iostream>
#include "EASEATools.hpp"
#include "EASEAIndividual.hpp"
maitre's avatar
maitre committed
10
#include <time.h>
maitre's avatar
maitre committed
11
12
13

RandomGenerator* globalRandomGenerator;

maitre's avatar
maitre committed
14

maitre's avatar
maitre committed
15
16
int main(int argc, char** argv){

maitre's avatar
maitre committed
17
18
19
20
21

  parseArguments("EASEA.prm",argc,argv);

  size_t parentPopulationSize = setVariable("popSize",\POP_SIZE);
  size_t offspringPopulationSize = setVariable("nbOffspring",\OFF_SIZE);
maitre's avatar
maitre committed
22
23
24
25
  float pCrossover = \XOVER_PROB;
  float pMutation = \MUT_PROB;
  float pMutationPerGene = 0.05;

maitre's avatar
maitre committed
26
27
28
29
  time_t seed = setVariable("seed",time(0));
  globalRandomGenerator = new RandomGenerator(seed);

  std::cout << "Seed is : " << seed << std::endl;
maitre's avatar
maitre committed
30
31
32
33
34

  SelectionOperator* selectionOperator = new \SELECTOR;
  SelectionOperator* replacementOperator = new \RED_FINAL;
  float selectionPressure = \SELECT_PRM;
  float replacementPressure = \RED_FINAL_PRM;
maitre's avatar
maitre committed
35
36
  string outputfile = setVariable("outputfile","");
  string inputfile = setVariable("inputfile","");
maitre's avatar
maitre committed
37

maitre's avatar
maitre committed
38
  EASEAInit(argc,argv);
maitre's avatar
maitre committed
39
40
    
  EvolutionaryAlgorithm ea(parentPopulationSize,offspringPopulationSize,selectionPressure,replacementPressure,
maitre's avatar
maitre committed
41
			   selectionOperator,replacementOperator,pCrossover, pMutation, pMutationPerGene,outputfile,inputfile);
maitre's avatar
maitre committed
42

maitre's avatar
maitre committed
43
  StoppingCriterion* sc = new GenerationalCriterion(&ea,setVariable("nbGen",\NB_GEN));
maitre's avatar
maitre committed
44
45
46
47
48
49
50
51
52
53
  ea.addStoppingCriterion(sc);
  Population* pop = ea.getPopulation();


  ea.runEvolutionaryLoop();

  EASEAFinal(pop);

  delete pop;
  delete sc;
maitre's avatar
maitre committed
54
55
56
57
  delete selectionOperator;
  delete replacementOperator;
  delete globalRandomGenerator;

maitre's avatar
maitre committed
58
59
60
61
62
63
64
65

  return 0;
}


\START_CUDA_GENOME_CU_TPL
#include "EASEAIndividual.hpp"
#include "EASEAUserClasses.hpp"
maitre's avatar
maitre committed
66
67
68
69
70
71
#include <string.h>
#include <fstream>
#include <sys/time.h>
#include "EASEATools.hpp"

#define STD_TPL
maitre's avatar
maitre committed
72
73
74
75
76
77
78
79
80
81

extern RandomGenerator* globalRandomGenerator;

\INSERT_USER_DECLARATIONS
\ANALYSE_USER_CLASSES

\INSERT_USER_FUNCTIONS

\INSERT_INITIALISATION_FUNCTION
\INSERT_FINALIZATION_FUNCTION
maitre's avatar
maitre committed
82
\INSERT_GENERATION_FUNCTION
maitre's avatar
maitre committed
83
84
85
86
87

void EASEAFinal(Population* pop){
  \INSERT_FINALIZATION_FCT_CALL
}

maitre's avatar
maitre committed
88
89
90
91
92
void EASEAInit(int argc, char** argv){
  \INSERT_INIT_FCT_CALL
}


maitre's avatar
maitre committed
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
using namespace std;

RandomGenerator* Individual::rg;

Individual::Individual(){
  \GENOME_CTOR 
  \INSERT_EO_INITIALISER
  valid = false;
}


Individual::~Individual(){
  \GENOME_DTOR
}


float Individual::evaluate(){
  if(valid)
    return fitness;
  else{
    valid = true;
    \INSERT_EVALUATOR
  } 
}

maitre's avatar
maitre committed
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144

/**
   This function allows to acces to the Individual stored in cudaBuffer as a standard
   individual.
*/
__device__ __host__ inline Individual* INDIVIDUAL_ACCESS(void* buffer,size_t id){
  return ((Individual*)(((char*)buffer)+(\GENOME_SIZE+sizeof(void*))*id));
}


__device__ float cudaEvaluate(void* devBuffer, size_t id){
  \INSERT_CUDA_EVALUATOR
}




void Individual::copyToCudaBuffer(void* buffer, size_t id){
  
  DEBUG_PRT("%p\n",(char*)this+sizeof(Individual*));
  DEBUG_PRT("%p\n",&this->sigma);
  DEBUG_PRT("%lu\n",id);
  
  memcpy(((char*)buffer)+(\GENOME_SIZE+sizeof(Individual*))*id,((char*)this),\GENOME_SIZE+sizeof(Individual*));
  
}

maitre's avatar
maitre committed
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
Individual::Individual(const Individual& genome){

  // ********************
  // Problem specific part
  \COPY_CTOR
  
  // ********************
  // Generic part
  this->valid = genome.valid;
  this->fitness = genome.fitness;
}


Individual* Individual::crossover(Individual** ps){
  // ********************
  // Generic part  
  Individual parent1(*this);
  Individual parent2(*ps[0]);
  Individual child1(*this);

maitre's avatar
maitre committed
165
  //DEBUG_PRT("Xover");
maitre's avatar
maitre committed
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
/*   cout << "p1 : " << parent1 << endl; */
/*   cout << "p2 : " << parent2 << endl; */

  // ********************
  // Problem specific part
  \INSERT_CROSSOVER

    child1.valid = false;
/*   cout << "child1 : " << child1 << endl; */
  return new Individual(child1);
}


void Individual::printOn(std::ostream& os) const{
  \INSERT_DISPLAY
}

std::ostream& operator << (std::ostream& O, const Individual& B) 
{ 
  // ********************
  // Problem specific part
  O << "\nIndividual : "<< std::endl;
  O << "\t\t\t";
  B.printOn(O);
    
  if( B.valid ) O << "\t\t\tfitness : " << B.fitness;
  else O << "fitness is not yet computed" << std::endl;
  return O; 
} 


size_t Individual::mutate( float pMutationPerGene ){
  this->valid=false;
  // ********************
  // Problem specific part
  \INSERT_MUTATOR  
}

maitre's avatar
maitre committed
204
205
206

size_t Individual::sizeOfGenome=\GENOME_SIZE;

maitre's avatar
maitre committed
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
/* ****************************************
   EvolutionaryAlgorithm class
****************************************/

/**
   @DEPRECATED This contructor will be deleted. It was for test only, because it
   is too much constrained (default selection/replacement operator)
 */
EvolutionaryAlgorithm::EvolutionaryAlgorithm( size_t parentPopulationSize,
					      size_t offspringPopulationSize,
					      float selectionPressure, float replacementPressure,
					      float pCrossover, float pMutation, 
					      float pMutationPerGene){
  RandomGenerator* rg = globalRandomGenerator;


  SelectionOperator* so = new MaxTournament(rg);
  SelectionOperator* ro = new MaxTournament(rg);
  
  Individual::initRandomGenerator(rg);
  Population::initPopulation(so,ro,selectionPressure,replacementPressure);
  
  this->population = new Population(parentPopulationSize,offspringPopulationSize,
				    pCrossover,pMutation,pMutationPerGene,rg);

  this->currentGeneration = 0;

  this->reduceParents = 0;
  this->reduceOffsprings = 0;


}

EvolutionaryAlgorithm::EvolutionaryAlgorithm( size_t parentPopulationSize,
					      size_t offspringPopulationSize,
					      float selectionPressure, float replacementPressure,
					      SelectionOperator* selectionOperator, SelectionOperator* replacementOperator,
					      float pCrossover, float pMutation, 
maitre's avatar
maitre committed
245
					      float pMutationPerGene, string& outputfile, string& inputfile){
maitre's avatar
maitre committed
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262

  RandomGenerator* rg = globalRandomGenerator;

  SelectionOperator* so = selectionOperator;
  SelectionOperator* ro = replacementOperator;
  
  Individual::initRandomGenerator(rg);
  Population::initPopulation(so,ro,selectionPressure,replacementPressure);
  
  this->population = new Population(parentPopulationSize,offspringPopulationSize,
				    pCrossover,pMutation,pMutationPerGene,rg);

  this->currentGeneration = 0;

  this->reduceParents = 0;
  this->reduceOffsprings = 0;

maitre's avatar
maitre committed
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
  if( outputfile.length() )
    this->outputfile = new string(outputfile);
  else
    this->outputfile = NULL;

  if( inputfile.length() )
    this->inputfile = new std::string(inputfile);
  else
    this->inputfile = NULL;
  


}

// do the repartition of data accross threads
__global__ void 
cudaEvaluatePopulation(void* d_population, size_t popSize, float* d_fitnesses){

  size_t id = (blockDim.x*blockIdx.x)+threadIdx.x;  // id of the individual computed by this thread

  // escaping for the last block
  if(blockIdx.x == (gridDim.x-1)) if( id >= popSize ) return;

  void* indiv = ((char*)d_population)+id*(\GENOME_SIZE+sizeof(Individual*)); // compute the offset of the current individual

  d_fitnesses[id] = cudaEvaluate(indiv,id);

}


#define NB_MP 16
inline size_t
partieEntiereSup(float E){
  int fl = floor(E);
  if( fl == E )
    return E;
  else
    return floor(E)+1;
}

inline int 
puissanceDeuxSup(float n){
  int tmp = 2;
  while(tmp<n)tmp*=2;
  return tmp;
}


maitre's avatar
maitre committed
311

maitre's avatar
maitre committed
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
bool
repartition(size_t popSize, size_t* nbBlock, size_t* nbThreadPB, size_t* nbThreadLB, 
	    size_t nbMP, size_t maxBlockSize){
  
  (*nbThreadLB) = 0;
  
  if( ((float)popSize / (float)nbMP) <= maxBlockSize ){
    //la population repartie sur les MP tient dans une bloc par MP
    (*nbThreadPB) = partieEntiereSup( (float)popSize/(float)nbMP);
    (*nbBlock) = popSize/(*nbThreadPB);
    if( popSize%nbMP != 0 ){
      //on fait MP-1 block de equivalent et un plus petit
      (*nbThreadLB) = popSize - (*nbThreadPB)*(*nbBlock);
    }
  }
  else{
    //la population est trop grande pour etre repartie sur les MP
    //directement
    //(*nbBlock) = partieEntiereSup( (float)popSize/((float)maxBlockSize*NB_MP));
    (*nbBlock) = puissanceDeuxSup( (float)popSize/((float)maxBlockSize*NB_MP));
    (*nbBlock) *= NB_MP;
    (*nbThreadPB) = popSize/(*nbBlock);
    if( popSize%maxBlockSize!=0){
      (*nbThreadLB) = popSize - (*nbThreadPB)*(*nbBlock);
      
      // Le rest est trop grand pour etre place dans un seul block (c'est possible uniquement qd 
      // le nombre de block depasse maxBlockSize 
      while( (*nbThreadLB) > maxBlockSize ){
	//on augmente le nombre de blocs principaux jusqu'a ce que nbthreadLB retombe en dessous de maxBlockSize
	//(*nbBlock) += nbMP;
	(*nbBlock) *= 2;
 	(*nbThreadPB) = popSize/(*nbBlock);
	(*nbThreadLB) = popSize - (*nbThreadPB)*(*nbBlock);
      }
    }
  }
  
  if((((*nbBlock)*(*nbThreadPB) + (*nbThreadLB))  == popSize) 
     && ((*nbThreadLB) <= maxBlockSize) && ((*nbThreadPB) <= maxBlockSize))
    return true;
  else 
    return false;
}



void EvolutionaryAlgorithm::cudaEvaluate(void* buffer, size_t actualPopulationSize){
  float* fitnesses = new float[actualPopulationSize];
  void* allocatedDeviceBuffer;
  float* deviceFitness;
  cudaError_t lastError;
  lastError = cudaMalloc(&allocatedDeviceBuffer,actualPopulationSize*(\GENOME_SIZE+sizeof(Individual*)));
  DEBUG_PRT("%s",cudaGetErrorString(lastError));
  lastError = cudaMalloc(((void**)&deviceFitness),actualPopulationSize*sizeof(float));
  DEBUG_PRT("%s",cudaGetErrorString(lastError));
  
  size_t nbBlock,nbThreadLB,nbThreadPB;
    
  //compute the repartition over MP and SP
  repartition(actualPopulationSize, &nbBlock, &nbThreadPB, &nbThreadLB,16, 192);
  dim3 dimBlock(nbThreadPB);
  
  
  dim3 dimGrid;
  if( nbThreadLB )
    dimGrid.x = (nbBlock+1);
  else
    dimGrid.x = (nbBlock);


  cudaEvaluatePopulation<<< dimGrid, dimBlock>>>(allocatedDeviceBuffer,actualPopulationSize,deviceFitness);
  lastError = cudaGetLastError();
  DEBUG_PRT("%s",cudaGetErrorString(lastError));
  
  
maitre's avatar
maitre committed
387
388
389
390
391
392
393
}

void EvolutionaryAlgorithm::addStoppingCriterion(StoppingCriterion* sc){
  this->stoppingCriteria.push_back(sc);
}

void EvolutionaryAlgorithm::runEvolutionaryLoop(){
maitre's avatar
maitre committed
394
395
396
397
398
399
400
401
402
403
404
405
406
  std::vector<Individual*> tmpVect;

/*   if( inputfile ){ */
/*     DEBUG_PRT("Loading initial population from file : %s",inputfile->c_str()); */
/*     std::ifstream ifs("essai.out"); */
/*     DEBUG_PRT("parent population size in ea %d",population->parentPopulationSize); */
/*     //population->parents = new Individual*[population->parentPopulationSize]; */
/*     boost::archive::text_iarchive ia(ifs); */

/*     //ia >> *population; */
/*     population->syncInVector(); */
/*     //ia >> *population; */
/*   } */
maitre's avatar
maitre committed
407
408

  std::cout << "Parent's population initializing "<< std::endl;
maitre's avatar
maitre committed
409
410
411
  this->population->initializeCudaParentPopulation();  
  cudaEvaluate(population->cudaParentBuffer,population->actualParentPopulationSize);

maitre's avatar
maitre committed
412
  std::cout << *population << std::endl;
maitre's avatar
maitre committed
413
414
415
416
417
418
419
420
421
422
423

  DEBUG_PRT("Genome size is %lu",Individual::sizeOfGenome);


  DECLARE_TIME(eval);
  struct timeval begin,accuEval;
  gettimeofday(&begin,NULL);
  accuEval.tv_sec = 0;
  accuEval.tv_usec = 0;


maitre's avatar
maitre committed
424
425
426
427
  
  while( this->allCriteria() == false ){    

    population->produceOffspringPopulation();
maitre's avatar
maitre committed
428
429

    TIME_ST(eval);
maitre's avatar
maitre committed
430
    population->evaluateOffspringPopulation();
maitre's avatar
maitre committed
431
432
433
434
435
    TIME_END(eval);

    SHOW_TIME(eval);
    timeradd(&accuEval,&eval_res,&accuEval);

maitre's avatar
maitre committed
436
    
maitre's avatar
maitre committed
437

maitre's avatar
maitre committed
438
439
440
441
442
443
444
    if(reduceParents)
      population->reduceParentPopulation(reduceParents);
    
    if(reduceOffsprings)
      population->reduceOffspringPopulation(reduceOffsprings);
    
    population->reduceTotalPopulation();
maitre's avatar
maitre committed
445
446
447
448
     
    \INSERT_GEN_FCT_CALL    

     showPopulationStats(begin);
maitre's avatar
maitre committed
449
450
451
    currentGeneration += 1;
  }  
  population->sortParentPopulation();
maitre's avatar
maitre committed
452
  //std::cout << *population << std::endl;
maitre's avatar
maitre committed
453
  std::cout << "Generation : " << currentGeneration << std::endl;
maitre's avatar
maitre committed
454
455
456
457
458
459
460
461
462
463
464
  SHOW_SIMPLE_TIME(accuEval);

/*   if( outputfile ){ */
/*     DEBUG_PRT("Dumping final population to file : %s",outputfile->c_str()); */
/*     std::ofstream ofs(outputfile->c_str()); */
/*     boost::archive::text_oarchive oa(ofs); */
/*     population->syncOutVector(); */
/*     oa << *population ; */
    
/*   } */

maitre's avatar
maitre committed
465
466
467
}


maitre's avatar
maitre committed
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
void EvolutionaryAlgorithm::showPopulationStats(struct timeval beginTime){

  float currentAverageFitness=0.0;
  float currentSTDEV=0.0;

  //Calcul de la moyenne et de l'ecart type
  population->Best=population->parents[0];

  for(size_t i=0; i<population->parentPopulationSize; i++){
    currentAverageFitness+=population->parents[i]->getFitness();
#if \MINIMAXI
    if(population->parents[i]->getFitness()>population->Best->getFitness())
#else
    if(population->parents[i]->getFitness()<population->Best->getFitness())
#endif
      population->Best=population->parents[i];
  }

  currentAverageFitness/=population->parentPopulationSize;

  for(size_t i=0; i<population->parentPopulationSize; i++){
    currentSTDEV+=(population->parents[i]->getFitness()-currentAverageFitness)*(population->parents[i]->getFitness()-currentAverageFitness);
  }
  currentSTDEV/=population->parentPopulationSize;
  currentSTDEV=sqrt(currentSTDEV);
  
  //Affichage
  if(currentGeneration==0)
    printf("GEN\tTIME\tEVAL\tBEST\t\tAVG\t\tSTDEV\n\n");

  
  struct timeval end, res;
  gettimeofday(&end,0);
  timersub(&end,&beginTime,&res);
  printf("%lu\t%lu.%06lu\t%lu\t%f\t%f\t%f\n",currentGeneration,res.tv_sec,res.tv_usec,population->currentEvaluationNb,
	 population->Best->getFitness(),currentAverageFitness,currentSTDEV);
}

maitre's avatar
maitre committed
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
bool EvolutionaryAlgorithm::allCriteria(){

  for( size_t i=0 ; i<stoppingCriteria.size(); i++ ){
    if( stoppingCriteria.at(i)->reached() ){
      std::cout << "Stopping criterion reached : " << i << std::endl;
      return true;
    }
  }
  return false;
}



\START_CUDA_USER_CLASSES_H_TPL
#include <iostream>
#include <ostream>
#include <sstream>
using namespace std;
\INSERT_USER_CLASSES

\START_CUDA_GENOME_H_TPL
#ifndef __INDIVIDUAL
#define __INDIVIDUAL
#include "EASEATools.hpp"
#include <iostream>
maitre's avatar
maitre committed
531
532
533
/* #include <boost/archive/text_oarchive.hpp> */
/* #include <boost/archive/text_iarchive.hpp> */

maitre's avatar
maitre committed
534
535
536

\INSERT_USER_CLASSES_DEFINITIONS

maitre's avatar
maitre committed
537
void EASEAInit(int argc, char *argv[]);
maitre's avatar
maitre committed
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
void EASEAFinal(Population* population);
void EASEAFinalization(Population* population);

class Individual{

 public: // in AESAE the genome is public (for user functions,...)
  \INSERT_GENOME
  bool valid;
  float fitness;
  static RandomGenerator* rg;

 public:
  Individual();
  Individual(const Individual& indiv);
  virtual ~Individual();
  float evaluate();
  static size_t getCrossoverArrity(){ return 2; }
  float getFitness(){ return this->fitness; }
  Individual* crossover(Individual** p2);
  void printOn(std::ostream& O) const;
  
  size_t mutate(float pMutationPerGene);
maitre's avatar
maitre committed
560
  void copyToCudaBuffer(void* buffer, size_t id);
maitre's avatar
maitre committed
561
562
563

  friend std::ostream& operator << (std::ostream& O, const Individual& B) ;
  static void initRandomGenerator(RandomGenerator* rg){ Individual::rg = rg;}
maitre's avatar
maitre committed
564
565
566
567
568
569
570
571
572
573
574
575
  static size_t sizeOfGenome;

/*  private: */
/*   friend class boost::serialization::access; */
/*   template <class Archive> void serialize(Archive& ar, const unsigned int version){ */

/*     ar & fitness; */
/*     DEBUG_PRT("(de)serialization of %f fitness",fitness); */
/*     ar & valid; */
/*     DEBUG_PRT("(de)serialization of %d valid",valid); */
/*     \GENOME_SERIAL */
/*   } */
maitre's avatar
maitre committed
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592

  
};


/* ****************************************
   EvolutionaryAlgorithm class
****************************************/
class EvolutionaryAlgorithm{
public:
  EvolutionaryAlgorithm(  size_t parentPopulationSize, size_t offspringPopulationSize,
			  float selectionPressure, float replacementPressure, 
			  float pCrossover, float pMutation, float pMutationPerGene);
  EvolutionaryAlgorithm( size_t parentPopulationSize,size_t offspringPopulationSize,
			 float selectionPressure, float replacementPressure,
			 SelectionOperator* selectionOperator, SelectionOperator* replacementOperator,
			 float pCrossover, float pMutation, 
maitre's avatar
maitre committed
593
			 float pMutationPerGene, std::string& outputfile, std::string& inputfile);
maitre's avatar
maitre committed
594
595
596
597
598
599

  size_t* getCurrentGenerationPtr(){ return &currentGeneration;}
  void addStoppingCriterion(StoppingCriterion* sc);
  void runEvolutionaryLoop();
  bool allCriteria();
  Population* getPopulation(){ return population;}
maitre's avatar
maitre committed
600
601
  size_t getCurrentGeneration() { return currentGeneration;}
  void cudaEvaluate(void* buffer, size_t actualPopulationSize);
maitre's avatar
maitre committed
602

maitre's avatar
maitre committed
603
public:
maitre's avatar
maitre committed
604
605
606
607
  size_t currentGeneration;
  Population* population;
  size_t reduceParents;
  size_t reduceOffsprings;
maitre's avatar
maitre committed
608
609
610
611
  //void showPopulationStats();
  void showPopulationStats(struct timeval beginTime);
  

maitre's avatar
maitre committed
612
  std::vector<StoppingCriterion*> stoppingCriteria;
maitre's avatar
maitre committed
613
614
615

  std::string* outputfile;
  std::string* inputfile;
maitre's avatar
maitre committed
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
};


#endif


\START_CUDA_TOOLS_CPP_TPL/* ****************************************
			    
   RandomGenerator class

****************************************/
#include "EASEATools.hpp"
#include "EASEAIndividual.hpp"
#include <stdio.h>
#include <iostream>
#include <values.h>
#include <string.h>
maitre's avatar
maitre committed
633
634
635
#include <boost/program_options.hpp>
#include <boost/program_options/errors.hpp>

maitre's avatar
maitre committed
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666

RandomGenerator::RandomGenerator(unsigned int seed){
  srand(seed);
}

int RandomGenerator::randInt(){
  return rand();
}

bool RandomGenerator::tossCoin(){

  int rVal = rand();
  if( rVal >=(RAND_MAX/2))
    return true;
  else return false;
}


bool RandomGenerator::tossCoin(float bias){

  int rVal = rand();
  if( rVal <=(RAND_MAX*bias) )
    return true;
  else return false;
}



int RandomGenerator::randInt(int min, int max){

  int rValue = (((float)rand()/RAND_MAX))*(max-min);
maitre's avatar
maitre committed
667
  //DEBUG_PRT("Int Random Value : %d",min+rValue);
maitre's avatar
maitre committed
668
669
670
671
672
673
674
675
676
677
  return rValue+min;

}

int RandomGenerator::random(int min, int max){
  return randInt(min,max);
}

float RandomGenerator::randFloat(float min, float max){
  float rValue = (((float)rand()/RAND_MAX))*(max-min);
maitre's avatar
maitre committed
678
  //DEBUG_PRT("Float Random Value : %f",min+rValue);
maitre's avatar
maitre committed
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
  return rValue+min;
}

float RandomGenerator::random(float min, float max){
  return randFloat(min,max);
}

double RandomGenerator::random(double min, double max){
  return randFloat(min,max);
}


int RandomGenerator::getRandomIntMax(int max){
  double r = rand();
  r = r / RAND_MAX;
  r = r * max;
  return r;
}


/* ****************************************
   Tournament class (min and max)
****************************************/
maitre's avatar
maitre committed
702
703
void MaxTournament::initialize(Individual** population, float selectionPressure, size_t populationSize) {
  SelectionOperator::initialize(population,selectionPressure,populationSize);
maitre's avatar
maitre committed
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
}


float MaxTournament::getExtremum(){
  return -FLT_MAX;
}

size_t MaxTournament::selectNext(size_t populationSize){
  size_t bestIndex = 0;
  float bestFitness = -FLT_MAX;

  //std::cout << "MaxTournament selection " ;
  if( currentSelectionPressure >= 2 ){
    for( size_t i = 0 ; i<currentSelectionPressure ; i++ ){
      size_t selectedIndex = rg->getRandomIntMax(populationSize);
      //std::cout << selectedIndex << " ";
      float currentFitness = population[selectedIndex]->getFitness();
      
      if( bestFitness < currentFitness ){
	bestIndex = selectedIndex;
	bestFitness = currentFitness;
      }

    }
  }
  else if( currentSelectionPressure <= 1 && currentSelectionPressure > 0 ){
    size_t i1 = rg->getRandomIntMax(populationSize);
    size_t i2 = rg->getRandomIntMax(populationSize);

    if( rg->tossCoin(currentSelectionPressure) ){
      if( population[i1]->getFitness() > population[i2]->getFitness() ){
	bestIndex = i1;
      }
    }
    else{
      if( population[i1]->getFitness() > population[i2]->getFitness() ){
	bestIndex = i2;
      }
    }
  }
  else{
    std::cerr << " MaxTournament selection operator doesn't handle selection pressure : " 
	      << currentSelectionPressure << std::endl;
  }
  //std::cout << std::endl;
  return bestIndex;
}


maitre's avatar
maitre committed
753
754
void MinTournament::initialize(Individual** population, float selectionPressure, size_t populationSize) {
  SelectionOperator::initialize(population,selectionPressure,populationSize);
maitre's avatar
maitre committed
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
}

float MinTournament::getExtremum(){
  return FLT_MAX;
}


size_t MinTournament::selectNext(size_t populationSize){
  size_t bestIndex = 0;
  float bestFitness = FLT_MAX;

  //std::cout << "MinTournament selection " ;
  if( currentSelectionPressure >= 2 ){
    for( size_t i = 0 ; i<currentSelectionPressure ; i++ ){
      size_t selectedIndex = rg->getRandomIntMax(populationSize);
      //std::cout << selectedIndex << " ";
      float currentFitness = population[selectedIndex]->getFitness();
      
      if( bestFitness > currentFitness ){
	bestIndex = selectedIndex;
	bestFitness = currentFitness;
      }

    }
  }
  else if( currentSelectionPressure <= 1 && currentSelectionPressure > 0 ){
    size_t i1 = rg->getRandomIntMax(populationSize);
    size_t i2 = rg->getRandomIntMax(populationSize);

    if( rg->tossCoin(currentSelectionPressure) ){
      if( population[i1]->getFitness() < population[i2]->getFitness() ){
	bestIndex = i1;
      }
    }
    else{
      if( population[i1]->getFitness() < population[i2]->getFitness() ){
	bestIndex = i2;
      }
    }
  }
  else{
    std::cerr << " MinTournament selection operator doesn't handle selection pressure : " 
	      << currentSelectionPressure << std::endl;
  }

  //std::cout << std::endl;
  return bestIndex;
}


/* ****************************************
   SelectionOperator class
****************************************/
maitre's avatar
maitre committed
808
void SelectionOperator::initialize(Individual** population, float selectionPressure, size_t populationSize){
maitre's avatar
maitre committed
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
  this->population = population;
  this->currentSelectionPressure = selectionPressure;
}

size_t SelectionOperator::selectNext(size_t populationSize){ return 0; }


/* ****************************************
   GenerationalCriterion class
****************************************/
GenerationalCriterion::GenerationalCriterion(EvolutionaryAlgorithm* ea, size_t generationalLimit){
  this->currentGenerationPtr = ea->getCurrentGenerationPtr();
  this->generationalLimit = generationalLimit;
}

bool GenerationalCriterion::reached(){
  if( generationalLimit <= *currentGenerationPtr ){
    std::cout << "Current generation " << *currentGenerationPtr << " Generational limit : " <<
      generationalLimit << std::endl;
    return true;
  }
  else return false;
}


/* ****************************************
   Population class
****************************************/
SelectionOperator* Population::selectionOperator;
SelectionOperator* Population::replacementOperator;

float Population::selectionPressure;
float Population::replacementPressure;


maitre's avatar
maitre committed
844
845
Population::Population(){
}
maitre's avatar
maitre committed
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865

Population::Population(size_t parentPopulationSize, size_t offspringPopulationSize,
		       float pCrossover, float pMutation, float pMutationPerGene,
		       RandomGenerator* rg){
  
  this->parents     = new Individual*[parentPopulationSize];
  this->offsprings  = new Individual*[offspringPopulationSize];
  
  this->parentPopulationSize     = parentPopulationSize;
  this->offspringPopulationSize  = offspringPopulationSize;
    
  this->actualParentPopulationSize    = 0;
  this->actualOffspringPopulationSize = 0;

  this->pCrossover       = pCrossover;
  this->pMutation        = pMutation;
  this->pMutationPerGene = pMutationPerGene;

  this->rg = rg;

maitre's avatar
maitre committed
866
867
868
869
870
871
872
873
874
875
876
877
  this->currentEvaluationNb = 0;

  this->cudaParentBuffer = (void*)malloc((\GENOME_SIZE+sizeof(Individual*))*parentPopulationSize);
  this->cudaOffspringBuffer = (void*)malloc((\GENOME_SIZE+sizeof(Individual*))*offspringPopulationSize);

}

void Population::syncInVector(){
  for( size_t i = 0 ; i<actualParentPopulationSize ; i++ ){
    parents[i] = pop_vect.at(i);
  }
}
maitre's avatar
maitre committed
878

maitre's avatar
maitre committed
879
880
881
882
883
884
void Population::syncOutVector(){
  pop_vect.clear();
  for( size_t i = 0 ; i<actualParentPopulationSize ; i++ ){
    pop_vect.push_back(parents[i]);
  }
  DEBUG_PRT("Size of outVector %lu",pop_vect.size());
maitre's avatar
maitre committed
885
886
887
888
889
890
891
892
}

Population::~Population(){
  for( size_t i=0 ; i<actualOffspringPopulationSize ; i++ ) delete(offsprings[i]);
  for( size_t i=0 ; i<actualParentPopulationSize ; i++ )    delete(parents[i]);

  delete[](this->parents);
  delete[](this->offsprings);
maitre's avatar
maitre committed
893
894
895

  free(cudaParentBuffer);
  free(cudaOffspringBuffer);
maitre's avatar
maitre committed
896
897
898
899
900
901
902
903
904
905
906
907
908
909
}

void Population::initPopulation(SelectionOperator* selectionOperator, 
				SelectionOperator* replacementOperator,
				float selectionPressure, float replacementPressure){
  Population::selectionOperator   = selectionOperator;
  Population::replacementOperator = replacementOperator;
  Population::selectionPressure   = selectionPressure;
  Population::replacementPressure = replacementPressure;
}


void Population::initializeParentPopulation(){

maitre's avatar
maitre committed
910
911
  DEBUG_PRT("Creation of %lu/%lu parents (other could have been loaded from input file)",parentPopulationSize-actualParentPopulationSize,parentPopulationSize);
  for( size_t i=actualParentPopulationSize ; i<parentPopulationSize ; i++ )
maitre's avatar
maitre committed
912
913
914
915
916
917
918
919
920
    parents[i] = new Individual();

  actualParentPopulationSize = parentPopulationSize;
  actualOffspringPopulationSize = 0;
  
  evaluateParentPopulation();
}


maitre's avatar
maitre committed
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
/**
   Initialize parent population for CUDA template.
   i.e. create new individuals, copy them to the cuda parent's buffer
   but don't evaluate them.
 */
void Population::initializeCudaParentPopulation(){

  DEBUG_PRT("Creation of %lu/%lu parents (other could have been loaded from input file)",parentPopulationSize-actualParentPopulationSize,parentPopulationSize);
  for( size_t i=actualParentPopulationSize ; i<parentPopulationSize ; i++ )
    parents[i] = new Individual();

  actualParentPopulationSize = parentPopulationSize;
  actualOffspringPopulationSize = 0;
  
  // Copy parent population in the cuda buffer.
  for( size_t i=0 ; i<actualParentPopulationSize ; i++ ){
    parents[i]->copyToCudaBuffer(cudaParentBuffer,i); 
  }

}


maitre's avatar
maitre committed
943
944
945
void Population::evaluatePopulation(Individual** population, size_t populationSize){
  for( size_t i=0 ; i < populationSize ; i++ )
    population[i]->evaluate();
maitre's avatar
maitre committed
946
  currentEvaluationNb += populationSize;
maitre's avatar
maitre committed
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
}


void Population::evaluateParentPopulation(){
  evaluatePopulation(parents,parentPopulationSize);
}


void Population::evaluateOffspringPopulation(){
  evaluatePopulation(offsprings,offspringPopulationSize);
}


/**
   Reduit la population population de taille populationSize 
   a une population reducedPopulation de taille obSize.
   reducedPopulation doit etre alloue a obSize.

   Ici on pourrait avoir le best fitness de la prochaine population de parents.
   

 */
maitre's avatar
maitre committed
969
void Population::reducePopulation(Individual** population, size_t populationSize,
maitre's avatar
maitre committed
970
971
972
973
					  Individual** reducedPopulation, size_t obSize,
					  SelectionOperator* replacementOperator){
  

maitre's avatar
maitre committed
974
  replacementOperator->initialize(population,replacementPressure,populationSize);
maitre's avatar
maitre committed
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035

  for( size_t i=0 ; i<obSize ; i++ ){
    
    // select an individual and add it to the reduced population
    size_t selectedIndex = replacementOperator->selectNext(populationSize - i);
    // std::cout << "Selected " << selectedIndex << "/" << populationSize
    // 	      << " replaced by : " << populationSize-(i+1)<< std::endl;
    reducedPopulation[i] = population[selectedIndex];
    
    // erase it to the std population by swapping last individual end current
    population[selectedIndex] = population[populationSize-(i+1)];
    //population[populationSize-(i+1)] = NULL;
  }

  //return reducedPopulation;
}


Individual** Population::reduceParentPopulation(size_t obSize){
  Individual** nextGeneration = new Individual*[obSize];

  reducePopulation(parents,actualParentPopulationSize,nextGeneration,obSize,
		   Population::replacementOperator);

  // free no longer needed individuals
  for( size_t i=0 ; i<actualParentPopulationSize-obSize ; i++ )
    delete(parents[i]);
  delete[](parents);

  this->actualParentPopulationSize = obSize;
  parents = nextGeneration;
  

  return nextGeneration;
}


Individual** Population::reduceOffspringPopulation(size_t obSize){
  Individual** nextGeneration = new Individual*[obSize];

  reducePopulation(offsprings,actualOffspringPopulationSize,nextGeneration,obSize,
		   Population::replacementOperator);

  // free no longer needed individuals
  for( size_t i=0 ; i<actualOffspringPopulationSize-obSize ; i++ )
    delete(parents[i]);
  delete[](parents);

  this->actualParentPopulationSize = obSize;
  parents = nextGeneration;
  return nextGeneration;
}


static int individualCompare(const void* p1, const void* p2){
  Individual** p1_i = (Individual**)p1;
  Individual** p2_i = (Individual**)p2;

  return p1_i[0]->getFitness() > p2_i[0]->getFitness();
}

maitre's avatar
maitre committed
1036
1037
1038
1039
1040
1041
1042
1043
static int individualRCompare(const void* p1, const void* p2){
  Individual** p1_i = (Individual**)p1;
  Individual** p2_i = (Individual**)p2;

  return p1_i[0]->getFitness() < p2_i[0]->getFitness();
}


maitre's avatar
maitre committed
1044
1045
1046
1047
void Population::sortPopulation(Individual** population, size_t populationSize){
  qsort(population,populationSize,sizeof(Individual*),individualCompare);
}

maitre's avatar
maitre committed
1048
1049
1050
1051
void Population::sortRPopulation(Individual** population, size_t populationSize){
  qsort(population,populationSize,sizeof(Individual*),individualRCompare);
}

maitre's avatar
maitre committed
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072

/**
   Reduit les populations en faisant l'operation de remplacement.

   @TODO : on aurait voulu eviter la recopie des deux populations en une seule
   mais cela semble incompatible avec SelectionOperator (notamment l'operation 
   d'initialisation.
*/
void Population::reduceTotalPopulation(){

  Individual** nextGeneration = new Individual*[parentPopulationSize];

#if ((\ELITE_SIZE!=0) && (\ELITISM==true))                     // If there is elitism and it is strong
  Population::elitism(\ELITE_SIZE,parents,actualParentPopulationSize,
		      nextGeneration,parentPopulationSize); // do the elitism on the parent population only
  actualParentPopulationSize -= \ELITE_SIZE;                // decrement the parent population size
#endif

  size_t actualGlobalSize = actualParentPopulationSize+actualOffspringPopulationSize;
  Individual** globalPopulation = new Individual*[actualGlobalSize]();

maitre's avatar
maitre committed
1073

maitre's avatar
maitre committed
1074
1075
1076
  memcpy(globalPopulation,parents,sizeof(Individual*)*actualParentPopulationSize);
  memcpy(globalPopulation+actualParentPopulationSize,offsprings,
   	 sizeof(Individual*)*actualOffspringPopulationSize);
maitre's avatar
maitre committed
1077
  replacementOperator->initialize(globalPopulation, replacementPressure,actualGlobalSize);
maitre's avatar
maitre committed
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108

#if ((\ELITE_SIZE!=0) && (\ELITISM==false))                    // If there is elitism and it is weak
  Population::elitism(\ELITE_SIZE,globalPopulation,actualGlobalSize,
		      nextGeneration,parentPopulationSize); // do the elitism on the global (already merged) population
  actualGlobalSize -= \ELITE_SIZE;                // decrement the parent population size
#endif

    
  Population::reducePopulation(globalPopulation,actualGlobalSize,\ELITE_SIZE+nextGeneration,
			       parentPopulationSize-\ELITE_SIZE,replacementOperator);

  for( size_t i=0 ; i<offspringPopulationSize ; i++ )
    delete(globalPopulation[i]);
    
  delete[](parents);
  delete[](globalPopulation);

  actualParentPopulationSize = parentPopulationSize;
  actualOffspringPopulationSize = 0;
  parents = nextGeneration;
  
}


void Population::produceOffspringPopulation(){

  size_t crossoverArrity = Individual::getCrossoverArrity();
  Individual* p1;
  Individual** ps = new Individual*[crossoverArrity]();
  Individual* child;

maitre's avatar
maitre committed
1109
  selectionOperator->initialize(parents,selectionPressure,actualParentPopulationSize);
maitre's avatar
maitre committed
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145

  for( size_t i=0 ; i<offspringPopulationSize ; i++ ){
    size_t index = selectionOperator->selectNext(offspringPopulationSize);
    p1 = parents[index];
    
    if( rg->tossCoin(pCrossover) ){
      for( size_t j=0 ; j<crossoverArrity-1 ; j++ ){
	index = selectionOperator->selectNext(offspringPopulationSize);
	ps[j] = parents[index];
      }
      child = p1->crossover(ps);
    }
    else child = new Individual(*parents[index]);

    if( rg->tossCoin(pMutation) ){
      child->mutate(pMutationPerGene);
    }
    
    offsprings[actualOffspringPopulationSize++] = child;
  }
  delete[](ps);
  }




/**
   Here we save elit individuals to the replacement
   
   @ARG elitismSize the number of individuals save by elitism
   @ARG population the population where the individuals are save
   @ARG populationSize the size of the population
   @ARG outPopulation the output population, this must be allocated with size greather than elitism
   @ARG outPopulationSize the size of the output population
   
*/
maitre's avatar
maitre committed
1146
void Population::elitism(size_t elitismSize, Individual** population, size_t populationSize, 
maitre's avatar
maitre committed
1147
1148
			 Individual** outPopulation, size_t outPopulationSize){
  
maitre's avatar
maitre committed
1149
1150
  float bestFitness = population[0]->getFitness();
  size_t bestIndividual = 0;
maitre's avatar
maitre committed
1151
  
maitre's avatar
maitre committed
1152
  if( elitismSize >= 5 )DEBUG_PRT("Warning, elitism has O(n) complexity, elitismSize is maybe too big (%lu)",elitismSize);
maitre's avatar
maitre committed
1153
1154
1155
1156
1157
1158
  
  
  for(size_t i = 0 ; i<elitismSize ; i++ ){
    bestFitness = replacementOperator->getExtremum();
    bestIndividual = 0;
    for( size_t j=0 ; j<populationSize-i ; j++ ){
maitre's avatar
maitre committed
1159
#if \MINIMAXI
maitre's avatar
maitre committed
1160
      if( bestFitness < population[j]->getFitness() ){
maitre's avatar
maitre committed
1161
1162
1163
#else
      if( bestFitness > population[j]->getFitness() ){
#endif
maitre's avatar
maitre committed
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
	bestFitness = population[j]->getFitness();
	bestIndividual = j;
      }
    }
    outPopulation[i] = population[bestIndividual];
    population[bestIndividual] = population[populationSize-(i+1)];
    population[populationSize-(i+1)] = NULL;
  }
}



std::ostream& operator << (std::ostream& O, const Population& B) 
{ 
  
  size_t offspringPopulationSize = B.offspringPopulationSize;
  size_t realOffspringPopulationSize = B.actualOffspringPopulationSize;

  size_t parentPopulationSize = B.parentPopulationSize;
  size_t realParentPopulationSize = B.actualParentPopulationSize;


  O << "Population : "<< std::endl;
  O << "\t Parents size : "<< realParentPopulationSize << "/" << 
    parentPopulationSize << std::endl;
  
  for( size_t i=0 ; i<realParentPopulationSize ; i++){
maitre's avatar
maitre committed
1191
    O << "\t\t" << *B.parents[i] ;
maitre's avatar
maitre committed
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
  } 

  O << "\t Offspring size : "<< realOffspringPopulationSize << "/" << 
    offspringPopulationSize << std::endl;
  for( size_t i=0 ; i<realOffspringPopulationSize ; i++){
    O << "\t\t" << *B.offsprings[i] << std::endl;
  }  
  return O; 
} 



maitre's avatar
maitre committed
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
void MaxDeterministic::initialize(Individual** population, float selectionPressure,size_t populationSize){
  SelectionOperator::initialize(population,selectionPressure,populationSize);
  Population::sortPopulation(population,populationSize);
  populationSize = populationSize;
}


size_t MaxDeterministic::selectNext(size_t populationSize){
  return populationSize-1;
}

float MaxDeterministic::getExtremum(){
  return -FLT_MAX;
}



void MinDeterministic::initialize(Individual** population, float selectionPressure,size_t populationSize){
  SelectionOperator::initialize(population,selectionPressure,populationSize);
  Population::sortRPopulation(population,populationSize);
  populationSize = populationSize;
}


size_t MinDeterministic::selectNext(size_t populationSize){
  return populationSize-1;
}

float MinDeterministic::getExtremum(){
  return FLT_MAX;
}

MaxRandom::MaxRandom(RandomGenerator* globalRandomGenerator){
  rg = globalRandomGenerator;
}

void MaxRandom::initialize(Individual** population, float selectionPressure, size_t populationSize){
  SelectionOperator::initialize(population,selectionPressure,populationSize);
}

size_t MaxRandom::selectNext(size_t populationSize){
  return rg->random(0,populationSize-1);
}

float MaxRandom::getExtremum(){
  return -FLT_MAX;
}

MinRandom::MinRandom(RandomGenerator* globalRandomGenerator){
  rg = globalRandomGenerator;
}

void MinRandom::initialize(Individual** population, float selectionPressure, size_t populationSize){
  SelectionOperator::initialize(population,selectionPressure,populationSize);
}

size_t MinRandom::selectNext(size_t populationSize){
  return rg->random(0,populationSize-1);
}

float MinRandom::getExtremum(){
  return -FLT_MAX;
}

namespace po = boost::program_options;


po::variables_map vm;
po::variables_map vm_file;

using namespace std;

string setVariable(string argumentName, string defaultValue, po::variables_map vm, po::variables_map vm_file){
  string ret;

  if( vm.count(argumentName) ){
    ret = vm[argumentName].as<string>();
    cout << argumentName << " is declared in user command line as "<< ret << endl;
  }
  else if( vm_file.count(argumentName) ){
    ret = vm_file[argumentName].as<string>();
    cout <<  argumentName << " is declared configuration file as "<< ret << endl;
  }
  else {
    ret = defaultValue;
    cout << argumentName << " is not declared, default value is "<< ret<< endl;
  }
  return ret;
}

int setVariable(string argumentName, int defaultValue, po::variables_map vm, po::variables_map vm_file ){
  int ret;

  if( vm.count(argumentName) ){
    ret = vm[argumentName].as<int>();
    cout << argumentName << " is declared in user command line as "<< ret << endl;
  }
  else if( vm_file.count(argumentName) ){
    ret = vm_file[argumentName].as<int>();
    cout <<  argumentName << " is declared configuration file as "<< ret << endl;
  }
  else {
    ret = defaultValue;
    cout << argumentName << " is not declared, default value is "<< ret<< endl;
  }
  return ret;
}


int loadParametersFile(const string& filename, char*** outputContainer){

  FILE* paramFile = fopen(filename.c_str(),"r");
  char buffer[512];
  vector<char*> tmpContainer;
  
  char* padding = (char*)malloc(sizeof(char));
  padding[0] = 0;

  tmpContainer.push_back(padding);
  
  while( fgets(buffer,512,paramFile)){
    for( size_t i=0 ; i<512 ; i++ )
      if( buffer[i] == '#' || buffer[i] == '\n' || buffer[i] == '\0' || buffer[i]==' '){
	buffer[i] = '\0';
	break;
      } 
    int str_len;
    if( (str_len = strlen(buffer)) ){
      cout << "line : " <<buffer << endl;
      char* nLine = (char*)malloc(sizeof(char)*(str_len+1));
      strcpy(nLine,buffer);
      tmpContainer.push_back(nLine);
    }    
  }

  (*outputContainer) = (char**)malloc(sizeof(char*)*tmpContainer.size());
 
  for ( size_t i=0 ; i<tmpContainer.size(); i++)
    (*outputContainer)[i] = tmpContainer.at(i);

  fclose(paramFile);
  return tmpContainer.size();
}


void parseArguments(const char* parametersFileName, int ac, char** av, 
		    po::variables_map& vm, po::variables_map& vm_file){

  char** argv;
  int argc = loadParametersFile(parametersFileName,&argv);
  
  po::options_description desc("Allowed options ");
  desc.add_options()
    ("help", "produce help message")
    ("compression", po::value<int>(), "set compression level")
    ("seed", po::value<int>(), "set the global seed of the pseudo random generator")
    ("popSize",po::value<int>(),"set the population size")
    ("nbOffspring",po::value<int>(),"set the offspring population size")
    ("elite",po::value<int>(),"Nb of elite parents (absolute)")
    ("eliteType",po::value<int>(),"Strong (1) or weak (1)")
    ("nbGen",po::value<int>(),"Set the number of generation")
    ("surviveParents",po::value<int>()," Nb of surviving parents (absolute)")
    ("surviveOffsprings",po::value<int>()," Nb of surviving offsprings (absolute)")
    ("outputfile",po::value<string>(),"Set an output file for the final population (default : none)")
    ("inputfile",po::value<string>(),"Set an input file for the initial population (default : none)")
    ("u1",po::value<string>(),"User defined parameter 1")
    ("u2",po::value<string>(),"User defined parameter 2")
    ("u3",po::value<string>(),"User defined parameter 3")
    ("u4",po::value<string>(),"User defined parameter 4")
    ;
    
  try{
    po::store(po::parse_command_line(ac, av, desc,0), vm);
    po::store(po::parse_command_line(argc, argv, desc,0), vm_file);
  }
  catch(po::unknown_option& e){
    cerr << "Unknown option  : " << e.what() << endl;    
    cout << desc << endl;
    exit(1);
  }
  
  po::notify(vm);    
  po::notify(vm_file);    

  if (vm.count("help")) {
    cout << desc << "\n";
    exit(1);
  }

  for( int i = 0 ; i<argc ; i++ )
    free(argv[i]);
  free(argv);
 
}
maitre's avatar
maitre committed
1398

maitre's avatar
maitre committed
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
void parseArguments(const char* parametersFileName, int ac, char** av){
  parseArguments(parametersFileName,ac,av,vm,vm_file);
}


int setVariable(const string optionName, int defaultValue){
  return setVariable(optionName,defaultValue,vm,vm_file);
}

string setVariable(const string optionName, string defaultValue){
  return setVariable(optionName,defaultValue,vm,vm_file);
}








\START_CUDA_TOOLS_H_TPL#ifndef TIMING_H
#define TIMING_H

#include <time.h>             //gettimeofday
#include <sys/time.h>
#include <stdio.h>



#ifdef TIMING
#define DECLARE_TIME(t)				\
  struct timeval t##_beg, t##_end, t##_res
#define TIME_ST(t)				\
  gettimeofday(&t##_beg,NULL)
#define TIME_END(t)				\
  gettimeofday(&t##_end,NULL)
#define SHOW_TIME(t)						\
  timersub(&t##_end,&t##_beg,&t##_res);				\
  printf("%s : %lu.%06lu\n",#t,t##_res.tv_sec,t##_res.tv_usec)
#define SHOW_SIMPLE_TIME(t)					\
  printf("%s : %lu.%06lu\n",#t,t.tv_sec,t.tv_usec)
#define COMPUTE_TIME(t)						\
  timersub(&t##_end,&t##_beg,&t##_res)
#else
#define DECLARE_TIME(t)
#define TIME_ST(t)
#define TIME_END(t)
#define SHOW_TIME(t)
#define SHOW_SIMPLE_TIME(t)
#endif


#endif

/* ****************************************
maitre's avatar
maitre committed
1454
1455
1456
1457
1458
   Some tools classes for algorithm
****************************************/
#include <stdlib.h>
#include <vector>
#include <iostream>
maitre's avatar
maitre committed
1459
1460
1461
1462
/* #include <boost/archive/text_oarchive.hpp> //for serialization (dumping) */
/* #include <boost/archive/text_iarchive.hpp> //for serialization (loading) */
/* #include <boost/serialization/vector.hpp> */

maitre's avatar
maitre committed
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
class EvolutionaryAlgorithm;
class Individual;
class Population;

#ifdef DEBUG
#define DEBUG_PRT(format, args...) fprintf (stdout,"***DBG***  %s-%d: "format"\n",__FILE__,__LINE__,##args)
#define DEBUG_YACC(format, args...) fprintf (stdout,"***DBG_YACC***  %s-%d: "format"\n",__FILE__,__LINE__,##args)
#else
#define DEBUG_PRT(format, args...) 
#define DEBUG_YACC(format, args...)
#endif


/* ****************************************
   StoppingCriterion class
****************************************/
#ifndef __EASEATOOLS
#define __EASEATOOLS
class StoppingCriterion {

public:
  virtual bool reached() = 0;

};


/* ****************************************
   GenerationalCriterion class
****************************************/
class GenerationalCriterion : public StoppingCriterion {
 private:
  size_t* currentGenerationPtr;
  size_t generationalLimit;
 public:
  virtual bool reached();
  GenerationalCriterion(EvolutionaryAlgorithm* ea, size_t generationalLimit);
  
};


/* ****************************************
   RandomGenerator class
****************************************/
class RandomGenerator{
public:
  RandomGenerator(unsigned int seed);
  int randInt();
  bool tossCoin();
  bool tossCoin(float bias);
  int randInt(int min, int max);
  int getRandomIntMax(int max);
  float randFloat(float min, float max);
  int random(int min, int max);
  float random(float min, float max);
  double random(double min, double max);

};



/* ****************************************
   Selection Operator class
****************************************/
class SelectionOperator{
public:
maitre's avatar
maitre committed
1528
  virtual void initialize(Individual** population, float selectionPressure, size_t populationSize);
maitre's avatar
maitre committed
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
  virtual size_t selectNext(size_t populationSize);
  virtual float getExtremum() = 0 ;
protected:
  Individual** population;
  float currentSelectionPressure;
};


/* ****************************************
   Tournament classes (min and max)
****************************************/
class MaxTournament : public SelectionOperator{
public:
  MaxTournament(RandomGenerator* rg){ this->rg = rg; }
maitre's avatar
maitre committed
1543
  virtual void initialize(Individual** population, float selectionPressure, size_t populationSize);
maitre's avatar
maitre committed
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
  virtual size_t selectNext(size_t populationSize);
  float getExtremum();
private:
  RandomGenerator* rg;
  
};



class MinTournament : public SelectionOperator{
public:
  MinTournament(RandomGenerator* rg){ this->rg = rg; }
maitre's avatar
maitre committed
1556
  virtual void initialize(Individual** population, float selectionPressure, size_t populationSize);
maitre's avatar
maitre committed
1557
1558
1559
1560
1561
1562
1563
  virtual size_t selectNext(size_t populationSize);
  float getExtremum();
private:
  RandomGenerator* rg;
  
};

maitre's avatar
maitre committed
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609

class MaxDeterministic : public SelectionOperator{
 public:
  virtual void initialize(Individual** population, float selectionPressure, size_t populationSize);
  virtual size_t selectNext(size_t populationSize);
  float getExtremum();
 private:
  size_t populationSize;
};

class MinDeterministic : public SelectionOperator{
 public:
  virtual void initialize(Individual** population, float selectionPressure, size_t populationSize);
  virtual size_t selectNext(size_t populationSize);
  float getExtremum();
 private:
  size_t populationSize;

};


class MaxRandom : public SelectionOperator{
 public:
  MaxRandom(RandomGenerator* globalRandomGenerator);
  virtual void initialize(Individual** population, float selectionPressure, size_t populationSize);
  virtual size_t selectNext(size_t populationSize);
  float getExtremum();
 private:
  size_t populationSize;
  RandomGenerator* rg;

};

class MinRandom : public SelectionOperator{
 public:
  MinRandom(RandomGenerator* globalRandomGenerator);
  virtual void initialize(Individual** population, float selectionPressure, size_t populationSize);
  virtual size_t selectNext(size_t populationSize);
  float getExtremum();
 private:
  size_t populationSize;
  RandomGenerator* rg;
};



maitre's avatar
maitre committed
1610
1611
class Population {
  
maitre's avatar
maitre committed
1612
 public:
maitre's avatar
maitre committed
1613
1614
1615
1616
  
  float pCrossover;
  float pMutation;
  float pMutationPerGene;
maitre's avatar
maitre committed
1617
1618

  Individual* Best;
maitre's avatar
maitre committed
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
  
  Individual** parents;
  Individual** offsprings;

  size_t parentPopulationSize;
  size_t offspringPopulationSize;

  size_t actualParentPopulationSize;
  size_t actualOffspringPopulationSize;

  static SelectionOperator* selectionOperator;
  static SelectionOperator* replacementOperator;

maitre's avatar
maitre committed
1632
  size_t currentEvaluationNb;
maitre's avatar
maitre committed
1633
  RandomGenerator* rg;
maitre's avatar
maitre committed
1634
  std::vector<Individual*> pop_vect;
maitre's avatar
maitre committed
1635

maitre's avatar
maitre committed
1636
1637
  void* cudaParentBuffer;
  void* cudaOffspringBuffer;
maitre's avatar
maitre committed
1638

maitre's avatar
maitre committed
1639
1640
 public:
  Population();
maitre's avatar
maitre committed
1641
1642
1643
1644
1645
  Population(size_t parentPopulationSize, size_t offspringPopulationSize, 
	     float pCrossover, float pMutation, float pMutationPerGene, RandomGenerator* rg);
  virtual ~Population();

  void initializeParentPopulation();  
maitre's avatar
maitre committed
1646
  void initializeCudaParentPopulation();
maitre's avatar
maitre committed
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
  void evaluatePopulation(Individual** population, size_t populationSize);
  void evaluateParentPopulation();

  static void elitism(size_t elitismSize, Individual** population, size_t populationSize, Individual** outPopulation,
		      size_t outPopulationSize);

  void evaluateOffspringPopulation();
  Individual** reducePopulations(Individual** population, size_t populationSize,
			       Individual** reducedPopulation, size_t obSize);
  Individual** reduceParentPopulation(size_t obSize);
  Individual** reduceOffspringPopulation(size_t obSize);
  void reduceTotalPopulation();
  void evolve();

  static float selectionPressure;
  static float replacementPressure;
  static void initPopulation(SelectionOperator* selectionOperator, 
			     SelectionOperator* replacementOperator,
			     float selectionPressure, float replacementPressure);

  static void sortPopulation(Individual** population, size_t populationSize);

maitre's avatar
maitre committed
1669
1670
1671
  static void sortRPopulation(Individual** population, size_t populationSize);


maitre's avatar
maitre committed
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
  void sortParentPopulation(){ Population::sortPopulation(parents,actualParentPopulationSize);}

  void produceOffspringPopulation();

  friend std::ostream& operator << (std::ostream& O, const Population& B);


  void setParentPopulation(Individual** population, size_t actualParentPopulationSize){ 
    this->parents = population;
    this->actualParentPopulationSize = actualParentPopulationSize;
  }

maitre's avatar
maitre committed
1684
  static void reducePopulation(Individual** population, size_t populationSize,
maitre's avatar
maitre committed
1685
1686
				       Individual** reducedPopulation, size_t obSize,
				       SelectionOperator* replacementOperator);
maitre's avatar
maitre committed
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
  void syncOutVector();
  void syncInVector();

/*  private: */
/*   friend class boost::serialization::access; */
/*   template <class Archive> void serialize(Archive& ar, const unsigned int version){ */

/*     ar & actualParentPopulationSize; */
/*     DEBUG_PRT("(de)serialization of %d parents",actualParentPopulationSize); */
/*     ar & pop_vect; */
/*     DEBUG_PRT("(de)serialization of %d offspring",actualOffspringPopulationSize); */
/*   } */
maitre's avatar
maitre committed
1699
1700
};

maitre's avatar
maitre committed
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
/* namespace boost{ */
/*   namespace serialization{ */
/*     template<class Archive> */
/*       void serialize(Archive & ar,std::vector<Individual*> population, const unsigned int version){ */
/*       ar & population; */
/*     } */
/*   } */
/* } */

void parseArguments(const char* parametersFileName, int ac, char** av);
int setVariable(const std::string optionName, int defaultValue);
std::string setVariable(const std::string optionName, std::string defaultValue);


maitre's avatar
maitre committed
1715
1716
1717
1718

#endif


maitre's avatar
maitre committed
1719

maitre's avatar
maitre committed
1720
1721
1722
1723
\START_CUDA_MAKEFILE_TPL

NVCC= nvcc
CPPC= g++
maitre's avatar
maitre committed
1724
1725
1726
1727
1728
CXXFLAGS+=-g -Wall -O2
LDFLAGS=-lboost_program_options -lboost_serialization

#USER MAKEFILE OPTIONS :
\INSERT_MAKEFILE_OPTION#END OF USER MAKEFILE OPTIONS
maitre's avatar
maitre committed
1729

maitre's avatar
maitre committed
1730
1731
1732
CPPFLAGS+=-DDEBUG

EASEA_SRC= EASEATools.cpp EASEAIndividual.cpp
maitre's avatar
maitre committed
1733
1734
1735
1736
1737
EASEA_MAIN_HDR= EASEA.cpp
EASEA_UC_HDR= EASEAUserClasses.hpp

EASEA_HDR= $(EASEA_SRC:.cpp=.hpp) 

maitre's avatar
maitre committed
1738
1739
1740
1741
SRC= $(EASEA_SRC) $(EASEA_MAIN_HDR)
CUDA_SRC = EASEAIndividual.cu
HDR= $(EASEA_HDR) $(EASEA_UC_HDR)
OBJ= $(EASEA_SRC:.cpp=.o) $(EASEA_MAIN_HDR:.cpp=.o)
maitre's avatar
maitre committed
1742
1743
1744
1745
1746
1747

BIN= EASEA
  
all:$(BIN)

$(BIN):$(OBJ)
maitre's avatar
maitre committed
1748
1749
1750
1751
	$(NVCC) $^ -o $@ $(LDFLAGS) 

%.o:%.cu
	$(NVCC) $(NVFLAGS) -o $@ $< -c -DTIMING $(CPPFLAGS) -g -Xcompiler -Wall
maitre's avatar
maitre committed
1752
1753

easeaclean: clean
maitre's avatar
maitre committed
1754
	rm -f Makefile EASEA.prm $(SRC) $(HDR) EASEA.mak $(CUDA_SRC) 
maitre's avatar
maitre committed
1755
clean:
maitre's avatar
maitre committed
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
	rm -f $(OBJ) $(BIN) 

\START_EO_PARAM_TPL#****************************************
#                                         
#  EASEA.prm
#                                         
#  Parameter file generated by AESAE-EO v0.7b
#                                         
#***************************************
# --seed=0   # -S : Random number seed. It is possible to give a specific seed.

######    Evolution Engine    ######
--popSize=\POP_SIZE # -P : Population Size
--nbOffspring=\OFF_SIZE # -O : Nb of offspring (percentage or absolute)

######    Evolution Engine / Replacement    ######
--elite=\ELITE_SIZE  # Nb of elite parents (percentage or absolute)
--eliteType=\ELITISM # Strong (true) or weak (false) elitism (set elite to 0 for none)
--surviveParents=\SURV_PAR_SIZE # Nb of surviving parents (percentage or absolute)
# --reduceParents=Ranking # Parents reducer: Deterministic, EP(T), DetTour(T), StochTour(t), Uniform
--surviveOffspring=\SURV_OFF_SIZE  # Nb of surviving offspring (percentage or absolute)
# --reduceOffspring=Roulette # Offspring reducer: Deterministic, EP(T), DetTour(T), StochTour(t), Uniform
# --reduceFinal=DetTour(2) # Final reducer: Deterministic, EP(T), DetTour(T), StochTour(t), Uniform

maitre's avatar
maitre committed
1780
1781

\TEMPLATE_END