parallelga.h
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 #ifndef PARALLELGA_H
21 #define PARALLELGA_H
22 
23 #include "gaconfig.h"
24 #include "core/geneticalgo.h"
25 #include <QList>
26 #include <QFuture>
27 
28 namespace farsa {
29 
30 class Evaluation;
31 class Reproduction;
32 
44 class FARSA_GA_API ParallelGA : public GeneticAlgo {
45 public:
47  ParallelGA();
49  virtual ~ParallelGA();
53  void setNumThreads( int numThreads );
55  int numThreads();
57  void setEvaluation( Evaluation* fitfunc );
62  virtual Evaluation* evaluationPrototype();
64  virtual QVector<Evaluation*> evaluationPool();
66  void setReproduction( Reproduction* reproduct );
68  Reproduction* reproduction();
71  virtual void initialize();
73  virtual void gaStep();
75  virtual void finalize();
76 
81  virtual void skipEvaluation();
82 
90  virtual void configure( ConfigurationParameters& params, QString prefix );
97  virtual void save( ConfigurationParameters& params, QString prefix );
99  static void describe( QString type );
100 
101 protected:
107  typedef enum { initEvaluation, evaluating, nextGeneration_pass1, nextGeneration_pass2, endEvolution } GAPhases;
114 
115 private:
117  bool nextGeneration;
118 
123  class evaluationThread {
124  public:
125  //--- Constructor
126  evaluationThread( Evaluation* eProto );
127  //--- Destructor
128  ~evaluationThread();
129  //--- evaluator used by this object
130  Evaluation* eval;
131  //--- evaluating genoma
132  int id;
133  //--- run a step of evaluation
134  void runStep();
135  //--- sequence of Genoma to evaluate
136  QVector<int> sequence;
137  //--- actual id inside sequence in evaluating
138  int idSeq;
139  };
140 
142  QList<evaluationThread*> evalThreads;
144  int numThreadv;
146  static void runStepWrapper( ParallelGA::evaluationThread* e );
148  QFuture<void>* future;
149 };
150 
151 } // end namespace farsa
152 
153 #endif