CUDA.tpl 54.4 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
#include <string.h>
#include <fstream>
#include <sys/time.h>
#include "EASEATools.hpp"

71
#define CUDA_TPL
maitre's avatar
maitre committed
72 73 74 75

extern RandomGenerator* globalRandomGenerator;

\INSERT_USER_DECLARATIONS
maitre's avatar
maitre committed
76 77
struct gpuOptions initOpts;

maitre's avatar
maitre committed
78 79 80 81 82 83
\ANALYSE_USER_CLASSES

\INSERT_USER_FUNCTIONS

\INSERT_INITIALISATION_FUNCTION
\INSERT_FINALIZATION_FUNCTION
maitre's avatar
maitre committed
84
\INSERT_GENERATION_FUNCTION
maitre's avatar
maitre committed
85
\INSERT_BOUND_CHECKING
maitre's avatar
maitre committed
86 87 88



maitre's avatar
maitre committed
89 90 91 92
void EASEAFinal(Population* pop){
  \INSERT_FINALIZATION_FCT_CALL
}

maitre's avatar
maitre committed
93 94 95 96 97
void EASEAInit(int argc, char** argv){
  \INSERT_INIT_FCT_CALL
}


maitre's avatar
maitre committed
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
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
123 124 125 126

/**
   This function allows to acces to the Individual stored in cudaBuffer as a standard
   individual.
maitre's avatar
maitre committed
127
   @TODO This should be a macro, at this time it is a function for debuging purpose
maitre's avatar
maitre committed
128 129 130 131 132 133
*/
__device__ __host__ inline Individual* INDIVIDUAL_ACCESS(void* buffer,size_t id){
  return ((Individual*)(((char*)buffer)+(\GENOME_SIZE+sizeof(void*))*id));
}


maitre's avatar
maitre committed
134
__device__ float cudaEvaluate(void* devBuffer, size_t id, struct gpuOptions initOpts){
maitre's avatar
maitre committed
135 136 137 138 139 140
  \INSERT_CUDA_EVALUATOR
}




maitre's avatar
maitre committed
141
inline void Individual::copyToCudaBuffer(void* buffer, size_t id){
maitre's avatar
maitre committed
142
  
maitre's avatar
maitre committed
143 144 145
/*   DEBUG_PRT("%p\n",(char*)this+sizeof(Individual*)); */
/*   DEBUG_PRT("%p\n",&this->sigma); */
/*   DEBUG_PRT("%lu\n",id); */
maitre's avatar
maitre committed
146 147 148 149 150
  
  memcpy(((char*)buffer)+(\GENOME_SIZE+sizeof(Individual*))*id,((char*)this),\GENOME_SIZE+sizeof(Individual*));
  
}

maitre's avatar
maitre committed
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
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
171
  //DEBUG_PRT("Xover");
maitre's avatar
maitre committed
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 204 205 206 207 208 209
/*   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
210 211 212

size_t Individual::sizeOfGenome=\GENOME_SIZE;

maitre's avatar
maitre committed
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 245 246 247 248 249 250
/* ****************************************
   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
251
					      float pMutationPerGene, string& outputfile, string& inputfile){
maitre's avatar
maitre committed
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268

  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
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
  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 
maitre's avatar
maitre committed
285
cudaEvaluatePopulation(void* d_population, size_t popSize, float* d_fitnesses, struct gpuOptions initOpts){
maitre's avatar
maitre committed
286 287 288 289 290 291

  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;

maitre's avatar
maitre committed
292
  //void* indiv = ((char*)d_population)+id*(\GENOME_SIZE+sizeof(Individual*)); // compute the offset of the current individual
maitre's avatar
maitre committed
293

maitre's avatar
maitre committed
294 295 296 297 298 299 300 301 302 303 304 305 306 307
  d_fitnesses[id] = cudaEvaluate(d_population,id,initOpts);


/*   if( blockIdx.x == 0){ */
/*   for( size_t i = 0 ; i<popSize ; i++ ){ */
/*     printf("%d : \n\t",i); */
/*     for( size_t j=0 ; j<10 ; j++ ) */
/*       printf("%f | ",INDIVIDUAL_ACCESS(d_population,i)->x[j]); */
/*     printf("\n\t"); */
/*     for( size_t j=0 ; j<10 ; j++ ) */
/*       printf("%f | ",INDIVIDUAL_ACCESS(d_population,i)->sigma[j]); */
/*     printf("\n"); */
/*   } */
/*   } */
maitre's avatar
maitre committed
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329

}


