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 53.6 KB
Newer Older
maitre's avatar
maitre committed
1
2
3
4
5
6
\TEMPLATE_START/**
 This is program entry for CUDA template for EASEA

*/
\ANALYSE_PARAMETERS
using namespace std;
7
8
9
10
11
12
13
14
15
16
17
18


class Individual;

#include <stdlib.h>
/** Global variables for the whole algorithm */
Individual** pPopulation = NULL;
float* pEZ_MUT_PROB = NULL;
float* pEZ_XOVER_PROB = NULL;
size_t *EZ_NB_GEN;
size_t *EZ_current_generation;

maitre's avatar
maitre committed
19
20
21
#include <iostream>
#include "EASEATools.hpp"
#include "EASEAIndividual.hpp"
maitre's avatar
maitre committed
22
#include <time.h>
maitre's avatar
maitre committed
23
24


maitre's avatar
maitre committed
25

26
27
RandomGenerator* globalRandomGenerator;

maitre's avatar
maitre committed
28
29
int main(int argc, char** argv){

maitre's avatar
maitre committed
30
31
32
33
34

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

  size_t parentPopulationSize = setVariable("popSize",\POP_SIZE);
  size_t offspringPopulationSize = setVariable("nbOffspring",\OFF_SIZE);
maitre's avatar
maitre committed
35
36
37
38
  float pCrossover = \XOVER_PROB;
  float pMutation = \MUT_PROB;
  float pMutationPerGene = 0.05;

39
40
41
42
43
  pEZ_MUT_PROB = &pMutationPerGene;
  pEZ_XOVER_PROB = &pCrossover;
  EZ_NB_GEN = (size_t*)setVariable("nbGen",\NB_GEN);
  EZ_current_generation=0;

maitre's avatar
maitre committed
44
45
46
47
  time_t seed = setVariable("seed",time(0));
  globalRandomGenerator = new RandomGenerator(seed);

  std::cout << "Seed is : " << seed << std::endl;
maitre's avatar
maitre committed
48
49
50

  SelectionOperator* selectionOperator = new \SELECTOR;
  SelectionOperator* replacementOperator = new \RED_FINAL;
51
52
  SelectionOperator* parentReductionOperator = new \RED_PAR;
  SelectionOperator* offspringReductionOperator = new \RED_OFF;
maitre's avatar
maitre committed
53
54
  float selectionPressure = \SELECT_PRM;
  float replacementPressure = \RED_FINAL_PRM;
55
56
57
  float parentReductionPressure = \RED_PAR_PRM;
  float offspringReductionPressure = \RED_OFF_PRM;

maitre's avatar
maitre committed
58
59
  string outputfile = setVariable("outputfile","");
  string inputfile = setVariable("inputfile","");
60
  
maitre's avatar
maitre committed
61
  EASEAInit(argc,argv);
maitre's avatar
maitre committed
62
    
63
64
65
  EvolutionaryAlgorithm ea(parentPopulationSize,offspringPopulationSize,selectionPressure,replacementPressure,parentReductionPressure,offspringReductionPressure,
			   selectionOperator,replacementOperator,parentReductionOperator, offspringReductionOperator, pCrossover, pMutation, pMutationPerGene,
			   outputfile,inputfile);
maitre's avatar
maitre committed
66

maitre's avatar
maitre committed
67
  StoppingCriterion* sc = new GenerationalCriterion(&ea,setVariable("nbGen",\NB_GEN));
maitre's avatar
maitre committed
68
  ea.addStoppingCriterion(sc);
69
70
71
72
  
  EZ_NB_GEN=((GenerationalCriterion*)ea.stoppingCriteria[0])->getGenerationalLimit();
  EZ_current_generation=&(ea.currentGeneration);
 
maitre's avatar
maitre committed
73
74
75
76
77
78
79
80
81
  Population* pop = ea.getPopulation();


  ea.runEvolutionaryLoop();

  EASEAFinal(pop);

  delete pop;
  delete sc;
maitre's avatar
maitre committed
82
83
84
85
  delete selectionOperator;
  delete replacementOperator;
  delete globalRandomGenerator;

maitre's avatar
maitre committed
86
87
88
89
90
91
92
93

  return 0;
}


