CEvolutionaryAlgorithm.cpp 11.8 KB
Newer Older
kruger's avatar
kruger committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#ifdef WIN32
#pragma comment(lib, "WinMM.lib")
#endif
/*
 * CEvolutionaryAlgorithm.cpp
 *
 *  Created on: 22 juin 2009
 *      Author: maitre
 */

#include "include/CEvolutionaryAlgorithm.h"
#include <string>
#ifndef WIN32
#include <sys/time.h>
#endif
#ifdef WIN32
#include <windows.h>
#endif
#include <time.h>
#include <math.h>
maitre's avatar
maitre committed
21
#include <string>
kruger's avatar
kruger committed
22
23
24
25
26
#include "include/CIndividual.h"
#include "include/Parameters.h"
#include "include/CGnuplot.h"
#include "include/global.h"

maitre's avatar
maitre committed
27
28
using namespace std;

kruger's avatar
kruger committed
29
extern CRandomGenerator* globalRandomGenerator;
30
extern CEvolutionaryAlgorithm* EA;
kruger's avatar
kruger committed
31
32
void EASEABeginningGenerationFunction(CEvolutionaryAlgorithm* evolutionaryAlgorithm);
void EASEAEndGenerationFunction(CEvolutionaryAlgorithm* evolutionaryAlgorithm);
maitre's avatar
maitre committed
33
void EASEAGenerationFunctionBeforeReplacement(CEvolutionaryAlgorithm* evolutionaryAlgorithm);
kruger's avatar
kruger committed
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/**
 * @DEPRECATED the next contructor has to be used instead of this one.
 */
CEvolutionaryAlgorithm::CEvolutionaryAlgorithm( size_t parentPopulationSize,
					      size_t offspringPopulationSize,
					      float selectionPressure, float replacementPressure, float parentReductionPressure, float offspringReductionPressure,
					      CSelectionOperator* selectionOperator, CSelectionOperator* replacementOperator,
					      CSelectionOperator* parentReductionOperator, CSelectionOperator* offspringReductionOperator,
					      float pCrossover, float pMutation,
					      float pMutationPerGene){

  CRandomGenerator* rg = globalRandomGenerator;

  CSelectionOperator* so = selectionOperator;
  CSelectionOperator* ro = replacementOperator;

  //CIndividual::initRandomGenerator(rg);
  CPopulation::initPopulation(so,ro,parentReductionOperator,offspringReductionOperator,selectionPressure,replacementPressure,parentReductionPressure,offspringReductionPressure);

  this->population = new CPopulation(parentPopulationSize,offspringPopulationSize,
				    pCrossover,pMutation,pMutationPerGene,rg,NULL);

  this->currentGeneration = 0;

  this->reduceParents = 0;
  this->reduceOffsprings = 0;
maitre's avatar
maitre committed
60
  
kruger's avatar
kruger committed
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
}

CEvolutionaryAlgorithm::CEvolutionaryAlgorithm(Parameters* params){
	this->params = params;

	CPopulation::initPopulation(params->selectionOperator,params->replacementOperator,params->parentReductionOperator,params->offspringReductionOperator,
			params->selectionPressure,params->replacementPressure,params->parentReductionPressure,params->offspringReductionPressure);

	this->population = new CPopulation(params->parentPopulationSize,params->offspringPopulationSize,
			params->pCrossover,params->pMutation,params->pMutationPerGene,params->randomGenerator,params);

	this->currentGeneration = 0;

	this->reduceParents = 0;
	this->reduceOffsprings = 0;
	this->gnuplot = NULL;
maitre's avatar
maitre committed
77
	if(params->plotStats || params->generateGnuplotScript){
78
		string fichier (params->outputFilename);
maitre's avatar
maitre committed
79
80
81
82
		fichier.append(".dat");
		remove(fichier.c_str());
	}
	if(params->generateGnuplotScript){
83
		string fichier (params->outputFilename);
maitre's avatar
maitre committed
84
85
86
87
		fichier.append(".plot");
		remove(fichier.c_str());
	}
	if(params->generateRScript || params->generateCVSFile){
88
89
		string fichier (params->outputFilename);
		fichier.append(".csv");
maitre's avatar
maitre committed
90
91
92
		remove(fichier.c_str());
	}
	if(params->generateRScript){
93
		string fichier (params->outputFilename);
maitre's avatar
maitre committed
94
95
96
		fichier.append(".r");
		remove(fichier.c_str());
	}
kruger's avatar
kruger committed
97
98
	#ifdef __linux__
	if(params->plotStats){
maitre's avatar
maitre committed
99
		this->gnuplot = new CGnuplot((this->params->offspringPopulationSize*this->params->nbGen)+this->params->parentPopulationSize);
kruger's avatar
kruger committed
100
101
102
103
104
105
106
107
108
109
110
	}
	#endif
}

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



