21 #include "gas/parallelga.h"
22 #include "core/reproduction.h"
23 #include "core/genome.h"
24 #include "core/evaluation.h"
25 #include <QThreadPool>
26 #include <QtConcurrentMap>
27 using namespace QtConcurrent;
31 ParallelGA::ParallelGA()
40 future =
new QFuture<void>();
44 foreach( ParallelGA::evaluationThread* e, evalThreads ) {
57 qWarning(
"Setting number of Generations to ZERO!! Check your config file" );
75 Descriptor d =
addTypeDescription( type,
"Parallel Genetic Algorithm",
"Respect to SimpleGA and others type of Genetic Algorithm, the implementation of the parallelization is more efficient" );
76 d.
describeInt(
"numThreads" ).
limits( 1, 32 ).
help(
"Number of threads to parallelize the evaluation of individuals" );
77 d.
describeInt(
"ngenerations" ).
limits( 1, INT_MAX ).
def( 1000 ).
help(
"Number of the generations of the evolutionary process" );
84 if ( numThreads < 1 ) {
85 qWarning(
"The number of Threads must be greater than one!!" );
88 "ParallelGA::setNumThreads",
89 "This method can only called before initialize of ParallelGA" );
91 "ParallelGA::setNumThreads",
92 "This method must be called after an Evaluation object has been setted by ParallelGA::setEvaluation" );
103 this->fitfunc->
setGA(
this );
112 QVector<Evaluation*> ev;
113 foreach( ParallelGA::evaluationThread* e, evalThreads ) {
114 ev.append( e->eval );
121 this->reprod->
setGA(
this );
131 "ParallelGA::initialize",
132 "You have to setup the Evaluation object of ParallelGA (Fitness Function)" );
134 "ParallelGA::initialize",
135 "You have to setup the Reproduction operator of ParallelGA" );
144 for(
int i=0; i<evalThreads.size(); i++ ) {
145 delete (evalThreads[i]);
148 for(
int i=0; i<numThreadv; i++ ) {
149 evalThreads.append(
new evaluationThread(
fitfunc ) );
152 QThreadPool::globalInstance()->setMaxThreadCount( numThreadv );
158 for(
int i=0; i<numThreadv; i++ ) {
159 evalThreads[i]->sequence.clear();
161 for(
int i=0; i<(int)
genome()->
size(); i++ ) {
162 evalThreads[ i%numThreadv ]->sequence.append( i );
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() );
172 (*future) = map( evalThreads, ParallelGA::runStepWrapper );
176 if ( future->isFinished() ) {
180 case nextGeneration_pass1:
190 case nextGeneration_pass2: {
207 qFatal(
"Default switch in ParallelGA::gaStep" );
230 ParallelGA::evaluationThread::evaluationThread(
Evaluation* eProto )
232 eval = eProto->
clone();
234 eval->setGA( eProto->
GA() );
237 ParallelGA::evaluationThread::~evaluationThread() {
242 void ParallelGA::evaluationThread::runStep() {
245 eval->initialize( eval->GA()->genome()->at(
id ) );
247 int nextIdSeq = idSeq + 1;
249 eval->genotype()->setRank( eval->genotype()->fitness() );
250 if ( nextIdSeq >= sequence.size() ) {
254 int nextId = sequence[ idSeq ];
259 void ParallelGA::runStepWrapper( ParallelGA::evaluationThread* e ) {