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

#include "include/CEvolutionaryAlgorithm.h"
#ifndef WIN32
#include <sys/time.h>
#endif
#ifdef WIN32
#include <windows.h>
17
#endif
18 19

#include <stdio.h>
20
#include <time.h>
kruger's avatar
kruger committed
21
#include <math.h>
kruger's avatar
kruger committed
22
#include <string.h>
kruger's avatar
kruger committed
23 24 25 26
#include "include/CIndividual.h"
#include "include/Parameters.h"
#include "include/CGnuplot.h"
#include "include/global.h"
kruger's avatar
kruger committed
27 28
#include "include/CComUDPLayer.h"
#include "include/CRandomGenerator.h"
kruger's avatar
kruger committed
29
#include <stdio.h>
kruger's avatar
kruger committed
30 31
#include <sstream>
#include <fstream>
kruger's avatar
kruger committed
32

maitre's avatar
maitre committed
33 34
using namespace std;

kruger's avatar
kruger committed
35
extern CRandomGenerator* globalRandomGenerator;
36
extern CEvolutionaryAlgorithm* EA;
kruger's avatar
kruger committed
37 38
void EASEABeginningGenerationFunction(CEvolutionaryAlgorithm* evolutionaryAlgorithm);
void EASEAEndGenerationFunction(CEvolutionaryAlgorithm* evolutionaryAlgorithm);
maitre's avatar
maitre committed
39
void EASEAGenerationFunctionBeforeReplacement(CEvolutionaryAlgorithm* evolutionaryAlgorithm);
40 41 42

extern void evale_pop_chunk(CIndividual** pop, int popSize);
extern bool INSTEAD_EVAL_STEP;
kruger's avatar
kruger committed
43

kruger's avatar
kruger committed
44 45 46
/**
 * @DEPRECATED the next contructor has to be used instead of this one.
 */
Ogier Maitre's avatar
Ogier Maitre committed
47 48
/*CEvolutionaryAlgorithm::CEvolutionaryAlgorithm( unsigned parentPopulationSize,
					      unsigned offspringPopulationSize,
kruger's avatar
kruger committed
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
					      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
70
  
kruger's avatar
kruger committed
71 72 73 74 75
  // INITIALIZE SERVER OBJECT ISLAND MODEL
  if(params->remoteIslandModel){
  	this->server = new CComUDPServer(2909,0);
	this->treatedIndividuals = 0;
	this->numberOfClients = 0;
kruger's avatar
kruger committed
76

kruger's avatar
kruger committed
77 78 79 80 81 82 83
	this->initializeClients();
  }
}*/

/*****
 * REAL CONSTRUCTOR
 */
kruger's avatar
kruger committed
84 85 86 87 88 89 90 91 92 93 94 95 96 97
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
98
	if(params->plotStats || params->generateGnuplotScript){
99
		string fichier = params->outputFilename;
maitre's avatar
maitre committed
100 101 102 103
		fichier.append(".dat");
		remove(fichier.c_str());
	}
	if(params->generateGnuplotScript){
104
		string fichier = params->outputFilename;
maitre's avatar
maitre committed
105 106 107
		fichier.append(".plot");
		remove(fichier.c_str());
	}
kruger's avatar
kruger committed
108
	if(params->generateRScript || params->generateCSVFile){
109
		string fichier = params->outputFilename;
kruger's avatar
kruger committed
110
		fichier.append(".csv");
maitre's avatar
maitre committed
111 112 113
		remove(fichier.c_str());
	}
	if(params->generateRScript){
114
		string fichier = params->outputFilename;
maitre's avatar
maitre committed
115 116 117
		fichier.append(".r");
		remove(fichier.c_str());
	}
kruger's avatar
kruger committed
118 119
	#ifdef __linux__
	if(params->plotStats){
maitre's avatar
maitre committed
120
		this->gnuplot = new CGnuplot((this->params->offspringPopulationSize*this->params->nbGen)+this->params->parentPopulationSize);
kruger's avatar
kruger committed
121 122
	}
	#endif