void CEvolutionaryAlgorithm::runEvolutionaryLoop(){
maitre's avatar
maitre committed
111
112
  CIndividual** elitistPopulation;
  
kruger's avatar
kruger committed
113
114
115
116
117
118
119
120
121
122
123
124
  std::cout << "Parent's population initializing "<< std::endl;
  this->initializeParentPopulation();
  this->population->evaluateParentPopulation();
  this->population->currentEvaluationNb += this->params->parentPopulationSize;
  if(this->params->printInitialPopulation){
  	std::cout << *population << std::endl;
  }


  struct timeval begin;
  gettimeofday(&begin,NULL);

maitre's avatar
maitre committed
125
126
127
128
129
  //Initialize elitPopulation
  if(params->elitSize)
		elitistPopulation = (CIndividual**)malloc(params->elitSize*sizeof(CIndividual*));	

  while( this->allCriteria() == false){
kruger's avatar
kruger committed
130
131

    EASEABeginningGenerationFunction(this);
maitre's avatar
maitre committed
132

kruger's avatar
kruger committed
133
134
135
136
137
138
    population->produceOffspringPopulation();

    population->evaluateOffspringPopulation();

    population->currentEvaluationNb += this->params->offspringPopulationSize;

maitre's avatar
maitre committed
139
    EASEAGenerationFunctionBeforeReplacement(this);
kruger's avatar
kruger committed
140

maitre's avatar
maitre committed
141
142
143
144
145
146
147
148
149
150
151
152
153
    /* ELITISM */
    if(params->elitSize && this->params->parentPopulationSize>=params->elitSize){
	/* STRONG ELITISM */
	if(params->strongElitism){
		population->strongElitism(params->elitSize, population->parents, this->params->parentPopulationSize, elitistPopulation, params->elitSize);
		population->actualParentPopulationSize -= params->elitSize;
	}
	/* WEAK ELITISM */
	else{
		population->weakElitism(params->elitSize, population->parents, population->offsprings, &(population->actualParentPopulationSize), &(population->actualOffspringPopulationSize), elitistPopulation, params->elitSize);
	}
	
    }
kruger's avatar
kruger committed
154

maitre's avatar
maitre committed
155
156
    if( params->parentReduction )
      population->reduceParentPopulation(params->parentReductionSize);
kruger's avatar
kruger committed
157

maitre's avatar
maitre committed
158
    if( params->offspringReduction )
kruger's avatar
kruger committed
159
160
      population->reduceOffspringPopulation( params->offspringReductionSize );

maitre's avatar
maitre committed
161
    population->reduceTotalPopulation(elitistPopulation);
kruger's avatar
kruger committed
162

maitre's avatar
maitre committed
163
    showPopulationStats(begin);
kruger's avatar
kruger committed
164

maitre's avatar
maitre committed
165
    EASEAEndGenerationFunction(this);
kruger's avatar
kruger committed
166
167
168

    currentGeneration += 1;
  }
maitre's avatar
maitre committed
169
170
171
172
173
174
#ifdef __linux__
  if(this->params->plotStats && this->gnuplot->valid){
  	outputGraph();
  	delete this->gnuplot;
  }
#endif
kruger's avatar
kruger committed
175

maitre's avatar
maitre committed
176
177
  if(this->params->printFinalPopulation){
  	population->sortParentPopulation();
kruger's avatar
kruger committed
178
  	std::cout << *population << std::endl;
maitre's avatar
maitre committed
179
  }
kruger's avatar
kruger committed
180

maitre's avatar
maitre committed
181
182
183
184
185
186
187
188
  if(this->params->generateGnuplotScript || !this->params->plotStats)
	generateGnuplotScript();

  if(this->params->generateRScript)
	generateRScript();
  
  if(params->elitSize)
  	free(elitistPopulation);
kruger's avatar
kruger committed
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
}