#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
330

maitre's avatar
maitre committed
331 332 333 334 335 336
bool
repartition(size_t popSize, size_t* nbBlock, size_t* nbThreadPB, size_t* nbThreadLB, 
	    size_t nbMP, size_t maxBlockSize){
  
  (*nbThreadLB) = 0;
  
maitre's avatar
maitre committed
337 338
  DEBUG_PRT("repartition : %d",popSize);
  
maitre's avatar
maitre committed
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
  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;
}


maitre's avatar
maitre committed
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
/**
   Allocate buffer for populationSize individuals and fitnesses
   compute the repartition
 */
void EvolutionaryAlgorithm::cudaPreliminaryProcess(size_t populationSize, dim3* dimBlock, dim3* dimGrid, void** allocatedDeviceBuffer,
						   float** deviceFitness){

  size_t nbThreadPB, nbThreadLB, nbBlock;
  cudaError_t lastError;

  lastError = cudaMalloc(allocatedDeviceBuffer,populationSize*(\GENOME_SIZE+sizeof(Individual*)));
  DEBUG_PRT("Population buffer allocation : %s",cudaGetErrorString(lastError));
  lastError = cudaMalloc(((void**)deviceFitness),populationSize*sizeof(float));
  DEBUG_PRT("Fitness buffer allocation : %s",cudaGetErrorString(lastError));
  
maitre's avatar
ok  
maitre committed
393
  if( !repartition(populationSize, &nbBlock, &nbThreadPB, &nbThreadLB,30, 240))
maitre's avatar
maitre committed
394 395 396 397 398 399 400 401 402 403 404 405 406 407
    exit( -1 );

  DEBUG_PRT("repartition is \n\tnbBlock %lu \n\tnbThreadPB %lu \n\tnbThreadLD %lu",nbBlock,nbThreadPB,nbThreadLB); 

  if( nbThreadLB!=0 )
    dimGrid->x = (nbBlock+1);
  else
    dimGrid->x = (nbBlock);

  dimBlock->x = nbThreadPB;
  cout << "Number of grid : " << dimGrid->x << endl;
  cout << "Number of block : " << dimBlock->x << endl;
}

maitre's avatar
maitre committed
408

maitre's avatar
maitre committed
409 410 411
void EvolutionaryAlgorithm::cudaOffspringEvaluate(void* d_offspringPopulation, float* d_fitnesses, dim3 dimBlock, dim3 dimGrid){
  cudaError_t lastError;
  size_t actualPopulationSize = this->population->actualOffspringPopulationSize;
maitre's avatar
maitre committed
412
  float* fitnesses = new float[actualPopulationSize];
maitre's avatar
maitre committed
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432

  
  lastError = cudaMemcpy(d_offspringPopulation,population->cudaOffspringBuffer,(\GENOME_SIZE+sizeof(Individual*))*actualPopulationSize,
			 cudaMemcpyHostToDevice);
  DEBUG_PRT("Parent population buffer copy : %s",cudaGetErrorString(lastError));

  cudaEvaluatePopulation<<< dimGrid, dimBlock>>>(d_offspringPopulation,actualPopulationSize,d_fitnesses,initOpts);
  lastError = cudaGetLastError();
  DEBUG_PRT("Kernel execution : %s",cudaGetErrorString(lastError));

  lastError = cudaMemcpy(fitnesses,d_fitnesses,actualPopulationSize*sizeof(float),cudaMemcpyDeviceToHost);
  DEBUG_PRT("Offspring's fitnesses gathering : %s",cudaGetErrorString(lastError));


#ifdef COMPARE_HOST_DEVICE
  population->evaluateOffspringPopulation();
#endif

  for( size_t i=0 ; i<actualPopulationSize ; i++ ){
#ifdef COMPARE_HOST_DEVICE
maitre's avatar
ok  
maitre committed
433 434 435 436 437
    float error = (population->offsprings[i]->getFitness()-fitnesses[i])/population->offsprings[i]->getFitness();
    printf("Difference for individual %lu is : %f %f|%f\n",i,error, population->offsprings[i]->getFitness(),fitnesses[i]);
    if( error > 0.2 )
      exit(-1);

maitre's avatar
maitre committed
438
#else
maitre's avatar
maitre committed
439
    DEBUG_PRT("%lu : %f\n",i,fitnesses[i]);
maitre's avatar
maitre committed
440 441 442 443 444 445 446 447 448 449 450 451 452
    population->offsprings[i]->fitness = fitnesses[i];
    population->offsprings[i]->valid = true;
#endif
  }
  
}