\START_CUDA_GENOME_CU_TPL
#include "EASEAIndividual.hpp"
#include "EASEAUserClasses.hpp"
maitre's avatar
maitre committed
94
95
96
#include <string.h>
#include <fstream>
#include <sys/time.h>
97
#include <EASEATools.hpp>
maitre's avatar
maitre committed
98

99
#define CUDA_TPL
maitre's avatar
maitre committed
100
101
102
extern RandomGenerator* globalRandomGenerator;

\INSERT_USER_DECLARATIONS
maitre's avatar
maitre committed
103
104
struct gpuOptions initOpts;

maitre's avatar
maitre committed
105
106
107
108
109
110
\ANALYSE_USER_CLASSES

\INSERT_USER_FUNCTIONS

\INSERT_INITIALISATION_FUNCTION
\INSERT_FINALIZATION_FUNCTION
maitre's avatar
maitre committed
111
\INSERT_GENERATION_FUNCTION
maitre's avatar
maitre committed
112

113
114
\INSERT_BEGIN_GENERATION_FUNCTION
\INSERT_END_GENERATION_FUNCTION
maitre's avatar
maitre committed
115

116
\INSERT_BOUND_CHECKING
maitre's avatar
maitre committed
117

maitre's avatar
maitre committed
118
119
120
121
void EASEAFinal(Population* pop){
  \INSERT_FINALIZATION_FCT_CALL
}

maitre's avatar
maitre committed
122
123
124
125
126
void EASEAInit(int argc, char** argv){
  \INSERT_INIT_FCT_CALL
}


maitre's avatar
maitre committed
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
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
152
153
154
/**
   This function allows to acces to the Individual stored in cudaBuffer as a standard
   individual.
maitre's avatar
maitre committed
155
   @TODO This should be a macro, at this time it is a function for debuging purpose
maitre's avatar
maitre committed
156
157
158
159
160
161
*/
__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
162
__device__ float cudaEvaluate(void* devBuffer, size_t id, struct gpuOptions initOpts){
maitre's avatar
maitre committed
163
164
165
  \INSERT_CUDA_EVALUATOR
}

maitre's avatar
maitre committed
166
inline void Individual::copyToCudaBuffer(void* buffer, size_t id){
maitre's avatar
maitre committed
167
168
169
170
171
  
  memcpy(((char*)buffer)+(\GENOME_SIZE+sizeof(Individual*))*id,((char*)this),\GENOME_SIZE+sizeof(Individual*));
  
}

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
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);

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

    child1.valid = false;
  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
209
210
  O << "\nIndividual : "<< std::endl;
  O << "\t\t\t";
maitre's avatar
maitre committed
211
212
  B.printOn(O);
    
213
214
  if( B.valid ) O << "\t\t\tfitness : " << B.fitness;
  else O << "fitness is not yet computed" << std::endl;
maitre's avatar
maitre committed
215
216
217
218
219
220
  return O; 
} 


size_t Individual::mutate( float pMutationPerGene ){
  this->valid=false;
221
222


maitre's avatar
maitre committed
223
224
225
226
227
228
229
230
231
232
  // ********************
  // Problem specific part
  \INSERT_MUTATOR  
}

/* ****************************************
   EvolutionaryAlgorithm class
****************************************/
EvolutionaryAlgorithm::EvolutionaryAlgorithm( size_t parentPopulationSize,
					      size_t offspringPopulationSize,
233
					      float selectionPressure, float replacementPressure, float parentReductionPressure, float offspringReductionPressure,
maitre's avatar
maitre committed
234
					      SelectionOperator* selectionOperator, SelectionOperator* replacementOperator,
235
					      SelectionOperator* parentReductionOperator, SelectionOperator* offspringReductionOperator,
maitre's avatar
maitre committed
236
					      float pCrossover, float pMutation, 
maitre's avatar
maitre committed
237
					      float pMutationPerGene, string& outputfile, string& inputfile){
maitre's avatar
maitre committed
238
239
240
241
242
243
244

  RandomGenerator* rg = globalRandomGenerator;

  SelectionOperator* so = selectionOperator;
  SelectionOperator* ro = replacementOperator;
  
  Individual::initRandomGenerator(rg);
245
  Population::initPopulation(so,ro,parentReductionOperator,offspringReductionOperator,selectionPressure,replacementPressure,parentReductionPressure,offspringReductionPressure);
maitre's avatar
maitre committed
246
247
248
249
250
251
252
253
254
  
  this->population = new Population(parentPopulationSize,offspringPopulationSize,
				    pCrossover,pMutation,pMutationPerGene,rg);

  this->currentGeneration = 0;

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

maitre's avatar
maitre committed
255
256
257
258
259
260
261
262
263
264
265
266
267
268
  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;
  


}