void CEvolutionaryAlgorithm::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();

    // here we are looking for the smaller individual's fitness if we are minimizing
    // or the greatest one if we are not
    if( (params->minimizing && population->parents[i]->getFitness()<population->Best->getFitness()) ||
    (!params->minimizing && population->parents[i]->getFitness()>population->Best->getFitness()))
      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);

  struct timeval end, res;
  gettimeofday(&end,0);
  timersub(&end,&beginTime,&res);

  //Affichage
  if(params->printStats){
	  if(currentGeneration==0)
	    printf("GEN\tTIME\t\tEVAL\tBEST\t\tAVG\t\tSTDEV\n\n");
maitre's avatar
maitre committed
225
226
	    printf("%lu\t%ld.%06ld\t%lu\t%.15e\t%.15e\t%.15e\n",currentGeneration,res.tv_sec,res.tv_usec,population->currentEvaluationNb,population->Best->getFitness(),currentAverageFitness,currentSTDEV);
	  //printf("%lu\t%ld.%06ld\t%lu\t%f\t%f\t%f\n",currentGeneration,res.tv_sec,res.tv_usec,population->currentEvaluationNb,population->Best->getFitness(),currentAverageFitness,currentSTDEV);
kruger's avatar
kruger committed
227
228
  }

maitre's avatar
maitre committed
229
230
  if((this->params->plotStats && this->gnuplot->valid) || this->params->generateGnuplotScript){
 	FILE *f;
231
	string fichier (params->outputFilename);
kruger's avatar
kruger committed
232
233
	fichier.append(".dat");
 	f = fopen(fichier.c_str(),"a"); //ajouter .dat
maitre's avatar
maitre committed
234
235
236
237
238
239
240
241
242
	if(f!=NULL){
	  if(currentGeneration==0)
		fprintf(f,"#GEN\tTIME\t\tEVAL\tBEST\t\tAVG\t\tSTDEV\n\n");
	  fprintf(f,"%lu\t%ld.%06ld\t%lu\t%.15e\t%.15e\t%.15e\n",currentGeneration,res.tv_sec,res.tv_usec,population->currentEvaluationNb,population->Best->getFitness(),currentAverageFitness,currentSTDEV);
	  fclose(f);
        }
  }
  if(params->generateCVSFile || params->generateRScript){ //Generation du fichier CVS;
 	FILE *f;
243
244
245
	string fichier (params->outputFilename);
	fichier.append(".csv");
 	f = fopen(fichier.c_str(),"a"); //ajouter .csv
maitre's avatar
maitre committed
246
247
248
249
250
251
252
	if(f!=NULL){
	  if(currentGeneration==0)
		fprintf(f,"GEN,TIME,EVAL,BEST,AVG,STDEV\n");
	  fprintf(f,"%lu,%ld.%06ld,%lu,%.15e,%.15e,%.15e\n",currentGeneration,res.tv_sec,res.tv_usec,population->currentEvaluationNb,population->Best->getFitness(),currentAverageFitness,currentSTDEV);
	  fclose(f);
        }
  }
kruger's avatar
kruger committed
253
254
255
256
  //print Gnuplot
  #ifdef __linux__
  if(this->params->plotStats && this->gnuplot->valid){
	if(currentGeneration==0)
kruger's avatar
kruger committed
257
		fprintf(this->gnuplot->fWrit,"plot \'%s.dat\' using 3:4 t \'Best Fitness\' w lines, \'%s.dat\' using 3:5 t  \'Average\' w lines, \'%s.dat\' using 3:6 t \'StdDev\' w lines\n", params->outputFilename,params->outputFilename,params->outputFilename);
kruger's avatar
kruger committed
258
259
260
261
	else
		fprintf(this->gnuplot->fWrit,"replot\n");
	fflush(this->gnuplot->fWrit);
 }
