parallelga.cpp
1 /********************************************************************************
2  * FARSA Genetic Algorithm Library *
3  * Copyright (C) 2007-2009 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/parallelga.h"
22 #include "core/reproduction.h"
23 #include "core/genome.h"
24 #include "core/evaluation.h"
25 #include "configurationhelper.h"
26 #include <QThreadPool>
27 #include <QtConcurrentMap>
28 using namespace QtConcurrent;
29 
30 namespace farsa {
31 
32 ParallelGA::ParallelGA()
33  : GeneticAlgo() {
34  fitfunc = 0;
35  reprod = 0;
36  numGens = 0;
37  currPhase = initEvaluation;
38  numThreadv = 1;
39  isInitialized = false;
40  isFinalized = true;
41  future = new QFuture<void>();
42 }
43 
45  foreach( ParallelGA::evaluationThread* e, evalThreads ) {
46  delete e;
47  }
48  delete fitfunc;
49 }
50 
51 void ParallelGA::configure( ConfigurationParameters& params, QString prefix ) {
52  setGenome( params.getObjectFromGroup<Genome>( prefix + QString( "GENOME" ) ) );
53  setEvaluation( params.getObjectFromGroup<Evaluation>( prefix + QString( "EVALUATION" ) ) );
54  fitfunc->setGenome( genome() );
55  setReproduction( params.getObjectFromGroup<Reproduction>( prefix + QString( "REPRODUCTION" ) ) );
56  setNumGenerations( ConfigurationHelper::getInt( params, prefix + QString( "ngenerations" ), 1000 ) );
57  setNumThreads( ConfigurationHelper::getInt( params, prefix + QString( "numThreads" ), 1 ) );
58 }
59 
60 void ParallelGA::save( ConfigurationParameters& params, QString prefix ) {
61  params.createParameter( prefix, QString("type"), "ParallelGA" );
62  params.createParameter( prefix, QString("numThreads"), QString("%1").arg( numThreads() ) );
63  params.createParameter( prefix, QString("ngenerations"), QString("%1").arg( numGenerations() ) );
64  //--- EVALUATION
65  fitfunc->save( params, params.createSubGroup( prefix, "EVALUATION" ) );
66  //--- REPRODUCTION
67  reproduction()->save( params, params.createSubGroup( prefix, "REPRODUCTION" ) );
68  //--- GENOME
69  genome()->save( params, params.createSubGroup( prefix, "GENOME" ) );
70 }
71 
72 void ParallelGA::describe( QString type ) {
73  Descriptor d = addTypeDescription( type, "Parallel Genetic Algorithm", "Respect to SimpleGA and others type of Genetic Algorithm, the implementation of the parallelization is more efficient" );
74  d.describeInt( "numThreads" ).limits( 1, 32 ).def(1).help( "Number of threads to parallelize the evaluation of individuals" ).runtime(&ParallelGA::setNumThreads, &ParallelGA::numThreads);
75  d.describeInt( "ngenerations" ).limits( 1, INT_MAX ).def( 1000 ).help( "Number of the generations of the evolutionary process" );
76  d.describeSubgroup( "EVALUATION" ).type( "Evaluation" ).props( IsMandatory ).help( "Object that calculate the fitness", "Create a subclass of Evalution and code your custom fitness function" );
77  d.describeSubgroup( "REPRODUCTION").type( "Reproduction" ).props( IsMandatory ).help( "Object that generate the new generations" );
78  d.describeSubgroup( "GENOME" ).type( "Genome" ).props( IsMandatory ).help( "Object containing the individuals under evolution" );
79 }
80 
81 void ParallelGA::setNumThreads( int numThreads ) {
82  if ( numThreads < 1 ) {
83  qWarning( "The number of Threads must be greater than one!!" );
84  }
85  Q_ASSERT_X( !isInitialized && isFinalized ,
86  "ParallelGA::setNumThreads",
87  "This method can only called before initialize of ParallelGA" );
88  Q_ASSERT_X( fitfunc != 0 ,
89  "ParallelGA::setNumThreads",
90  "This method must be called after an Evaluation object has been setted by ParallelGA::setEvaluation" );
91  numThreadv = numThreads;
92  return;
93 }
94 
96  return numThreadv;
97 }
98 
100  this->fitfunc = fitfunc;
101  this->fitfunc->setGA( this );
102 }
103 
105 {
106  return fitfunc;
107 }
108 
109 QVector<Evaluation*> ParallelGA::evaluationPool() {
110  QVector<Evaluation*> ev;
111  foreach( ParallelGA::evaluationThread* e, evalThreads ) {
112  ev.append( e->eval );
113  }
114  return ev;
115 }
116 
118  this->reprod = reprod;
119  this->reprod->setGA( this );
120 }
121 
123  return reprod;
124 }
125 
127  if ( isInitialized && !isFinalized ) return;
128  Q_ASSERT_X( fitfunc != 0 ,
129  "ParallelGA::initialize",
130  "You have to setup the Evaluation object of ParallelGA (Fitness Function)" );
131  Q_ASSERT_X( reprod !=0 ,
132  "ParallelGA::initialize",
133  "You have to setup the Reproduction operator of ParallelGA" );
134 
135  isInitialized = true;
136  isFinalized = false;
137  setGeneration( 0 );
138  currPhase = initEvaluation;
139  evolutionEnd = false;
140  evaluationDone = false;
141  getIODelegate()->recoverData(this);
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( fitfunc ) );
149  evalThreads.last()->eval->initGeneration( generation() );
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  }
169  currPhase = evaluating;
170  //--- here also starts to run all sub-threads for evaluation
171  //--- it evaluate all genotypes of the population in separate threads
172  (*future) = map( evalThreads, ParallelGA::runStepWrapper );
173  break;
174  case evaluating: /* Multi Thread Block (i.e. Parallel Evaluation of Genotypes */
175  //--- check if the evaluation has been completed
176  if ( future->isFinished() ) {
177  currPhase = nextGeneration_pass1;
178  }
179  break;
180  case nextGeneration_pass1:
181  qSort( genome()->begin(), genome()->end(), Genotype::rankGreaterThanComparator );
182  updateStats();
183  evaluationDone = true;
184  for( int i=0; i<numThreadv; i++ ) {
185  evalThreads[i]->eval->endGeneration( generation() );
186  }
188  getIODelegate()->saveData(this);
189  if ( generation() < numGens ) {
190  currPhase = nextGeneration_pass2;
191  } else {
192  currPhase = endEvolution;
193  }
194  break;
195  case nextGeneration_pass2: {
196  //--- this additional pass is for avoid to modify the
197  //--- genotypes contained in the last generation of the evolution
198  //--- and to allow to save the genotypes after each generation
199  Genome* old = genome();
200  setGenome( reprod->reproduction( old ) );
201  delete old;
202  fitfunc->setGenome( genome() );
203  evaluationDone = false;
204  setGeneration( generation()+1 );
205  for( int i=0; i<numThreadv; i++ ) {
206  evalThreads[i]->eval->initGeneration( generation() );
207  }
208  currPhase = initEvaluation;
209  }
210  break;
211  case endEvolution:
212  finalize();
213  break;
214  default:
215  qFatal( "Default switch in ParallelGA::gaStep" );
216  break;
217  }
218 }
219 
221  // Set evaluation done, and check which phase to go to
222  evaluationDone = true;
223  if ( generation() < numGens ) {
224  currPhase = nextGeneration_pass2;
225  } else {
226  currPhase = endEvolution;
227  }
228 }
229 
231  if ( isFinalized && !isInitialized ) return;
232 
233  isInitialized = false;
234  isFinalized = true;
235  evolutionEnd = true;
236 }
237 
238 ParallelGA::evaluationThread::evaluationThread( Evaluation* eProto )
239  : id(0) {
240  eval = eProto->clone();
241  eval->setGenome( eProto->GA()->genome() );
242  eval->setGA( eProto->GA() );
243 }
244 
245 ParallelGA::evaluationThread::~evaluationThread() {
246  delete eval;
247  sequence.clear();
248 }
249 
250 void ParallelGA::evaluationThread::runStep() {
251  //--- it evaluate all individual assigned to this thread
252  while( true ) {
253  eval->initialize( eval->GA()->genome()->at( id ) );
254  eval->evaluate();
255  int nextIdSeq = idSeq + 1;
256  eval->finalize();
257  eval->genotype()->setRank( eval->genotype()->fitness() );
258  if ( nextIdSeq >= sequence.size() ) {
259  return;
260  }
261  idSeq = nextIdSeq;
262  int nextId = sequence[ idSeq ];
263  id = nextId;
264  }
265 }
266 
267 void ParallelGA::runStepWrapper( ParallelGA::evaluationThread* e ) {
268  e->runStep();
269 }
270 
271 } // end namespace farsa