269

maitre's avatar
maitre committed
270
271
// do the repartition of data accross threads
__global__ void 
maitre's avatar
maitre committed
272
cudaEvaluatePopulation(void* d_population, size_t popSize, float* d_fitnesses, struct gpuOptions initOpts){
maitre's avatar
maitre committed
273
274
275
276
277
278

  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
279
  //void* indiv = ((char*)d_population)+id*(\GENOME_SIZE+sizeof(Individual*)); // compute the offset of the current individual
maitre's avatar
maitre committed
280

maitre's avatar
maitre committed
281
282
  d_fitnesses[id] = cudaEvaluate(d_population,id,initOpts);

maitre's avatar
maitre committed
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
}


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

maitre's avatar
maitre committed
305
306
307
308
309
310
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
311
312
  DEBUG_PRT("repartition : %d",popSize);
  
maitre's avatar
maitre committed
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
  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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
/**
   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
367
  if( !repartition(populationSize, &nbBlock, &nbThreadPB, &nbThreadLB,30, 240))
maitre's avatar
maitre committed
368
369
370
371
372
373
374
375
376
377
378
379
380
381
    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
382

maitre's avatar
maitre committed
383
384
385
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
386
  float* fitnesses = new float[actualPopulationSize];
maitre's avatar
maitre committed
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406

  
  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
407
408
409
410
411
    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
412
#else
maitre's avatar
maitre committed
413
    DEBUG_PRT("%lu : %f\n",i,fitnesses[i]);
maitre's avatar
maitre committed
414
415
416
417
418
419
420
421
422
423
424
425
426
    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
427
428
429
  void* allocatedDeviceBuffer;
  float* deviceFitness;
  cudaError_t lastError;
maitre's avatar
maitre committed
430
431
432
433
  dim3 dimBlock, dimGrid;
  size_t actualPopulationSize = this->population->actualParentPopulationSize;

  cudaPreliminaryProcess(actualPopulationSize,&dimBlock,&dimGrid,&allocatedDeviceBuffer,&deviceFitness);
maitre's avatar
maitre committed
434
435
    
  //compute the repartition over MP and SP
maitre's avatar
maitre committed
436
437
438
  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
439
440


maitre's avatar
maitre committed
441
  cudaEvaluatePopulation<<< dimGrid, dimBlock>>>(allocatedDeviceBuffer,actualPopulationSize,deviceFitness,initOpts);
maitre's avatar
ok    
maitre committed
442
  lastError = cudaThreadSynchronize();
maitre's avatar
maitre committed
443
444
445
446
447
448
449
450
451
452
453
454
455
456
  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
457
458
459
460
461
    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
462
#else
maitre's avatar
ok    
maitre committed
463
    DEBUG_PRT("%lu : %f\n",i,fitnesses[i]);
maitre's avatar
maitre committed
464
465
466
467
    population->parents[i]->fitness = fitnesses[i];
    population->parents[i]->valid = true;
#endif
  }
maitre's avatar
maitre committed
468
469
}

470

maitre's avatar
maitre committed
471
472
473
474
475
void EvolutionaryAlgorithm::addStoppingCriterion(StoppingCriterion* sc){
  this->stoppingCriteria.push_back(sc);
}

void EvolutionaryAlgorithm::runEvolutionaryLoop(){
maitre's avatar
maitre committed
476
477
  std::vector<Individual*> tmpVect;

maitre's avatar
maitre committed
478
479

  std::cout << "Parent's population initializing "<< std::endl;
maitre's avatar
maitre committed
480
481
  this->population->initializeCudaParentPopulation();
  cudaParentEvaluate();
maitre's avatar
maitre committed
482

483
  std::cout << *population << std::endl;
maitre's avatar
maitre committed
484
485
486
487
488
489
490

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

maitre's avatar
maitre committed
491
492
493
494
495
  void* d_offspringPopulation;
  float* d_fitnesses;
  dim3 dimBlock, dimGrid;

  cudaPreliminaryProcess(this->population->offspringPopulationSize,&dimBlock,&dimGrid,&d_offspringPopulation,&d_fitnesses);
maitre's avatar
maitre committed
496
497
498
  
  while( this->allCriteria() == false ){    

499
    \INSERT_BEGINNING_GEN_FCT_CALL
maitre's avatar
maitre committed
500
    population->produceOffspringPopulation();
maitre's avatar
maitre committed
501

maitre's avatar
maitre committed
502
    \INSERT_BOUND_CHECKING_FCT_CALL
503
      
maitre's avatar
maitre committed
504
    TIME_ST(eval);
maitre's avatar
maitre committed
505
506
507
508
    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
509
510
    TIME_END(eval);

maitre's avatar
ok    
maitre committed
511
512
    COMPUTE_TIME(eval);
    //SHOW_TIME(eval);
maitre's avatar
maitre committed
513
514
    timeradd(&accuEval,&eval_res,&accuEval);

515
    \INSERT_END_GEN_FCT_CALL
maitre's avatar
maitre committed
516

517
518
519
#if \IS_PARENT_REDUCTION
      population->reduceParentPopulation(\SURV_PAR_SIZE);
#endif
maitre's avatar
maitre committed
520
    
521
522
523
524

#if \IS_OFFSPRING_REDUCTION
      population->reduceOffspringPopulation(\SURV_OFF_SIZE);
#endif
maitre's avatar
maitre committed
525
526
    
    population->reduceTotalPopulation();
527
528

    \INSERT_GEN_FCT_CALL         
maitre's avatar
maitre committed
529

maitre's avatar
ok    
maitre committed
530
    showPopulationStats(begin);
maitre's avatar
maitre committed
531
532
533
    currentGeneration += 1;
  }  
  population->sortParentPopulation();
534
  //std::cout << *population << std::endl;
maitre's avatar
maitre committed
535
536
537
538
  std::cout << "Generation : " << currentGeneration << std::endl;
}


maitre's avatar
maitre committed
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
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)
567
    printf("GEN\tTIME\t\tEVAL\tBEST\t\tAVG\t\tSTDEV\n\n");
maitre's avatar
maitre committed
568

569
    //  assert( currentSTDEV == currentSTDEV );
maitre's avatar
maitre committed
570
571
572
573
  
  struct timeval end, res;
  gettimeofday(&end,0);
  timersub(&end,&beginTime,&res);
574
  printf("%lu\t%d.%06d\t%lu\t%f\t%f\t%f\n",currentGeneration,res.tv_sec,res.tv_usec,population->currentEvaluationNb,
maitre's avatar
maitre committed
575
576
577
	 population->Best->getFitness(),currentAverageFitness,currentSTDEV);
}

maitre's avatar
maitre committed
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
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
603
#include <vector_types.h>
maitre's avatar
maitre committed
604

maitre's avatar
maitre committed
605
606
607

\INSERT_USER_CLASSES_DEFINITIONS

maitre's avatar
maitre committed
608
void EASEAInit(int argc, char *argv[]);
maitre's avatar
maitre committed
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
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
631
  void copyToCudaBuffer(void* buffer, size_t id);
maitre's avatar
maitre committed
632
633
634
635
636
637
638
639
640
641
642
643
644

  friend std::ostream& operator << (std::ostream& O, const Individual& B) ;
  static void initRandomGenerator(RandomGenerator* rg){ Individual::rg = rg;}

  
};


/* ****************************************
   EvolutionaryAlgorithm class
****************************************/
class EvolutionaryAlgorithm{
public:
645
646
647
648
649
650
651
/*   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, float parentReductionPressure, float offspringReductionPressure,
maitre's avatar
maitre committed
652
			 SelectionOperator* selectionOperator, SelectionOperator* replacementOperator,
653
			 SelectionOperator* parentReductionOperator, SelectionOperator* offspringReductionOperator,
maitre's avatar
maitre committed
654
			 float pCrossover, float pMutation, 
maitre's avatar
maitre committed
655
			 float pMutationPerGene, std::string& outputfile, std::string& inputfile);
maitre's avatar
maitre committed
656
657
658
659
660
661

  size_t* getCurrentGenerationPtr(){ return &currentGeneration;}
  void addStoppingCriterion(StoppingCriterion* sc);
  void runEvolutionaryLoop();
  bool allCriteria();
  Population* getPopulation(){ return population;}
maitre's avatar
maitre committed
662
  size_t getCurrentGeneration() { return currentGeneration;}
663

maitre's avatar
maitre committed
664
665
666
  void cudaParentEvaluate();
  void cudaOffspringEvaluate(void* d_offspringPopulation, float* fitnesses, dim3 dimBlock, dim3 dimGrid);
  void cudaPreliminaryProcess(size_t populationSize, dim3* dimBlock, dim3* dimGrid, void** allocatedDeviceBuffer,
667
					     float** deviceFitness);
maitre's avatar
maitre committed
668
  
maitre's avatar
maitre committed
669

maitre's avatar
maitre committed
670
public:
maitre's avatar
maitre committed
671
672
673
674
  size_t currentGeneration;
  Population* population;
  size_t reduceParents;
  size_t reduceOffsprings;
maitre's avatar
maitre committed
675
676
677
678
  //void showPopulationStats();
  void showPopulationStats(struct timeval beginTime);
  

maitre's avatar
maitre committed
679
  std::vector<StoppingCriterion*> stoppingCriteria;
maitre's avatar
maitre committed
680
681
682

  std::string* outputfile;
  std::string* inputfile;
maitre's avatar
maitre committed
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
};


#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
700
701
702
#include <boost/program_options.hpp>
#include <boost/program_options/errors.hpp>

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

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
734
  //DEBUG_PRT("Int Random Value : %d",min+rValue);
maitre's avatar
maitre committed
735
736
737
738
739
740
741
742
743
744
  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
745
  //DEBUG_PRT("Float Random Value : %f",min+rValue);
maitre's avatar
maitre committed
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
  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
769
770
void MaxTournament::initialize(Individual** population, float selectionPressure, size_t populationSize) {
  SelectionOperator::initialize(population,selectionPressure,populationSize);
maitre's avatar
maitre committed
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
808
809
810
811
812
813
814
815
816
817
818
819
}


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
820
821
void MinTournament::initialize(Individual** population, float selectionPressure, size_t populationSize) {
  SelectionOperator::initialize(population,selectionPressure,populationSize);
maitre's avatar
maitre committed
822
823
824
825
826
827
828
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
}

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
875
void SelectionOperator::initialize(Individual** population, float selectionPressure, size_t populationSize){
maitre's avatar
maitre committed
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
  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;
}

900
901
902
size_t* GenerationalCriterion::getGenerationalLimit(){
	return &(this->generationalLimit);
}
maitre's avatar
maitre committed
903
904
905
906
907
908

/* ****************************************
   Population class
****************************************/
SelectionOperator* Population::selectionOperator;
SelectionOperator* Population::replacementOperator;
909
910
911
SelectionOperator* Population::parentReductionOperator;
SelectionOperator* Population::offspringReductionOperator;

maitre's avatar
maitre committed
912
913
914

float Population::selectionPressure;
float Population::replacementPressure;
915
916
917
float Population::parentReductionPressure;
float Population::offspringReductionPressure;

maitre's avatar
maitre committed
918
919


maitre's avatar
maitre committed
920
921
Population::Population(){
}
maitre's avatar
maitre committed
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937

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;
938
939
  pEZ_MUT_PROB = &this->pMutation;
  pEZ_XOVER_PROB = &this->pCrossover;
maitre's avatar
maitre committed
940
  this->pMutationPerGene = pMutationPerGene;
941
  pPopulation = parents;
maitre's avatar
maitre committed
942
943
944

