From a233802f6c382ed4550169cebd930a85fa9dbedd Mon Sep 17 00:00:00 2001 From: Mike Date: Sat, 14 Apr 2018 04:18:05 -0700 Subject: [PATCH] Duplicated EvaluateFitness() to EvaluateError(), reversed --- Population.cpp | 74 ++++++++++++++++++++++++++++++++++++++++++++++++++ Population.h | 5 ++++ 2 files changed, 79 insertions(+) diff --git a/Population.cpp b/Population.cpp index 4519774..d36cdcd 100644 --- a/Population.cpp +++ b/Population.cpp @@ -237,6 +237,45 @@ namespace BitEvolver } } + // + void Population::EvaluateError(std::function)> evaluation_callback) + { + // + std::shared_ptr>> _chromosomes_copy; + std::vector> threads; + std::shared_ptr thread; + int + threads_count, + i + ; + + // Make a new vector containing all current chromosomes + this->population_modification_mutex.lock(); + _chromosomes_copy = std::shared_ptr>>( + new std::vector>() + ); + for ( i=0; i<(int)this->chromosomes.size(); i++ ) { + _chromosomes_copy->push_back( this->chromosomes[i] ); + } + this->population_modification_mutex.unlock(); + + // Spawn threads + threads_count = this->GetThreadCountSuggestion(); + for ( i=0; i( + new std::thread(&Population::EvaluateError_Thread, this, _chromosomes_copy, evaluation_callback) + ); + threads.push_back(thread); + } + + // Wait for threads to finish + for ( i=0; ijoin(); + } + } + // void Population::Evolve() { @@ -448,6 +487,41 @@ namespace BitEvolver } } + // + void Population::EvaluateError_Thread( + std::shared_ptr>> _chromosomes, + std::function)> evaluation_callback + ) + { + // + std::shared_ptr chromosome; + double error; + + // + while (true) + { + // Grab a free chromosome + this->evaluate_fitness_mutex.lock(); + chromosome = nullptr; + if ( _chromosomes->size() ) { + chromosome = _chromosomes->at(_chromosomes->size()-1); + _chromosomes->pop_back(); + } + this->evaluate_fitness_mutex.unlock(); + + // Call the evaluation callback + if ( chromosome != nullptr ) { + error = evaluation_callback(chromosome); + chromosome->SetError(error); + } + + // We're done if there was nothing to grab + else{ + break; + } + } + } + // std::shared_ptr Population::BreedChild() { diff --git a/Population.h b/Population.h index 24fc6fe..776c492 100644 --- a/Population.h +++ b/Population.h @@ -58,6 +58,7 @@ namespace BitEvolver // void EvaluateFitness(std::function)> evaluation_callback); + void EvaluateError(std::function)> evaluation_callback); // void Evolve(); @@ -117,6 +118,10 @@ namespace BitEvolver std::shared_ptr>> _chromosomes, std::function)> evaluation_callback ); + void EvaluateError_Thread( + std::shared_ptr>> _chromosomes, + std::function)> evaluation_callback + ); // std::shared_ptr BreedChild();