maitre's avatar
maitre committed
262
 
kruger's avatar
kruger committed
263
#endif
maitre's avatar
maitre committed
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279

  params->timeCriterion->setElapsedTime(res.tv_sec);
}

void CEvolutionaryAlgorithm::outputGraph(){
      	fprintf(this->gnuplot->fWrit,"set term png\n");
      	fprintf(this->gnuplot->fWrit,"set output \"%s\"\n",params->plotOutputFilename);
	fprintf(this->gnuplot->fWrit,"set xrange[0:%d]\n",population->currentEvaluationNb);
	fprintf(this->gnuplot->fWrit,"set xlabel \"Number of Evaluations\"\n");
        fprintf(this->gnuplot->fWrit,"set ylabel \"Fitness\"\n");
        fprintf(this->gnuplot->fWrit,"replot \n");
	fflush(this->gnuplot->fWrit);
}

void CEvolutionaryAlgorithm::generateGnuplotScript(){
	FILE* f;
280
	string fichier (this->params->outputFilename);
maitre's avatar
maitre committed
281
282
283
284
285
286
287
288
289
290
291
292
293
	fichier.append(".plot");
	f = fopen(fichier.c_str(),"a");
	fprintf(f,"set term png\n");
	fprintf(f,"set output \"%s\"\n",params->plotOutputFilename);
	fprintf(f,"set xrange[0:%d]\n",population->currentEvaluationNb);
	fprintf(f,"set xlabel \"Number of Evaluations\"\n");
        fprintf(f,"set ylabel \"Fitness\"\n");
	fprintf(f,"plot \'%s.dat\' using 3:4 t \'Best Fitness\' w lines, \'%s.dat\' using 3:5 t  \'Average\' w lines, \'%s.dat\' using 3:6 t \'StdDev\' w lines\n", params->outputFilename,params->outputFilename,params->outputFilename);
	fclose(f);	
}

void CEvolutionaryAlgorithm::generateRScript(){
	FILE* f;
294
	string fichier (this->params->outputFilename);
maitre's avatar
maitre committed
295
296
297
298
	fichier.append(".r");
	f=fopen(fichier.c_str(),"a");
	fprintf(f,"#Plotting for R\n"),
	fprintf(f,"png(\"%s\")\n",params->plotOutputFilename);
299
	fprintf(f,"data <- read.table(\"./%s.csv\",sep=\",\")\n",params->outputFilename);
maitre's avatar
maitre committed
300
301
302
303
304
305
306
307
	fprintf(f,"plot(0, type = \"n\", main = \"Plot Title\", xlab = \"Number of Evaluations\", ylab = \"Fitness\", xlim = c(0,%d) )\n",population->currentEvaluationNb);
	fprintf(f,"grid() # add grid\n");
	fprintf(f,"lines(data[,3], data[,4], lty = 1) #draw first dataset\n");
	fprintf(f,"lines(data[,3], data[,5], lty = 2) #draw second dataset\n");
	fprintf(f,"lines(data[,3], data[,6], lty = 3) #draw third dataset\n");
	fprintf(f,"legend(\"topright\", c(\"Best Fitness\", \"Average\", \"StdDev\"), lty = c(1, 2, 3) )\n");
	fclose(f);
	
kruger's avatar
kruger committed
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
}

bool CEvolutionaryAlgorithm::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;
}

#ifdef WIN32
int gettimeofday
      (struct timeval* tp, void* tzp) {
    DWORD t;
    t = timeGetTime();
    tp->tv_sec = t / 1000;
    tp->tv_usec = t % 1000;
    /* 0 indicates success. */
    return 0;
}

void timersub( const timeval * tvp, const timeval * uvp, timeval* vvp )
{
    vvp->tv_sec = tvp->tv_sec - uvp->tv_sec;
    vvp->tv_usec = tvp->tv_usec - uvp->tv_usec;
    if( vvp->tv_usec < 0 )
    {
       --vvp->tv_sec;
       vvp->tv_usec += 1000000;
    }
} 
#endif
maitre's avatar
maitre committed
343