From 821e79ac975924de6c70be946c8769f9c44b8d87 Mon Sep 17 00:00:00 2001 From: Ronaldd Pinho Date: Sat, 29 Jun 2019 00:03:45 -0300 Subject: [PATCH] eoSGAVerbose class was added --- eo/src/eoSGA.h | 71 +++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 70 insertions(+), 1 deletion(-) diff --git a/eo/src/eoSGA.h b/eo/src/eoSGA.h index b31dff04e..7ab93063c 100644 --- a/eo/src/eoSGA.h +++ b/eo/src/eoSGA.h @@ -36,6 +36,7 @@ #include #include + /** The Simple Genetic Algorithm, following Holland and Goldberg * * Needs a selector (class eoSelectOne) a crossover (eoQuad, i.e. a @@ -105,7 +106,7 @@ public : } while (cont(_pop)); } -private : +protected: eoContinue& cont; /// eoInvalidateMonOp invalidates the embedded operator @@ -118,4 +119,72 @@ private : eoEvalFunc& eval; }; + +template +class eoSGAVerbose : protected eoSGA +{ +public : + + using eoSGA::select; + using eoSGA::cross; + using eoSGA::crossoverRate; + using eoSGA::mutate; + using eoSGA::mutationRate; + using eoSGA::eval; + using eoSGA::cont; + + // added this second ctor as I didn't like the ordering of the parameters + // in the one above. Any objection :-) MS + eoSGAVerbose( + eoSelectOne& _select, + eoQuadOp& _cross, float _crate, + eoMonOp& _mutate, float _mrate, + eoEvalFunc& _eval, + eoContinue& _cont) + : eoSGA(_select, _cross, _crate, _mutate, _mrate, _eval, _cont) {} + + void operator()(eoPop& _pop) + { + eoPop offspring; + unsigned gen=0; + + do + { + _pop.sort(); + std::cout << "G" << ++gen << " --> "; + std::cout << _pop[0] << std::endl; + + select(_pop, offspring); + + unsigned i; + + for (i=0; i<_pop.size()/2; i++) + { + if ( rng.flip(crossoverRate) ) + { + // this crossover generates 2 offspring from two parents + if (cross(offspring[2*i], offspring[2*i+1])) + { + offspring[2*i].invalidate(); + offspring[2*i+1].invalidate(); + } + } + } + + for (i=0; i < offspring.size(); i++) + { + if (rng.flip(mutationRate) ) + { + if (mutate(offspring[i])) + offspring[i].invalidate(); + } + } + + _pop.swap(offspring); + apply(eval, _pop); + + } while (cont(_pop)); + } +}; + #endif