/**
   Evaluate parent population on the GPU. This is special because this evaluation occures
   only one time. Buffers are allocated and freed here.
 */
void EvolutionaryAlgorithm::cudaParentEvaluate(){
  float* fitnesses = new float[this->population->actualParentPopulationSize];
maitre's avatar
maitre committed
453 454 455
  void* allocatedDeviceBuffer;
  float* deviceFitness;
  cudaError_t lastError;
maitre's avatar
maitre committed
456 457 458 459
  dim3 dimBlock, dimGrid;
  size_t actualPopulationSize = this->population->actualParentPopulationSize;

  cudaPreliminaryProcess(actualPopulationSize,&dimBlock,&dimGrid,&allocatedDeviceBuffer,&deviceFitness);
maitre's avatar
maitre committed
460 461
    
  //compute the repartition over MP and SP
maitre's avatar
maitre committed
462 463 464
  lastError = cudaMemcpy(allocatedDeviceBuffer,this->population->cudaParentBuffer,(\GENOME_SIZE+sizeof(Individual*))*actualPopulationSize,
			 cudaMemcpyHostToDevice);
  DEBUG_PRT("Parent population buffer copy : %s",cudaGetErrorString(lastError));
maitre's avatar
maitre committed
465 466


maitre's avatar
maitre committed
467
  cudaEvaluatePopulation<<< dimGrid, dimBlock>>>(allocatedDeviceBuffer,actualPopulationSize,deviceFitness,initOpts);
maitre's avatar
ok  
maitre committed
468
  lastError = cudaThreadSynchronize();
maitre's avatar
maitre committed
469 470 471 472 473 474 475 476 477 478 479 480 481 482
  DEBUG_PRT("Kernel execution : %s",cudaGetErrorString(lastError));
 
  lastError = cudaMemcpy(fitnesses,deviceFitness,actualPopulationSize*sizeof(float),cudaMemcpyDeviceToHost);
  DEBUG_PRT("Parent's fitnesses gathering : %s",cudaGetErrorString(lastError));

  cudaFree(deviceFitness);
  cudaFree(allocatedDeviceBuffer);

#ifdef COMPARE_HOST_DEVICE
  population->evaluateParentPopulation();
#endif

  for( size_t i=0 ; i<actualPopulationSize ; i++ ){
#ifdef COMPARE_HOST_DEVICE
maitre's avatar
ok  
maitre committed
483 484 485 486 487
    float error = (population->parents[i]->getFitness()-fitnesses[i])/population->parents[i]->getFitness();
    printf("Difference for individual %lu is : %f %f|%f\n",i,error,
	   population->parents[i]->getFitness(), fitnesses[i]);
    if( error > 0.2 )
      exit(-1);
maitre's avatar
maitre committed
488
#else
maitre's avatar
ok  
maitre committed
489
    DEBUG_PRT("%lu : %f\n",i,fitnesses[i]);
maitre's avatar
maitre committed
490 491 492 493
    population->parents[i]->fitness = fitnesses[i];
    population->parents[i]->valid = true;
#endif
  }
maitre's avatar
maitre committed
494 495 496 497 498 499 500
}

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

