nsga2.cpp
1 /********************************************************************************
2  * FARSA Genetic Algorithm Library *
3  * Copyright (C) 2007-2011 Gianluca Massera <emmegian@yahoo.it> *
4  * *
5  * This program is free software; you can redistribute it and/or modify *
6  * it under the terms of the GNU General Public License as published by *
7  * the Free Software Foundation; either version 2 of the License, or *
8  * (at your option) any later version. *
9  * *
10  * This program is distributed in the hope that it will be useful, *
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13  * GNU General Public License for more details. *
14  * *
15  * You should have received a copy of the GNU General Public License *
16  * along with this program; if not, write to the Free Software *
17  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA *
18  ********************************************************************************/
19 
20 #include "factory.h"
21 #include "gas/nsga2.h"
22 #include "core/reproduction.h"
23 #include "core/genome.h"
24 #include "core/evaluation.h"
25 #include "configurationhelper.h"
26 #include <cmath>
27 #include <cfloat>
28 #include <QThreadPool>
29 #include <QtConcurrentMap>
30 using namespace QtConcurrent;
31 
32 namespace farsa {
33 
34 NSGA2::NSGA2()
35  : GeneticAlgo(), lastPareto() {
36  fitfunc = 0;
37  reprod = 0;
38  numGens = 0;
39  currPhase = initEvaluation;
40  numThreadv = 1;
41  isInitialized = false;
42  isFinalized = true;
43 }
44 
46  foreach( NSGA2::evaluationThread* e, evalThreads ) {
47  delete e;
48  }
49  delete fitfunc;
50 }
51 
52 void NSGA2::configure( ConfigurationParameters& params, QString prefix ) {
53  setGenome( params.getObjectFromGroup<Genome>( prefix + QString( "GENOME" ) ) );
54  setEvaluation( params.getObjectFromGroup<Evaluation>( prefix + QString( "EVALUATION" ) ) );
55  fitfunc->setGenome( genome() );
56  setReproduction( params.getObjectFromGroup<Reproduction>( prefix + QString( "REPRODUCTION" ) ) );
57  setNumGenerations( ConfigurationHelper::getInt( params, prefix + QString( "ngenerations" ), 1000 ) );
58  setNumThreads( ConfigurationHelper::getInt( params, prefix + QString( "numThreads" ), 1 ) );
59 }
60 
61 void NSGA2::save( ConfigurationParameters& params, QString prefix ) {
62  params.createParameter( prefix, QString("type"), "NSGA2" );
63  params.createParameter( prefix, QString("numThreads"), QString("%1").arg( numThreads() ) );
64  params.createParameter( prefix, QString("ngenerations"), QString("%1").arg( numGenerations() ) );
65  //--- EVALUATION
66  fitfunc->save( params, params.createSubGroup( prefix, "EVALUATION" ) );
67  //--- REPRODUCTION
68  reproduction()->save( params, params.createSubGroup( prefix, "REPRODUCTION" ) );
69  //--- GENOME
70  genome()->save( params, params.createSubGroup( prefix, "GENOME" ) );
71 }
72 
73 void NSGA2::describe( QString type ) {
74  Descriptor d = addTypeDescription( type, "Non-dominated Sorting Genetic Algorithm version 2" );
75  d.describeInt( "numThreads" ).limits( 1, 32 ).def(1).help( "Number of threads to parallelize the evaluation of individuals" );
76  d.describeInt( "ngenerations" ).limits( 1, INT_MAX ).def( 1000 ).help( "Number of the generations of the evolutionary process" );
77  d.describeSubgroup( "EVALUATION" ).type( "Evaluation" ).props( IsMandatory ).help( "Object that calculate the fitness", "Create a subclass of Evalution and code your custom fitness function" );
78  d.describeSubgroup( "REPRODUCTION" ).type( "Reproduction" ).props( IsMandatory ).help( "Object that generate the new generations" );
79  d.describeSubgroup( "GENOME" ).type( "Genome" ).props( IsMandatory ).help( "Object containing the individuals under evolution" );
80 }
81 
82 void NSGA2::setNumThreads( int numThreads ) {
83  if ( numThreads < 1 ) {
84  qWarning( "The number of Threads must be greater than one!!" );
85  }
86  Q_ASSERT_X( !isInitialized && isFinalized ,
87  "NSGA2::setNumThreads",
88  "This method can only called before initialize of NSGA2" );
89  Q_ASSERT_X( fitfunc != 0 ,
90  "NSGA2::setNumThreads",
91  "This method must be called after an Evaluation object has been setted by NSGA2::setEvaluation" );
92  numThreadv = numThreads;
93  return;
94 }
95 
97  return numThreadv;
98 }
99 
101  this->fitfunc = fitfunc;
102  this->fitfunc->setGA( this );
103 }
104 
106 {
107  return fitfunc;
108 }
109 
110 QVector<Evaluation*> NSGA2::evaluationPool() {
111  QVector<Evaluation*> ev;
112  foreach( NSGA2::evaluationThread* e, evalThreads ) {
113  ev.append( e->eval );
114  }
115  return ev;
116 }
117 
119  this->reprod = reprod;
120  this->reprod->setGA( this );
121 }
122 
124  return reprod;
125 }
126 
128  if ( isInitialized && !isFinalized ) return;
129  Q_ASSERT_X( fitfunc != 0 ,
130  "NSGA2::initialize",
131  "You have to setup the Evaluation object of NSGA2 (Fitness Function)" );
132  Q_ASSERT_X( reprod !=0 ,
133  "NSGA2::initialize",
134  "You have to setup the Reproduction operator of NSGA2" );
135 
136  isInitialized = true;
137  isFinalized = false;
138  setGeneration( 0 );
139  currPhase = initEvaluation;
140  evolutionEnd = false;
141  evaluationDone = false;
142  //--- Setting up the evalThreads
143  for( int i=0; i<evalThreads.size(); i++ ) {
144  delete (evalThreads[i]);
145  }
146  evalThreads.clear();
147  for( int i=0; i<numThreadv; i++ ) {
148  evalThreads.append( new evaluationThread( this, fitfunc ) );
149  evalThreads.last()->eval->initGeneration(0);
150  }
151  //--- set the number of thread to create
152  QThreadPool::globalInstance()->setMaxThreadCount( numThreadv );
153 }
154 
156  switch( currPhase ) {
157  case initEvaluation:
158  for( int i=0; i<numThreadv; i++ ) {
159  evalThreads[i]->sequence.clear();
160  }
161  for( int i=0; i<(int)genome()->size(); i++ ) {
162  evalThreads[ i%numThreadv ]->sequence.append( i );
163  }
164  for( int i=0; i<numThreadv; i++ ) {
165  evalThreads[i]->idSeq = 0;
166  evalThreads[i]->id = evalThreads[i]->sequence[ evalThreads[i]->idSeq ];
167  evalThreads[i]->eval->setGenome( genome() );
168  evalThreads[i]->eval->initialize( genome()->at( evalThreads[i]->id ) );
169  evalThreads[i]->blocked = false;
170  }
171  currPhase = evaluating;
172  break;
173  case evaluating: { /* Multi Thread Block (i.e. Parallel Evaluation of Genotypes */
174  nextGeneration = true;
175  if ( numThreadv == 1 ) {
176  // Don't use Threads if is not necessary
177  evalThreads[0]->runStep();
178  } else {
179  QFuture<void> future = map( evalThreads, NSGA2::runStepWrapper );
180  future.waitForFinished();
181  }
182  if ( nextGeneration ) {
183  currPhase = nextGeneration_pass1;
184  }
185  } /* End of Multi Thread Block */
186  break;
187  case nextGeneration_pass1: {
188  // --- Core of the NSGA-II Algorithm
189  // -1) merge previous front population lastPareto with current genome()
190  //--- this merge assure that the best (elite) pareto-fronts are mantained
191  nsgaGenome allGenome;
192  for( unsigned int i=0; i<lastPareto.size(); i++ ) {
193  allGenome.append( new nsgaGenotype( lastPareto.at(i), 0, 0.0 ) );
194  }
195  for( unsigned int i=0; i<genome()->size(); i++ ) {
196  allGenome.append( new nsgaGenotype( genome()->at(i), 0, 0.0 ) );
197  }
198  // -2) fastNonDominatedSort( onMergedPopulation )
199  //--- genotype grouped by the front rank
200  QVector<nsgaGenome> frontsByRank = fastNonDominatedSort( allGenome );
201  // -3) create new population of size genome().size() using the fronts
202  // calculated and use the crowdingDistanceAssignment
203  unsigned int currentGenotype = 0;
204  int numOfFronts = frontsByRank.size();
205  int numObjs = allGenome[0]->genotype->numOfObjectives();
206  for( int front=0; front<numOfFronts; front++ ) {
207  //--- sort it on crowding distance and add to the new Genome
208  crowdingDistanceAssignment( frontsByRank[front] );
209  qStableSort( frontsByRank[front].begin(), frontsByRank[front].end(), NSGA2::crowdingDistanceGreaterThan );
210  foreach( nsgaGenotype* gen, frontsByRank[front] ) {
211  //--- assign the rank
212  gen->genotype->setRank( 2*(numOfFronts - front) + (gen->distance/numObjs) );
213  genome()->set( currentGenotype, gen->genotype );
214  currentGenotype++;
215  if ( currentGenotype == genome()->size() ) break;
216  }
217  if ( currentGenotype == genome()->size() ) break;
218  }
219  // -4) lastPareto <- genome()
220  //--- this pass correspond to elite the pareto-fronts
221  lastPareto = *(genome());
222  // -5) clean up memory
223  for( int i=0; i<allGenome.size(); i++ ) {
224  delete (allGenome[i]);
225  }
226  updateStats();
227  evaluationDone = true;
228  for( int i=0; i<numThreadv; i++ ) {
229  evalThreads[i]->eval->endGeneration( generation() );
230  }
231  if ( generation() < numGens ) {
232  currPhase = nextGeneration_pass2;
233  } else {
234  currPhase = endEvolution;
235  }
236  }
237  break;
238  case nextGeneration_pass2: {
239  //--- this additional pass is for avoid to modify the
240  //--- genotypes contained in the last generation of the evolution
241  //--- and to allow to save the genotypes after each generation
242  Genome* old = genome();
243  setGenome( reprod->reproduction( old ) );
244  delete old;
245  fitfunc->setGenome( genome() );
246  evaluationDone = false;
247  setGeneration( generation()+1 );
248  for( int i=0; i<numThreadv; i++ ) {
249  evalThreads[i]->eval->initGeneration( generation() );
250  }
251  currPhase = initEvaluation;
252  }
253  break;
254  case endEvolution:
255  finalize();
256  break;
257  default:
258  qFatal( "Default switch in NSGA2::gaStep" );
259  break;
260  }
261 }
262 
264  // Set evaluation done, and check which phase to go to
265  evaluationDone = true;
266  if ( generation() < numGens ) {
267  currPhase = nextGeneration_pass2;
268  } else {
269  currPhase = endEvolution;
270  }
271 }
272 
274  if ( isFinalized && !isInitialized ) return;
275 
276  isInitialized = false;
277  isFinalized = true;
278  evolutionEnd = true;
279 }
280 
281 QVector<NSGA2::nsgaGenome> NSGA2::fastNonDominatedSort( nsgaGenome& pareto ) {
282  QMap<nsgaGenotype*, nsgaGenome> dominatedBy;
283  QVector<nsgaGenome> frontsByRank;
284  frontsByRank.resize(1);
285  //--- create the first front containing the top solutions
286  for( int p=0; p<pareto.size(); p++ ) {
287  //--- domination counter of genP reset to zero
288  pareto[p]->dominationCounter = 0;
289  for( int q=0; q<pareto.size(); q++ ) {
290  if ( p==q ) continue;
291  if ( pareto[q]->genotype->dominatedBy( pareto[p]->genotype ) ) {
292  // OPTIMIZE: it seems that most of the time is spent on accessing the QMap
293  dominatedBy[ pareto[p] ].append( pareto[q] );
294  } else if ( pareto[p]->genotype->dominatedBy( pareto[q]->genotype ) ) {
295  pareto[p]->dominationCounter++;
296  }
297  }
298  //--- if nP == 0 means that genP is a solution belongs to the top pareto-front
299  if ( pareto[p]->dominationCounter == 0 ) {
300  pareto[p]->rank = 0;
301  frontsByRank[0].append( pareto[p] );
302  }
303  }
304  //--- create all the other fronts
305  bool done = false;
306  int currentFront = 0;
307  while( !done ) {
308  nsgaGenome newFront;
309  for( int i=0; i<frontsByRank[currentFront].size(); i++ ) {
310  nsgaGenotype* p = frontsByRank[currentFront][i];
311  nsgaGenome pDominate = dominatedBy[p];
312  for( int q=0; q<pDominate.size(); q++ ) {
313  pDominate[q]->dominationCounter--;
314  if ( pDominate[q]->dominationCounter == 0 ) {
315  pDominate[q]->rank = currentFront+1;
316  newFront.append( pDominate[q] );
317  }
318  }
319  }
320  currentFront++;
321  if ( newFront.isEmpty() ) {
322  done = true;
323  } else {
324  frontsByRank.append( newFront );
325  }
326  }
327  int total = 0;
328  for( int i=0; i<frontsByRank.size(); i++ ) {
329  total += frontsByRank[i].size();
330  }
331  return frontsByRank;
332 }
333 
334 void NSGA2::crowdingDistanceAssignment( nsgaGenome& genome ) {
335  int dimGenome = genome.size();
336  if ( dimGenome == 0 ) return;
337  int numObjs = genome[0]->genotype->numOfObjectives();
338  //--- vectors containing the max and min values of objectives in this genome
339  QVector<double> fmax;
340  QVector<double> fmin;
341  fmax.resize( numObjs );
342  fmin.resize( numObjs );
343  for( int i=0; i<numObjs; i++ ) {
344  fmax[i] = genome[0]->genotype->objective( i );
345  fmin[i] = genome[0]->genotype->objective( i );
346  }
347  //--- initialize distance and calculate fmax and fmin values
348  for( int i=0; i<dimGenome; i++ ) {
349  genome[i]->distance = 0;
350  for( int m=0; m<numObjs; m++ ) {
351  fmax[m] = qMax( fmax[m], genome[i]->genotype->objective(m) );
352  fmin[m] = qMin( fmin[m], genome[i]->genotype->objective(m) );
353  }
354  }
355  //--- calculate the distance
356  nObjectiveGreaterThan objCompare;
357  for( int m=0; m<numObjs; m++ ) {
358  // currentObjective is used by nObjectiveGreaterThan for sorting
359  objCompare.currentObjective = m;
360  qStableSort( genome.begin(), genome.end(), objCompare );
361  // the maximum value is numObj, setting to numObj assure that this two
362  // genotypes are always the top in the current front
363  genome[0]->distance = numObjs; //DBL_MAX;
364  genome.last()->distance = numObjs; //DBL_MAX;
365  for( int i=1; i<dimGenome-1; i++ ) {
366  double m1 = genome[i+1]->genotype->objective(m);
367  double m2 = genome[i-1]->genotype->objective(m);
368  genome[i]->distance += fabs(m1-m2)/(fmax[m]-fmin[m]);
369  // if the value is nan, then it will setted to zero (worst distance)
370  if ( genome[i]->distance != genome[i]->distance ) {
371  genome[i]->distance = 0.0;
372  }
373  }
374  }
375 }
376 
377 NSGA2::evaluationThread::evaluationThread( NSGA2* p, Evaluation* eProto )
378  : parent(p), id(0), blocked(false) {
379  eval = eProto->clone();
380  eval->setGenome( p->genome() );
381  eval->setGA( p );
382 }
383 
384 NSGA2::evaluationThread::~evaluationThread() {
385  delete eval;
386  sequence.clear();
387 }
388 
389 void NSGA2::evaluationThread::runStep() {
390  if ( blocked ) {
391  return;
392  }
393 
394  parent->nextGeneration = false;
395  eval->evaluateStep();
396  if ( eval->isEvaluationDone() ) {
397  int nextIdSeq = idSeq + 1;
398  eval->finalize();
399  if ( nextIdSeq >= sequence.size() ) {
400  blocked = true;
401  return;
402  }
403  idSeq = nextIdSeq;
404  int nextId = sequence[ idSeq ];
405  id = nextId;
406  eval->initialize( parent->genome()->at( id ) );
407  }
408 }
409 
410 void NSGA2::runStepWrapper( NSGA2::evaluationThread* e ) {
411  e->runStep();
412 }
413 
414 } // end namespace farsa