kruger's avatar
kruger committed
123 124 125 126 127 128 129


	// INITIALIZE SERVER OBJECT ISLAND MODEL
	if(params->remoteIslandModel){
		server = new CComUDPServer(2909,0); //1 if debug
		this->treatedIndividuals = 0;
		this->numberOfClients = 0;
kruger's avatar
kruger committed
130
		this->myClientNumber=0;	
kruger's avatar
kruger committed
131
		this->initializeClients();
132 133
		if(!params->remoteIslandModel)
			delete this->server;
kruger's avatar
kruger committed
134
	}
kruger's avatar
kruger committed
135 136
}

kruger's avatar
kruger committed
137
/* DESTRUCTOR */
138
CEvolutionaryAlgorithm::~CEvolutionaryAlgorithm(){
kruger's avatar
kruger committed
139 140 141 142 143 144 145 146 147
	delete population;
        if(this->params->remoteIslandModel){
                delete this->server;
                if(this->numberOfClients>1){
                        for(int i=0; (unsigned)i<this->numberOfClients; i++)
                                delete this->Clients[i];
                        delete this->Clients;
                }
        }
148
}
kruger's avatar
kruger committed
149 150 151 152
void CEvolutionaryAlgorithm::addStoppingCriterion(CStoppingCriterion* sc){
  this->stoppingCriteria.push_back(sc);
}