void EvolutionaryAlgorithm::runEvolutionaryLoop(){
maitre's avatar
maitre committed
501 502 503 504 505 506 507 508 509 510 511 512 513
  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
514 515

  std::cout << "Parent's population initializing "<< std::endl;
maitre's avatar
maitre committed
516 517
  this->population->initializeCudaParentPopulation();
  cudaParentEvaluate();
maitre's avatar
maitre committed
518

maitre's avatar
ok  
maitre committed
519
//  std::cout << *population << std::endl;
maitre's avatar
maitre committed
520

maitre's avatar
ok  
maitre committed
521
  DEBUG_PRT("Genome size is %lu",\GENOME_SIZE);
maitre's avatar
maitre committed
522 523 524 525 526 527 528 529 530


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


maitre's avatar
maitre committed
531 532 533 534 535
  void* d_offspringPopulation;
  float* d_fitnesses;
  dim3 dimBlock, dimGrid;

  cudaPreliminaryProcess(this->population->offspringPopulationSize,&dimBlock,&dimGrid,&d_offspringPopulation,&d_fitnesses);
maitre's avatar
maitre committed
536 537 538 539
  
  while( this->allCriteria() == false ){    

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

maitre's avatar
maitre committed
541
    \INSERT_BOUND_CHECKING_FCT_CALL
maitre's avatar
maitre committed
542

maitre's avatar
maitre committed
543
    TIME_ST(eval);
maitre's avatar
maitre committed
544 545 546 547
    for( size_t i=0 ; i<this->population->actualOffspringPopulationSize ; i++ )
      this->population->offsprings[i]->copyToCudaBuffer(this->population->cudaOffspringBuffer,i); 

    cudaOffspringEvaluate(d_offspringPopulation,d_fitnesses,dimBlock,dimGrid);
maitre's avatar
maitre committed
548 549
    TIME_END(eval);

maitre's avatar
ok  
maitre committed
550 551
    COMPUTE_TIME(eval);
    //SHOW_TIME(eval);
maitre's avatar
maitre committed
552 553
    timeradd(&accuEval,&eval_res,&accuEval);

maitre's avatar
maitre committed
554
    
maitre's avatar
maitre committed
555

maitre's avatar
maitre committed
556 557 558 559 560 561 562
    if(reduceParents)
      population->reduceParentPopulation(reduceParents);
    
    if(reduceOffsprings)
      population->reduceOffspringPopulation(reduceOffsprings);
    
    population->reduceTotalPopulation();
maitre's avatar
maitre committed
563 564 565
     
    \INSERT_GEN_FCT_CALL    

maitre's avatar
ok  
maitre committed
566
    showPopulationStats(begin);
maitre's avatar
maitre committed
567 568 569
    currentGeneration += 1;
  }  
  population->sortParentPopulation();
maitre's avatar
maitre committed
570
  //std::cout << *population << std::endl;
maitre's avatar
maitre committed
571
  std::cout << "Generation : " << currentGeneration << std::endl;
maitre's avatar
maitre committed
572 573 574 575 576 577 578 579 580 581 582
  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
583 584
  cudaFree(d_offspringPopulation);
  cudaFree(d_fitnesses);
maitre's avatar
maitre committed
585 586 587
}


maitre's avatar
maitre committed
588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625
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
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650
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
651
#include <vector_types.h>
maitre's avatar
maitre committed
652 653 654
/* #include <boost/archive/text_oarchive.hpp> */
/* #include <boost/archive/text_iarchive.hpp> */

maitre's avatar
maitre committed
655 656 657

\INSERT_USER_CLASSES_DEFINITIONS

maitre's avatar
maitre committed
658
void EASEAInit(int argc, char *argv[]);
maitre's avatar
maitre committed
659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
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
681
  void copyToCudaBuffer(void* buffer, size_t id);