  this->rg = rg;

maitre's avatar
maitre committed
945
946
947
948
949
950
951
952
953
954
955
  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
956

maitre's avatar
maitre committed
957
958
959
960
961
void Population::syncOutVector(){
  pop_vect.clear();
  for( size_t i = 0 ; i<actualParentPopulationSize ; i++ ){
    pop_vect.push_back(parents[i]);
  }
962
  DEBUG_PRT("Size of outVector",pop_vect.size());
maitre's avatar
maitre committed
963
964
965
966
967
968
969
970
971
972
973
974
}

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);
}

void Population::initPopulation(SelectionOperator* selectionOperator, 
				SelectionOperator* replacementOperator,
975
976
977
978
				SelectionOperator* parentReductionOperator,
				SelectionOperator* offspringReductionOperator,
				float selectionPressure, float replacementPressure,
				float parentReductionPressure, float offspringReductionPressure){
maitre's avatar
maitre committed
979
980
  Population::selectionOperator   = selectionOperator;
  Population::replacementOperator = replacementOperator;
981
982
983
  Population::parentReductionOperator = parentReductionOperator;
  Population::offspringReductionOperator = offspringReductionOperator;

maitre's avatar
maitre committed
984
985
  Population::selectionPressure   = selectionPressure;
  Population::replacementPressure = replacementPressure;
986
987
988
  Population::parentReductionPressure = parentReductionPressure;
  Population::offspringReductionPressure = offspringReductionPressure;

maitre's avatar
maitre committed
989
990
991
992
993
}