kruger's avatar
kruger committed
153
/* MAIN FUNCTION TO RUN THE EVOLUTIONARY LOOP */
kruger's avatar
kruger committed
154
void CEvolutionaryAlgorithm::runEvolutionaryLoop(){
maitre's avatar
maitre committed
155
  CIndividual** elitistPopulation;
156

kruger's avatar
kruger committed
157 158 159 160
#ifdef WIN32
   clock_t begin(clock());
#else
  struct timeval begin;
161
  gettimeofday(&begin,0);
kruger's avatar
kruger committed
162 163
#endif

164
  std::cout << "Population initialisation (Generation 0)... "<< std::endl;
kruger's avatar
kruger committed
165
  this->initializeParentPopulation();
166

167 168 169 170 171
  if(!INSTEAD_EVAL_STEP)
    this->population->evaluateParentPopulation();
  else
    evale_pop_chunk(population->parents, population->parentPopulationSize);

kruger's avatar
kruger committed
172 173 174 175
  if(this->params->optimise){
        population->optimiseParentPopulation();
  }

kruger's avatar
kruger committed
176 177 178 179 180
  this->population->currentEvaluationNb += this->params->parentPopulationSize;
  if(this->params->printInitialPopulation){
  	std::cout << *population << std::endl;
  }

kruger's avatar
kruger committed
181
  showPopulationStats(begin);
182
  bBest = population->Best;
kruger's avatar
kruger committed
183
  currentGeneration += 1;
kruger's avatar
kruger committed
184

maitre's avatar
maitre committed
185 186 187 188
  //Initialize elitPopulation
  if(params->elitSize)
		elitistPopulation = (CIndividual**)malloc(params->elitSize*sizeof(CIndividual*));	

kruger's avatar
kruger committed
189
  // EVOLUTIONARY LOOP
maitre's avatar
maitre committed
190
  while( this->allCriteria() == false){
kruger's avatar
kruger committed
191 192

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

kruger's avatar
kruger committed
194
    // Sending individuals if remote island model
195
    if(params->remoteIslandModel)
kruger's avatar
kruger committed
196 197
	    this->sendIndividual();

kruger's avatar
kruger committed
198
    population->produceOffspringPopulation();
199

200 201 202 203
    if(!INSTEAD_EVAL_STEP)
      population->evaluateOffspringPopulation();
    else
      evale_pop_chunk(population->offsprings, population->offspringPopulationSize);
kruger's avatar
kruger committed
204 205
    population->currentEvaluationNb += this->params->offspringPopulationSize;

kruger's avatar
kruger committed
206 207 208 209
    if(this->params->optimise){
          population->optimiseOffspringPopulation();
    }

maitre's avatar
maitre committed
210
    EASEAGenerationFunctionBeforeReplacement(this);
kruger's avatar
kruger committed
211

maitre's avatar
maitre committed
212 213 214 215 216 217 218 219 220 221 222 223 224
    /* 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
225

maitre's avatar
maitre committed
226 227
    if( params->parentReduction )
      population->reduceParentPopulation(params->parentReductionSize);
kruger's avatar
kruger committed
228

maitre's avatar
maitre committed
229
    if( params->offspringReduction )
kruger's avatar
kruger committed
230 231
      population->reduceOffspringPopulation( params->offspringReductionSize );

maitre's avatar
maitre committed
232
    population->reduceTotalPopulation(elitistPopulation);
kruger's avatar
kruger committed
233

234
    population->sortParentPopulation();
235 236
    //if( this->params->printStats  || this->params->generateCSVFile )
    showPopulationStats(begin); // (always calculate stats)
237
    bBest = population->Best;
maitre's avatar
maitre committed
238
    EASEAEndGenerationFunction(this);
kruger's avatar
kruger committed
239

kruger's avatar
kruger committed
240 241 242 243 244
    //Receiving individuals if cluster island model
    if(params->remoteIslandModel){
	this->receiveIndividuals();
    }

kruger's avatar
kruger committed
245 246
    currentGeneration += 1;
  }
maitre's avatar
maitre committed
247 248 249 250 251 252
#ifdef __linux__
  if(this->params->plotStats && this->gnuplot->valid){
  	outputGraph();
  	delete this->gnuplot;
  }
#endif
kruger's avatar
kruger committed
253

maitre's avatar
maitre committed
254 255
  if(this->params->printFinalPopulation){
  	population->sortParentPopulation();
kruger's avatar
kruger committed
256
  	std::cout << *population << std::endl;
maitre's avatar
maitre committed
257
  }
kruger's avatar
kruger committed
258

kruger's avatar
kruger committed
259 260 261 262 263 264 265 266 267
  //IF SAVING THE POPULATION, ERASE THE OLD FILE
  if(params->savePopulation){
	
	string fichier = params->outputFilename;
	fichier.append(".pop");
	remove(fichier.c_str());
  	population->serializePopulation();
  }

maitre's avatar
maitre committed
268 269 270 271 272 273 274 275
  if(this->params->generateGnuplotScript || !this->params->plotStats)
	generateGnuplotScript();

  if(this->params->generateRScript)
	generateRScript();
  
  if(params->elitSize)
  	free(elitistPopulation);
kruger's avatar
kruger committed
276 277 278
}


279 280 281
#ifdef WIN32
void CEvolutionaryAlgorithm::showPopulationStats(clock_t beginTime){
#else
kruger's avatar
kruger committed
282
void CEvolutionaryAlgorithm::showPopulationStats(struct timeval beginTime){
283
#endif
284 285 286
  
  currentAverageFitness=0.0;
  currentSTDEV=0.0;
kruger's avatar
kruger committed
287 288

  //Calcul de la moyenne et de l'ecart type
289
  population->Best = population->Worst = population->parents[0];
Ogier Maitre's avatar
Ogier Maitre committed
290
  for(unsigned i=0; i<population->parentPopulationSize; i++){
kruger's avatar
kruger committed
291 292 293 294 295 296 297
    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];
298 299 300 301 302 303

    // keep track of worst individual too, for statistical purposes
    if( (params->minimizing && population->parents[i]->getFitness() > population->Worst->getFitness()) ||
    (!params->minimizing && population->parents[i]->getFitness() < population->Worst->getFitness()))
      population->Worst=population->parents[i];

kruger's avatar
kruger committed
304 305 306 307
  }

  currentAverageFitness/=population->parentPopulationSize;

Ogier Maitre's avatar
Ogier Maitre committed
308
  for(unsigned i=0; i<population->parentPopulationSize; i++){
kruger's avatar
kruger committed
309 310 311 312 313
    currentSTDEV+=(population->parents[i]->getFitness()-currentAverageFitness)*(population->parents[i]->getFitness()-currentAverageFitness);
  }
  currentSTDEV/=population->parentPopulationSize;
  currentSTDEV=sqrt(currentSTDEV);

314 315 316 317 318
#ifdef WIN32
  clock_t end(clock());
  double duration;
  duration = (double)(end-beginTime)/CLOCKS_PER_SEC;
#else
kruger's avatar
kruger committed
319 320 321
  struct timeval end, res;
  gettimeofday(&end,0);
  timersub(&end,&beginTime,&res);
322
#endif
kruger's avatar
kruger committed
323 324 325 326

  //Affichage
  if(params->printStats){
	  if(currentGeneration==0)
327
	    printf("GEN\tTIME\t\tEVAL\tBEST\t\t\t\tAVG\t\t\t\tSTDEV\t\t\tWORST\n\n");
328
#ifdef WIN32
329
	  printf("%lu\t%2.6f\t%lu\t%.15e\t\t%.15e\t\t%.15e\t%.15e\n",currentGeneration,duration,population->currentEvaluationNb,population->Best->getFitness(),currentAverageFitness,currentSTDEV, population->Worst->getFitness());
330
#else
331
	    printf("%d\t%ld.%06ld\t%d\t%.15e\t\t%.15e\t\t%.15e\t%.15e\n",(int)currentGeneration,res.tv_sec,res.tv_usec,(int)population->currentEvaluationNb,population->Best->getFitness(),currentAverageFitness,currentSTDEV, population->Worst->getFitness());
332
#endif
maitre's avatar
maitre committed
333
	  //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
334 335
  }

maitre's avatar
maitre committed
336 337
  if((this->params->plotStats && this->gnuplot->valid) || this->params->generateGnuplotScript){
 	FILE *f;
kruger's avatar
kruger committed
338 339 340
	string fichier = params->outputFilename;
	fichier.append(".dat");
 	f = fopen(fichier.c_str(),"a"); //ajouter .csv
maitre's avatar
maitre committed
341 342
	if(f!=NULL){
	  if(currentGeneration==0)
343
	    fprintf(f,"#GEN\tTIME\t\tEVAL\tBEST\t\tAVG\t\tSTDEV\t\tWORST\n\n");
344
#ifdef WIN32
345
          fprintf(f,"%lu\t%2.6f\t%lu\t%.15e\t%.15e\t%.15e\t%.15e\n",currentGeneration,duration,population->currentEvaluationNb,population->Best->getFitness(),currentAverageFitness,currentSTDEV,population->Worst->getFitness());
346
#else
347
	  fprintf(f,"%d\t%ld.%06ld\t%d\t%.15e\t%.15e\t%.15e\t%.15e\n",(int)currentGeneration,res.tv_sec,res.tv_usec,(int)population->currentEvaluationNb,population->Best->getFitness(),currentAverageFitness,currentSTDEV,population->Worst->getFitness());
348
#endif
maitre's avatar
maitre committed
349 350 351
	  fclose(f);
        }
  }
kruger's avatar
kruger committed
352
  if(params->generateCSVFile || params->generateRScript){ //Generation du fichier CSV;
maitre's avatar
maitre committed
353
 	FILE *f;
354
	string fichier = params->outputFilename;
kruger's avatar
kruger committed
355 356
	fichier.append(".csv");
 	f = fopen(fichier.c_str(),"a"); //ajouter .csv
maitre's avatar
maitre committed
357 358
	if(f!=NULL){
	  if(currentGeneration==0)
359
		fprintf(f,"GEN,TIME,EVAL,BEST,AVG,STDEV,WORST\n");
360
#ifdef WIN32
361
	  fprintf(f,"%lu,%2.6f,%lu,%.15e,%.15e,%.15e,%.15e\n",currentGeneration,duration,population->currentEvaluationNb,population->Best->getFitness(),currentAverageFitness,currentSTDEV,population->Worst->getFitness());
362
#else
363
	  fprintf(f,"%d,%ld.%ld,%d,%f,%f,%f,%f\n",(int)currentGeneration,res.tv_sec,res.tv_usec,(int)population->currentEvaluationNb,population->Best->getFitness(),currentAverageFitness,currentSTDEV, population->Worst->getFitness());
364
#endif
maitre's avatar
maitre committed
365 366 367
	  fclose(f);
        }
  }
kruger's avatar
kruger committed
368 369 370 371
  //print Gnuplot
  #ifdef __linux__
  if(this->params->plotStats && this->gnuplot->valid){
	if(currentGeneration==0)
Ogier Maitre's avatar
Ogier Maitre committed
372
		fprintf(this->gnuplot->fWrit,"plot \'%s.dat\' using 3:4 t \'Best Fitness\' w lines ls 1, \'%s.dat\' using 3:5 t  \'Average\' w lines ls 4, \'%s.dat\' using 3:6 t \'StdDev\' w lines ls 3\n", params->outputFilename,params->outputFilename,params->outputFilename);
kruger's avatar
kruger committed
373 374 375 376
	else
		fprintf(this->gnuplot->fWrit,"replot\n");
	fflush(this->gnuplot->fWrit);
 }
maitre's avatar
maitre committed
377
 
kruger's avatar
kruger committed
378
#endif
maitre's avatar
maitre committed
379 380 381 382

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

kruger's avatar
kruger committed
383 384
//REMOTE ISLAND MODEL FUNCTIONS
void CEvolutionaryAlgorithm::initializeClients(){
kruger's avatar
kruger committed
385
	int clientNumber=0;
kruger's avatar
kruger committed
386 387
	char (*clients)[16] = (char(*)[16])calloc(1,sizeof(char)*16);
	
388
	cout << "Reading IP address file: " << this->params->ipFile << endl;
kruger's avatar
kruger committed
389
	ifstream IP_File(this->params->ipFile);
kruger's avatar
kruger committed
390 391 392
	string line;
	while(getline(IP_File, line)){
		if(!isLocalMachine(line.c_str())){
kruger's avatar
kruger committed
393 394 395 396 397 398 399 400
			memmove(clients[this->numberOfClients],line.c_str(),sizeof(char)*16);
			this->numberOfClients++;
			clients = (char(*)[16])realloc(clients,sizeof(char)*16*(this->numberOfClients*16));
			clientNumber++;
		}
		else{
			this->myClientNumber = clientNumber;	
		}
kruger's avatar
kruger committed
401 402
	}

Frederic Kruger's avatar
Frederic Kruger committed
403
	if(this->numberOfClients>0){
404 405 406 407 408 409 410 411
		this->Clients = (CComUDPClient**)malloc(this->numberOfClients*sizeof(CComUDPClient*));
		for(int i=0; i<(signed)this->numberOfClients; i++){
			this->Clients[i] = new CComUDPClient(2909,(const char*)clients[i],0);
		}
	}
	else{
		cout << "***WARNING***\nNo islands to communicate with. Aborting Island Model.\n***WARNING***" << endl;
		params->remoteIslandModel=0;
kruger's avatar
kruger committed
412 413 414 415 416 417
	}
	free(clients);
}

void CEvolutionaryAlgorithm::sendIndividual(){
	//Sending an individual every n generations	
418
	if(globalRandomGenerator->random(0.0,1.0)<=params->migrationProbability){
kruger's avatar
kruger committed
419
		//cout << "I'm going to send an Individual now" << endl;
420
		//this->population->selectionOperator->initialize(this->population->parents, 7, this->population->actualParentPopulationSize);
Ogier Maitre's avatar
Ogier Maitre committed
421
		//unsigned index = this->population->selectionOperator->selectNext(this->population->actualParentPopulationSize);
kruger's avatar
kruger committed
422 423 424 425 426 427
		//cout << "Going to send individual " << index << " with fitness " << this->population->parents[index]->fitness << endl;
	
		//selecting a client randomly
		int client = globalRandomGenerator->getRandomIntMax(this->numberOfClients);
		cout << "Going to send and individual to client " << client << endl;
		cout << "His IP is " << this->Clients[client]->getIP() << endl;
428
		//cout << "Sending individual " << index << " to client " << client << " now" << endl;
kruger's avatar
kruger committed
429
		//cout << this->population->parents[index]->serialize() << endl;
430
		this->Clients[client]->CComUDP_client_send((char*)bBest->serialize().c_str());
kruger's avatar
kruger committed
431 432 433 434 435 436 437 438 439 440 441 442 443
		
	}
}

void CEvolutionaryAlgorithm::receiveIndividuals(){
	//Checking every generation for received individuals
	if(this->treatedIndividuals<(unsigned)this->server->nb_data){
		//cout << "number of received individuals :" << this->server->nb_data << endl;
		//cout << "number of treated individuals :" << this->treatedIndividuals << endl;

		//Treating all the individuals before continuing
		while(this->treatedIndividuals < (unsigned)this->server->nb_data){
			//selecting the individual to erase
444 445
			//CSelectionOperator *antiTournament = getSelectionOperator("Tournament",!this->params->minimizing, globalRandomGenerator);		
			//antiTournament->initialize(this->population->parents, 7, this->population->actualParentPopulationSize);
Frederic Kruger's avatar
Frederic Kruger committed
446
			//unsigned index = antiTournament->selectNext(this->population->actualParentPopulationSize);
447 448 449
			
			//We're selecting the worst element to replace
			size_t index = this->population->getWorstIndividualIndex(this->population->parents);
kruger's avatar
kruger committed
450 451 452 453 454 455 456 457 458 459 460 461 462

			//cout << "old individual fitness :" << this->population->parents[index]->fitness << endl;
			//cout << "old Individual :" << this->population->parents[index]->serialize() << endl;
			this->server->read_data_lock();
			string line = this->server->parm->data[this->treatedIndividuals].data;
			this->population->parents[index]->deserialize(line);
			this->server->read_data_unlock();
			//cout << "new Individual :" << this->population->parents[index]->serialize() << endl;
			this->treatedIndividuals++;
		}
	}
}

maitre's avatar
maitre committed
463 464 465
void CEvolutionaryAlgorithm::outputGraph(){
      	fprintf(this->gnuplot->fWrit,"set term png\n");
      	fprintf(this->gnuplot->fWrit,"set output \"%s\"\n",params->plotOutputFilename);
466
	fprintf(this->gnuplot->fWrit,"set xrange[0:%d]\n",(int)population->currentEvaluationNb);
maitre's avatar
maitre committed
467 468 469 470 471 472 473 474
	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;
475
	string fichier = this->params->outputFilename;
maitre's avatar
maitre committed
476 477 478 479
	fichier.append(".plot");
	f = fopen(fichier.c_str(),"a");
	fprintf(f,"set term png\n");
	fprintf(f,"set output \"%s\"\n",params->plotOutputFilename);
480
	fprintf(f,"set xrange[0:%d]\n",(int)population->currentEvaluationNb);
maitre's avatar
maitre committed
481 482 483 484 485 486 487 488
	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;
489
	string fichier = this->params->outputFilename;
maitre's avatar
maitre committed
490 491 492 493
	fichier.append(".r");
	f=fopen(fichier.c_str(),"a");
	fprintf(f,"#Plotting for R\n"),
	fprintf(f,"png(\"%s\")\n",params->plotOutputFilename);
kruger's avatar
kruger committed
494
	fprintf(f,"data <- read.table(\"./%s.csv\",sep=\",\")\n",params->outputFilename);
495
	fprintf(f,"plot(0, type = \"n\", main = \"Plot Title\", xlab = \"Number of Evaluations\", ylab = \"Fitness\", xlim = c(0,%d) )\n",(int)population->currentEvaluationNb);
maitre's avatar
maitre committed
496 497 498 499 500 501 502
	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
503 504 505 506
}

bool CEvolutionaryAlgorithm::allCriteria(){

Ogier Maitre's avatar
Ogier Maitre committed
507
	for( unsigned i=0 ; i<stoppingCriteria.size(); i++ ){
kruger's avatar
kruger committed
508
		if( stoppingCriteria.at(i)->reached() ){
509
			std::cout << "Stopping criterion reached" << std::endl;
kruger's avatar
kruger committed
510 511 512 513
			return true;
		}
	}
	return false;
kruger's avatar
kruger committed
514
}
515 516

#ifdef WIN32
kruger's avatar
kruger committed
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536
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;
	}
} 
537 538
#endif