maitre's avatar
maitre committed
682 683 684

  friend std::ostream& operator << (std::ostream& O, const Individual& B) ;
  static void initRandomGenerator(RandomGenerator* rg){ Individual::rg = rg;}
maitre's avatar
maitre committed
685 686 687 688 689 690 691 692 693 694 695 696
  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
697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713

  
};


/* ****************************************
   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
714
			 float pMutationPerGene, std::string& outputfile, std::string& inputfile);
maitre's avatar
maitre committed
715 716 717 718 719 720

  size_t* getCurrentGenerationPtr(){ return &currentGeneration;}
  void addStoppingCriterion(StoppingCriterion* sc);
  void runEvolutionaryLoop();
  bool allCriteria();
  Population* getPopulation(){ return population;}
maitre's avatar
maitre committed
721
  size_t getCurrentGeneration() { return currentGeneration;}
maitre's avatar
maitre committed
722 723 724 725 726
  void cudaParentEvaluate();
  void cudaOffspringEvaluate(void* d_offspringPopulation, float* fitnesses, dim3 dimBlock, dim3 dimGrid);
  void cudaPreliminaryProcess(size_t populationSize, dim3* dimBlock, dim3* dimGrid, void** allocatedDeviceBuffer,
						     float** deviceFitness);
  
maitre's avatar
maitre committed
727

maitre's avatar
maitre committed
728
public:
maitre's avatar
maitre committed
729 730 731 732
  size_t currentGeneration;
  Population* population;
  size_t reduceParents;
  size_t reduceOffsprings;
maitre's avatar
maitre committed
733 734 735 736
  //void showPopulationStats();
  void showPopulationStats(struct timeval beginTime);
  

maitre's avatar
maitre committed
737
  std::vector<StoppingCriterion*> stoppingCriteria;
maitre's avatar
maitre committed
738 739 740

  std::string* outputfile;
  std::string* inputfile;
maitre's avatar
maitre committed
741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757
};


#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
758 759 760
#include <boost/program_options.hpp>
#include <boost/program_options/errors.hpp>

maitre's avatar
maitre committed
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

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
792
  //DEBUG_PRT("Int Random Value : %d",min+rValue);
maitre's avatar
maitre committed
793 794 795 796 797 798 799 800 801 802
  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
803
  //DEBUG_PRT("Float Random Value : %f",min+rValue);
maitre's avatar
maitre committed
804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826
  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
827 828
void MaxTournament::initialize(Individual** population, float selectionPressure, size_t populationSize) {
  SelectionOperator::initialize(population,selectionPressure,populationSize);
maitre's avatar
maitre committed
829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877
}


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
878 879
void MinTournament::initialize(Individual** population, float selectionPressure, size_t populationSize) {
  SelectionOperator::initialize(population,selectionPressure,populationSize);
maitre's avatar
maitre committed
880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932
}

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
933
void SelectionOperator::initialize(Individual** population, float selectionPressure, size_t populationSize){
maitre's avatar
maitre committed
934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968
  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
969 970
Population::Population(){
}
maitre's avatar
maitre committed
971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990

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
991 992 993 994 995 996 997 998 999 1000 1001 1002
  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
1003

maitre's avatar
maitre committed
1004 1005 1006 1007 1008 1009
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
1010 1011 1012 1013 1014 1015 1016 1017
}

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
1018 1019 1020

  free(cudaParentBuffer);
  free(cudaOffspringBuffer);
maitre's avatar
maitre committed
1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034
}

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
1035 1036
  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
1037 1038 1039 1040 1041 1042 1043 1044 1045
    parents[i] = new Individual();

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


maitre's avatar
maitre committed
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
/**
   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
1068 1069 1070
void Population::evaluatePopulation(Individual** population, size_t populationSize){
  for( size_t i=0 ; i < populationSize ; i++ )
    population[i]->evaluate();
maitre's avatar
maitre committed
1071
  currentEvaluationNb += populationSize;
maitre's avatar
maitre committed
1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
}


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
1094
void Population::reducePopulation(Individual** population, size_t populationSize,
maitre's avatar
maitre committed
1095 1096 1097 1098
					  Individual** reducedPopulation, size_t obSize,
					  SelectionOperator* replacementOperator){
  

maitre's avatar
maitre committed
1099
  replacementOperator->initialize(population,replacementPressure,populationSize);
maitre's avatar
maitre committed
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 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 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160

  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
1161 1162 1163 1164 1165 1166 1167 1168
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
1169 1170 1171 1172
void Population::sortPopulation(Individual** population, size_t populationSize){
  qsort(population,populationSize,sizeof(Individual*),individualCompare);
}

maitre's avatar
maitre committed
1173 1174 1175 1176
void Population::sortRPopulation(Individual** population, size_t populationSize){
  qsort(population,populationSize,sizeof(Individual*),individualRCompare);
}

maitre's avatar
maitre committed
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197

/**
   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
1198

maitre's avatar
maitre committed
1199 1200 1201
  memcpy(globalPopulation,parents,sizeof(Individual*)*actualParentPopulationSize);
  memcpy(globalPopulation+actualParentPopulationSize,offsprings,
   	 sizeof(Individual*)*actualOffspringPopulationSize);
maitre's avatar
maitre committed
1202
  replacementOperator->initialize(globalPopulation, replacementPressure,actualGlobalSize);
maitre's avatar
maitre committed
1203 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

#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
1234
  selectionOperator->initialize(parents,selectionPressure,actualParentPopulationSize);
maitre's avatar
maitre committed
1235 1236

  for( size_t i=0 ; i<offspringPopulationSize ; i++ ){
maitre's avatar
maitre committed
1237
    size_t index = selectionOperator->selectNext(parentPopulationSize);
maitre's avatar
maitre committed
1238 1239 1240 1241
    p1 = parents[index];
    
    if( rg->tossCoin(pCrossover) ){
      for( size_t j=0 ; j<crossoverArrity-1 ; j++ ){
maitre's avatar
maitre committed
1242
	index = selectionOperator->selectNext(parentPopulationSize);
maitre's avatar
maitre committed
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
	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
1271
void Population::elitism(size_t elitismSize, Individual** population, size_t populationSize, 
maitre's avatar
maitre committed
1272 1273
			 Individual** outPopulation, size_t outPopulationSize){
  
maitre's avatar
maitre committed
1274 1275
  float bestFitness = population[0]->getFitness();
  size_t bestIndividual = 0;
maitre's avatar
maitre committed
1276
  
maitre's avatar
maitre committed
1277
  if( elitismSize >= 5 )DEBUG_PRT("Warning, elitism has O(n) complexity, elitismSize is maybe too big (%lu)",elitismSize);
maitre's avatar
maitre committed
1278 1279 1280 1281 1282 1283
  
  
  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
1284
#if \MINIMAXI
maitre's avatar
maitre committed
1285
      if( bestFitness < population[j]->getFitness() ){
maitre's avatar
maitre committed
1286 1287 1288
#else
      if( bestFitness > population[j]->getFitness() ){
#endif
maitre's avatar
maitre committed
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
	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
1316
    O << "\t\t" << *B.parents[i] ;
maitre's avatar
maitre committed
1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328
  } 

  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
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 1398 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 1454 1455 1456 1457 1458 1459 1460 1461 1462 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
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
1523

maitre's avatar
maitre committed
1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578
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
1579 1580 1581 1582 1583
   Some tools classes for algorithm
****************************************/
#include <stdlib.h>
#include <vector>
#include <iostream>
maitre's avatar
maitre committed
1584 1585 1586 1587
/* #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
1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651
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
1652
  virtual void initialize(Individual** population, float selectionPressure, size_t populationSize);
maitre's avatar
maitre committed
1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666
  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
1667
  virtual void initialize(Individual** population, float selectionPressure, size_t populationSize);
maitre's avatar
maitre committed
1668 16