void Population::initializeParentPopulation(){

994
  DEBUG_PRT("Creation of %d/%d parents (other could have been loaded from input file)",parentPopulationSize-actualParentPopulationSize,parentPopulationSize);
maitre's avatar
maitre committed
995
  for( size_t i=actualParentPopulationSize ; i<parentPopulationSize ; i++ )
maitre's avatar
maitre committed
996
997
998
999
1000
1001
1002
1003
    parents[i] = new Individual();

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

maitre's avatar
maitre committed
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
/**
   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); 
  }

}


1026

maitre's avatar
maitre committed
1027
1028
1029
void Population::evaluatePopulation(Individual** population, size_t populationSize){
  for( size_t i=0 ; i < populationSize ; i++ )
    population[i]->evaluate();
maitre's avatar
maitre committed
1030
  currentEvaluationNb += populationSize;
maitre's avatar
maitre committed
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
}


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
1053
void Population::reducePopulation(Individual** population, size_t populationSize,
maitre's avatar
maitre committed
1054
1055
1056
1057
					  Individual** reducedPopulation, size_t obSize,
					  SelectionOperator* replacementOperator){
  

maitre's avatar
maitre committed
1058
  replacementOperator->initialize(population,replacementPressure,populationSize);
maitre's avatar
maitre committed
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095

  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;
}


1096

maitre's avatar
maitre committed
1097
Individual** Population::reduceOffspringPopulation(size_t obSize){
1098
1099
1100
1101
  // this array has offspringPopulationSize because it will be used as offspring population in
  // the next generation
  Individual** nextGeneration = new Individual*[offspringPopulationSize]; 
  
maitre's avatar
maitre committed
1102
1103
1104
1105
1106
1107

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

  // free no longer needed individuals
  for( size_t i=0 ; i<actualOffspringPopulationSize-obSize ; i++ )
1108
1109
    delete(offsprings[i]);
  delete[](offsprings);
maitre's avatar
maitre committed
1110

1111
1112
  this->actualOffspringPopulationSize = obSize;
  offsprings = nextGeneration;
maitre's avatar
maitre committed
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
  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
1124
1125
1126
1127
1128
1129
1130
1131
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
1132
1133
1134
1135
void Population::sortPopulation(Individual** population, size_t populationSize){
  qsort(population,populationSize,sizeof(Individual*),individualCompare);
}

maitre's avatar
maitre committed
1136
1137
1138
1139
void Population::sortRPopulation(Individual** population, size_t populationSize){
  qsort(population,populationSize,sizeof(Individual*),individualRCompare);
}

maitre's avatar
maitre committed
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160

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

maitre's avatar
maitre committed
1162
1163
1164
  memcpy(globalPopulation,parents,sizeof(Individual*)*actualParentPopulationSize);
  memcpy(globalPopulation+actualParentPopulationSize,offsprings,
   	 sizeof(Individual*)*actualOffspringPopulationSize);
maitre's avatar
maitre committed
1165
  replacementOperator->initialize(globalPopulation, replacementPressure,actualGlobalSize);
maitre's avatar
maitre committed
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176

#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);

1177
  for( size_t i=0 ; i<((int)actualGlobalSize+\ELITE_SIZE)-(int)parentPopulationSize ; i++ )
maitre's avatar
maitre committed
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
    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
1197
  selectionOperator->initialize(parents,selectionPressure,actualParentPopulationSize);
maitre's avatar
maitre committed
1198
1199

  for( size_t i=0 ; i<offspringPopulationSize ; i++ ){
maitre's avatar
maitre committed
1200
    size_t index = selectionOperator->selectNext(parentPopulationSize);
maitre's avatar
maitre committed
1201
1202
1203
1204
    p1 = parents[index];
    
    if( rg->tossCoin(pCrossover) ){
      for( size_t j=0 ; j<crossoverArrity-1 ; j++ ){
maitre's avatar
maitre committed
1205
	index = selectionOperator->selectNext(parentPopulationSize);
maitre's avatar
maitre committed
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
	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
1234
void Population::elitism(size_t elitismSize, Individual** population, size_t populationSize, 
maitre's avatar
maitre committed
1235
1236
			 Individual** outPopulation, size_t outPopulationSize){
  
maitre's avatar
maitre committed
1237
1238
  float bestFitness = population[0]->getFitness();
  size_t bestIndividual = 0;
maitre's avatar
maitre committed
1239
  
1240
  if( elitismSize >= 5 )DEBUG_PRT("Warning, elitism has O(n) complexity, elitismSize is maybe too big (%d)",elitismSize);
maitre's avatar
maitre committed
1241
1242
1243
1244
1245
1246
  
  
  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
1247
#if \MINIMAXI
maitre's avatar
maitre committed
1248
      if( bestFitness < population[j]->getFitness() ){
maitre's avatar
maitre committed
1249
1250
1251
#else
      if( bestFitness > population[j]->getFitness() ){
#endif
maitre's avatar
maitre committed
1252
1253
1254
1255
1256
1257
1258
1259
1260
	bestFitness = population[j]->getFitness();
	bestIndividual = j;
      }
    }
    outPopulation[i] = population[bestIndividual];
    population[bestIndividual] = population[populationSize-(i+1)];
    population[populationSize-(i+1)] = NULL;
  }
}
1261
 
maitre's avatar
maitre committed
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279



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
1280
    O << "\t\t" << *B.parents[i] ;
maitre's avatar
maitre committed
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
  } 

  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
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
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
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
1487

maitre's avatar
maitre committed
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
1528
1529
1530
1531
1532
1533
1534
1535
1536
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

1537

maitre's avatar
maitre committed
1538
/* ****************************************
maitre's avatar
maitre committed
1539
1540
1541
1542
1543
   Some tools classes for algorithm
****************************************/
#include <stdlib.h>
#include <vector>
#include <iostream>
maitre's avatar
maitre committed
1544

maitre's avatar
maitre committed
1545
1546
1547
1548
class EvolutionaryAlgorithm;
class Individual;
class Population;

1549
1550
1551
1552
1553
1554
1555
1556
extern float* pEZ_MUT_PROB;
extern float* pEZ_XOVER_PROB;
extern Individual** pPopulation;


extern size_t *EZ_NB_GEN;
extern size_t *EZ_current_generation;

1557
1558
1559
1560
1561
#define EZ_MINIMIZE \MINIMAXI
#define EZ_MINIMISE \MINIMAXI
#define EZ_MAXIMIZE !\MINIMAXI
#define EZ_MAXIMISE !\MINIMAXI

maitre's avatar
maitre committed
1562
1563
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
#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);
1594
  size_t *getGenerationalLimit();
maitre's avatar
maitre committed
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
};


/* ****************************************
   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);
1613

maitre's avatar
maitre committed
1614
1615
1616
1617
1618
1619
1620
1621
1622
};



/* ****************************************
   Selection Operator class
****************************************/
class SelectionOperator{
public:
maitre's avatar
maitre committed
1623
  virtual void initialize(Individual** population, float selectionPressure, size_t populationSize);
maitre's avatar
maitre committed
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
  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
1638
  virtual void initialize(Individual** population, float selectionPressure, size_t populationSize);
maitre's avatar
maitre committed
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
  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
1651
  virtual void initialize(Individual** population, float selectionPressure, size_t populationSize);
maitre's avatar
maitre committed
1652
1653
1654
1655
1656
1657
1658
  virtual size_t selectNext(size_t populationSize);
  float getExtremum();
private:
  RandomGenerator* rg;
  
};

maitre's avatar
maitre committed
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704

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
1705
1706
class Population {
  
maitre's avatar
maitre committed
1707
 public:
maitre's avatar
maitre committed
1708
1709
1710
1711
  
  float pCrossover;
  float pMutation;
  float pMutationPerGene;
maitre's avatar
maitre committed
1712
1713

  Individual* Best;
maitre's avatar
maitre committed
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
  
  Individual** parents;
  Individual** offsprings;

  size_t parentPopulationSize;
  size_t offspringPopulationSize;

  size_t actualParentPopulationSize;
  size_t actualOffspringPopulationSize;

  static SelectionOperator* selectionOperator;
  static SelectionOperator* replacementOperator;
1726
1727
  static SelectionOperator* parentReductionOperator;
  static SelectionOperator* offspringReductionOperator;
maitre's avatar
maitre committed
1728

maitre's avatar
maitre committed
1729
  size_t currentEvaluationNb;
maitre's avatar
maitre committed
1730
  RandomGenerator* rg;
maitre's avatar
maitre committed
1731
  std::vector<Individual*> pop_vect;
maitre's avatar
maitre committed
1732

maitre's avatar
maitre committed
1733
1734
  void* cudaParentBuffer;
  void* cudaOffspringBuffer;
maitre's avatar
maitre committed
1735

maitre's avatar
maitre committed
1736
1737
 public:
  Population();
maitre's avatar
maitre committed
1738
1739
1740
1741
1742
  Population(size_t parentPopulationSize, size_t offspringPopulationSize, 
	     float pCrossover, float pMutation, float pMutationPerGene, RandomGenerator* rg);
  virtual ~Population();

  void initializeParentPopulation();  
maitre's avatar
maitre committed
1743
  void initializeCudaParentPopulation();
maitre's avatar
maitre committed
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
  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;
1760
1761
1762
  static float parentReductionPressure;
  static float offspringReductionPressure;

maitre's avatar
maitre committed
1763
1764
  static void initPopulation(SelectionOperator* selectionOperator, 
			     SelectionOperator* replacementOperator,
1765
1766
1767
1768
			     SelectionOperator* parentReductionOperator,
			     SelectionOperator* offspringReductionOperator,
			     float selectionPressure, float replacementPressure,
			     float parentReductionPressure, float offspringReductionPressure);
maitre's avatar
maitre committed
1769
1770
1771

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

maitre's avatar
maitre committed
1772
1773
1774
  static void sortRPopulation(Individual** population, size_t populationSize);


maitre's avatar
maitre committed
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
  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
1787
  static void reducePopulation(Individual** population, size_t populationSize,
maitre's avatar
maitre committed
1788
1789
				       Individual** reducedPopulation, size_t obSize,
				       SelectionOperator* replacementOperator);
maitre's avatar
maitre committed
1790
1791
1792
  void syncOutVector();
  void syncInVector();

maitre's avatar
maitre committed
1793
1794
};

maitre's avatar
maitre committed
1795
1796
1797
1798
1799
1800

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
1801
1802
1803
1804

#endif


maitre's avatar
maitre committed
1805

maitre's avatar
maitre committed
1806
1807
1808
1809
\START_CUDA_MAKEFILE_TPL

NVCC= nvcc
CPPC= g++
maitre's avatar
maitre committed
1810
CXXFLAGS+=-g -Wall -O2
1811
LDFLAGS=-lboost_program_options
maitre's avatar
maitre committed
1812
1813
1814

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

maitre's avatar
ok    
maitre committed
1816
CPPFLAGS+=
1817
NVCCFLAGS+=
maitre's avatar
maitre committed
1818

maitre's avatar
maitre committed
1819
1820

EASEA_SRC= EASEATools.cpp EASEAIndividual.cpp
maitre's avatar
maitre committed
1821
1822
1823
1824
1825
EASEA_MAIN_HDR= EASEA.cpp
EASEA_UC_HDR= EASEAUserClasses.hpp

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

maitre's avatar
maitre committed
1826
1827
1828
1829
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
1830
1831
1832
1833
1834
1835

BIN= EASEA
  
all:$(BIN)

$(BIN):$(OBJ)
maitre's avatar
maitre committed
1836
1837
1838
	$(NVCC) $^ -o $@ $(LDFLAGS) 

%.o:%.cu
1839
	$(NVCC) $(NVCCFLAGS) -o $@ $< -c -DTIMING $(CPPFLAGS) -g -Xcompiler -Wall
maitre's avatar
maitre committed
1840
1841

easeaclean: clean
1842
	rm -f Makefile