From 85a326c5e496d0f9932ad8790d68e2f153655a4c Mon Sep 17 00:00:00 2001 From: kuepper Date: Thu, 23 Dec 2004 15:29:07 +0000 Subject: [PATCH] Adjust code to perform to C++ standard according to gcc-3.4 interpretation... (Have not compiled/checked/changed paradisEO.) That is, the current code compiles with gcc-3.4 and the checks (besides t-MGE1bit) all pass. --- eo/app/gprop/mlp.h | 89 ++++---- eo/app/mastermind/mastermind.cpp | 32 +-- eo/contrib/MGE/eoVirus.h | 18 +- eo/src/eoDominanceMap.h | 16 +- eo/src/eoLinearFitScaling.h | 73 +++---- eo/src/eoNDSorting.h | 118 ++++++----- eo/src/eoOpContainer.h | 74 +++---- eo/src/eoParetoRanking.h | 9 +- eo/src/eoPerf2Worth.h | 86 ++++---- eo/src/eoPopulator.h | 83 ++++---- eo/src/eoRanking.h | 5 +- eo/src/eoScalarFitnessAssembled.h | 101 ++++----- eo/src/eoSelectFromWorth.h | 157 +++++++------- eo/src/eoSharing.h | 20 +- eo/src/eoSurviveAndDie.h | 55 ++--- eo/src/eoVector.h | 24 ++- eo/src/es/eoEsFull.h | 8 +- eo/src/es/eoEsStdev.h | 6 +- eo/src/es/eoNormalMutation.h | 42 ++-- eo/src/ga/eoBit.h | 16 +- eo/src/ga/eoPBILAdditive.h | 20 +- eo/src/gp/eoParseTree.h | 60 +++--- eo/src/gp/parse_tree.h | 285 ++++++++++++++------------ eo/src/other/eoExternalEO.h | 31 +-- eo/src/other/eoString.h | 20 +- eo/src/utils/eoAssembledFitnessStat.h | 70 ++++--- eo/src/utils/eoFDCStat.h | 10 +- eo/src/utils/eoMOFitnessStat.h | 8 +- eo/src/utils/eoPopStat.h | 72 ++++--- eo/src/utils/eoScalarFitnessStat.h | 15 +- eo/src/utils/eoStat.h | 95 ++++++--- eo/src/utils/eoUpdater.h | 31 +-- eo/src/utils/selectors.h | 86 ++++---- eo/test/t-MGE1bit.cpp | 38 ++-- eo/test/t-eoPareto.cpp | 30 ++- 35 files changed, 1048 insertions(+), 855 deletions(-) diff --git a/eo/app/gprop/mlp.h b/eo/app/gprop/mlp.h index b0e7a232..2667002a 100644 --- a/eo/app/gprop/mlp.h +++ b/eo/app/gprop/mlp.h @@ -48,7 +48,7 @@ namespace std { copy(v.begin(), v.end(), oi); return os; } - + istream& operator>>(istream& is, mlp::vector& v) { for (mlp::vector::iterator vi = v.begin() ; vi != v.end() ; vi++) { @@ -63,8 +63,8 @@ namespace mlp //--------------------------------------------------------------------------- // useful typedefs //--------------------------------------------------------------------------- - - + + const real max_real = MLP_MAXFLOAT; const real min_real = MLP_MINFLOAT; @@ -72,38 +72,38 @@ namespace mlp //--------------------------------------------------------------------------- // sigmoid //--------------------------------------------------------------------------- - + real sigmoid(const real& x) { return 1.0 / (1.0 + exp(-x)); } - - + + //--------------------------------------------------------------------------- // neuron //--------------------------------------------------------------------------- - + struct neuron { real bias; vector weight; - + neuron(const unsigned& num_inputs = 0): weight(num_inputs) {} - + void reset() { normal_generator rnd(1.0); bias = rnd(); generate(weight.begin(), weight.end(), rnd); } - + real operator()(const vector& input) const { return sigmoid(bias + weight * input); } unsigned length() const { return weight.size() + 1; } - + void normalize() { real n = sqrt(bias * bias + weight * weight); @@ -114,7 +114,7 @@ namespace mlp void desaturate() { bias = -5.0 + 10.0 / (1.0 + exp(bias / -5.0)); - + for (vector::iterator w = weight.begin(); w != weight.end(); ++w) *w = -5.0 + 10.0 / (1.0 + exp(*w / -5.0)); } @@ -127,7 +127,7 @@ namespace mlp void perturb(double magnitude = 0.3, double probability = 1.0) { - + for (vector::iterator w = weight.begin(); w != weight.end(); ++w) if ( probability >= 1.0 || drand48() < probability) perturb_num(*w, magnitude); @@ -143,7 +143,7 @@ namespace std { { return os << n.bias << " " << n.weight; } - + istream& operator>>(istream& is, mlp::neuron& n) { return is >> n.bias >> n.weight; @@ -152,15 +152,15 @@ namespace std { } namespace mlp { - + //--------------------------------------------------------------------------- // layer //--------------------------------------------------------------------------- - + class layer: public std::vector { public: - layer(const unsigned& num_inputs = 0, const unsigned& num_neurons = 0): + layer(const unsigned& num_inputs = 0, const unsigned& num_neurons = 0): std::vector(num_neurons, neuron(num_inputs)) {} void reset() @@ -169,11 +169,11 @@ namespace mlp { for(iterator n = begin(); n != end(); ++n) n->reset(); } - + vector operator()(const vector& input) const { vector output(size()); - + for(unsigned i = 0; i < output.size(); ++i) output[i] = (*this)[i](input); @@ -212,7 +212,7 @@ namespace std { copy(l.begin(), l.end(), oi); return os; } - + istream& operator>>(istream& is, mlp::layer& l) { for (mlp::layer::iterator li = l.begin() ; li != l.end() ; li++) { @@ -224,7 +224,7 @@ namespace std { } namespace mlp { - + //--------------------------------------------------------------------------- // net @@ -234,7 +234,7 @@ namespace mlp { { public: net(const unsigned& num_inputs = 0, - const unsigned& num_outputs = 0, + const unsigned& num_outputs = 0, const std::vector& hidden = std::vector()) { init(num_inputs,num_outputs,hidden); @@ -272,8 +272,8 @@ namespace mlp { assert(c == '>'); } - void init( unsigned num_inputs, - unsigned num_outputs, + void init( unsigned num_inputs, + unsigned num_outputs, const std::vector& hidden ) { clear(); switch(hidden.size()) @@ -317,21 +317,21 @@ namespace mlp { unsigned num_inputs() const { return front().front().length() - 1; } unsigned num_outputs() const { return back().size(); } - unsigned num_hidden_layers() const { - signed s = (signed) size() -1; + unsigned num_hidden_layers() const { + signed s = (signed) size() -1; return (s<0) ? 0 : s ; } - unsigned length() + unsigned length() { unsigned sum = 0; for(iterator l = begin(); l != end(); ++l) sum += l->length(); - - return sum; - } + + return sum; + } void normalize() { @@ -356,38 +356,38 @@ namespace mlp { vector net::operator()(const vector& input) const { vector tmp = input; - + for(const_iterator l = begin(); l != end(); ++l) tmp = (*l)(tmp); - + return tmp; - } + } #endif //--------------------------------------------------------------------------- // sample //--------------------------------------------------------------------------- - + struct sample { vector input, output; - + sample(unsigned input_size = 0, unsigned output_size = 0): input(input_size), output(output_size) {} }; - + istream& operator>>(istream& is, sample& s) { return is >> s.input >> s.output; } - + ostream& operator<<(ostream& os, const sample& s) { return os << s.input << " " << s.output; } - + //--------------------------------------------------------------------------- // set //--------------------------------------------------------------------------- @@ -395,8 +395,8 @@ namespace mlp { class set: public std::vector { public: - set(unsigned input_size = 0, unsigned output_size = 0, - unsigned num_samples = 0): + set(unsigned input_size = 0, unsigned output_size = 0, + unsigned num_samples = 0): std::vector(num_samples, sample(input_size, output_size)) {} set(istream& is) : std::vector(0, sample(0, 0)) { @@ -433,9 +433,9 @@ namespace mlp { { real sum = 0; - for(net::const_reverse_iterator l1 = n1.rbegin(), l2 = n2.rbegin(); + for(net::const_reverse_iterator l1 = n1.rbegin(), l2 = n2.rbegin(); l1 != n1.rend() && l2 != n2.rend(); ++l1, ++l2) - for(layer::const_iterator n1 = l1->begin(), n2 = l2->begin(); + for(layer::const_iterator n1 = l1->begin(), n2 = l2->begin(); n1 != l1->end() && n2 != l2->end(); ++n1, ++n2) { real b = n1->bias - n2->bias; @@ -462,6 +462,7 @@ namespace mlp { #endif // mlp_h -// Local Variables: -// mode:C++ +// Local Variables: +// mode:C++ +// c-file-style: "Stroustrup" // End: diff --git a/eo/app/mastermind/mastermind.cpp b/eo/app/mastermind/mastermind.cpp index 7a971efe..9a2ed163 100644 --- a/eo/app/mastermind/mastermind.cpp +++ b/eo/app/mastermind/mastermind.cpp @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- #include // EXIT_SUCCESS EXIT_FAILURE -#include // exception +#include // exception #include // cerr cout #include // ifstream #include // string @@ -51,8 +51,8 @@ int main(int argc, char** argv) } catch (exception& e) { - cerr << argv[0] << ": " << e.what() << endl; - exit(EXIT_FAILURE); + cerr << argv[0] << ": " << e.what() << endl; + exit(EXIT_FAILURE); } return 0; @@ -65,7 +65,7 @@ int main(int argc, char** argv) void arg(int argc, char** argv) { eoParser parser(argc, argv); - + parser.processParam(pop_size, "genetic operators"); parser.processParam(generations, "genetic operators"); parser.processParam(mut_rate, "genetic operators"); @@ -90,49 +90,49 @@ void ga() // create population eoInitChrom init; eoPop pop(pop_size.value(), init); - + // evaluate population eoEvalFuncPtr evaluator(eoChromEvaluator); apply(evaluator, pop); - + // selector eoProportionalSelect select(pop); // genetic operators eoChromMutation mutation; eoChromXover xover; - + // stop condition eoGenContinue continuator1(generations.value()); - eoFitContinue continuator2(solution.fitness()); + eoFitContinue continuator2(solution.fitness()); eoCombinedContinue continuator(continuator1, continuator2); // checkpoint eoCheckPoint checkpoint(continuator); - + // monitor eoStdoutMonitor monitor; checkpoint.add(monitor); - + // statistics eoBestFitnessStat stats; checkpoint.add(stats); monitor.add(stats); - + // genetic algorithm eoSGA sga(select, - xover, xover_rate.value(), - mutation, mut_rate.value(), - evaluator, + xover, xover_rate.value(), + mutation, mut_rate.value(), + evaluator, checkpoint); sga(pop); - + cout << "solution = " << solution << endl << "best = " << *max_element(pop.begin(), pop.end()) << endl; } //----------------------------------------------------------------------------- -// Local Variables: +// Local Variables: // mode:C++ // End: diff --git a/eo/contrib/MGE/eoVirus.h b/eo/contrib/MGE/eoVirus.h index 720e2eda..a7a61a63 100644 --- a/eo/contrib/MGE/eoVirus.h +++ b/eo/contrib/MGE/eoVirus.h @@ -18,7 +18,7 @@ Contact: todos@geneura.ugr.es, http://geneura.ugr.es Marc.Schoenauer@polytechnique.fr -CVS Info: $Date: 2003-02-27 19:26:44 $ $Header: /home/nojhan/dev/eodev/eodev_cvs/eo/contrib/MGE/eoVirus.h,v 1.2 2003-02-27 19:26:44 okoenig Exp $ $Author: okoenig $ +CVS Info: $Date: 2004-12-23 15:29:07 $ $Header: /home/nojhan/dev/eodev/eodev_cvs/eo/contrib/MGE/eoVirus.h,v 1.3 2004-12-23 15:29:07 kuepper Exp $ $Author: kuepper $ */ #ifndef eoVirus_h @@ -43,9 +43,15 @@ CVS Info: $Date: 2003-02-27 19:26:44 $ $Header: /home/nojhan/dev/eodev/eodev_cvs \ingroup bitstring * based on STL's vector specialization. */ -template class eoVirus: public eoBit +template +class eoVirus: public eoBit { - public: +public: + + using eoBit::begin; + using eoBit::end; + using eoBit::size; + /** * (Default) Constructor. @@ -110,3 +116,9 @@ template class eoVirus: public eoBit //----------------------------------------------------------------------------- #endif //eoBit_h + + +// Local Variables: +// mode: C++ +// c-file-style: "Stroustrup" +// End: diff --git a/eo/src/eoDominanceMap.h b/eo/src/eoDominanceMap.h index fab752b7..fa57e507 100644 --- a/eo/src/eoDominanceMap.h +++ b/eo/src/eoDominanceMap.h @@ -46,16 +46,14 @@ template class eoDominanceMap : public eoUF&, void>, public std::vector > { - public : +public: - /** - Clears the map - */ - void clear() - { - std::vector >::clear(); - fitnesses.clear(); - } + /** Clears the map */ + void clear() { + std::vector >::clear(); +#warning Is this correct? Was: "fitnesses.clear()" + fitness.clear(); + } /** Update or create the dominance map diff --git a/eo/src/eoLinearFitScaling.h b/eo/src/eoLinearFitScaling.h index ead16039..e33858b6 100644 --- a/eo/src/eoLinearFitScaling.h +++ b/eo/src/eoLinearFitScaling.h @@ -1,9 +1,9 @@ /** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- ----------------------------------------------------------------------------- - eoLinearFitScaling.h + eoLinearFitScaling.h (c) GeNeura Team, 1998, Maarten Keijzer, Marc Schoenauer, 2001 - + This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -43,47 +43,48 @@ template class eoLinearFitScaling : public eoPerf2Worth // false: do not cache fitness { public: - /* Ctor: - @param _p selective pressure (in (1,2] - @param _e exponent (1 == linear) - */ - eoLinearFitScaling(double _p=2.0): - pressure(_p) {} - /* COmputes the ranked fitness: fitnesses range in [m,M] - with m=2-pressure/popSize and M=pressure/popSize. - in between, the progression depends on exponent (linear if 1). - */ - virtual void operator()(const eoPop& _pop) - { - unsigned pSize =_pop.size(); - // value() refers to the vector of worthes (we're in an eoParamvalue) - value().resize(pSize); + using eoLinearFitScaling< EOT >::value; - // best and worse fitnesses - double bestFitness = static_cast (_pop.best_element().fitness()); - // double worstFitness = static_cast (_pop.worse_element().fitness()); + /* Ctor: + @param _p selective pressure (in (1,2]) + @param _e exponent (1 == linear) + */ + eoLinearFitScaling(double _p=2.0) + : pressure(_p) {} - // average fitness - double sum=0.0; - unsigned i; - for (i=0; i(_pop[i].fitness()); - double averageFitness = sum/pSize; + /* COmputes the ranked fitness: fitnesses range in [m,M] + with m=2-pressure/popSize and M=pressure/popSize. + in between, the progression depends on exponent (linear if 1). + */ + virtual void operator()(const eoPop& _pop) { + unsigned pSize =_pop.size(); + // value() refers to the vector of worthes (we're in an eoParamvalue) + value().resize(pSize); - // the coefficients for linear scaling - double denom = pSize*(bestFitness - averageFitness); - double alpha = (pressure-1)/denom; - double beta = (bestFitness - pressure*averageFitness)/denom; + // best and worse fitnesses + double bestFitness = static_cast (_pop.best_element().fitness()); + // double worstFitness = static_cast (_pop.worse_element().fitness()); - for (i=0; i(_pop[i].fitness()); + double averageFitness = sum/pSize; + // the coefficients for linear scaling + double denom = pSize*(bestFitness - averageFitness); + double alpha = (pressure-1)/denom; + double beta = (bestFitness - pressure*averageFitness)/denom; + + for (i=0; i class eoNDSorting : public eoPerf2WorthCached { - public : - - eoNDSorting() : nasty_declone_flag_that_only_is_implemented_for_two_objectives(false) - {} - +public: + + using eoNDSorting< EOT >::value; + + eoNDSorting() + : nasty_declone_flag_that_only_is_implemented_for_two_objectives(false) + {} + /** Pure virtual function that calculates the 'distance' for each element in the current front Implement to create your own nondominated sorting algorithm. The size of the returned std::vector should be equal to the size of the current_front. @@ -56,7 +59,7 @@ class eoNDSorting : public eoPerf2WorthCached { // resize the worths beforehand value().resize(_pop.size()); - + typedef typename EOT::Fitness::fitness_traits traits; switch (traits::nObjectives()) @@ -77,7 +80,7 @@ class eoNDSorting : public eoPerf2WorthCached } } } - + private : /** used in fast nondominated sorting @@ -90,7 +93,7 @@ private : }; void one_objective(const eoPop& _pop) - { + { unsigned i; std::vector tmp_pop; tmp_pop.resize(_pop.size()); @@ -101,23 +104,23 @@ private : tmp_pop[i].fitness(_pop[i].fitness()); tmp_pop[i].index = i; } - + std::sort(tmp_pop.begin(), tmp_pop.end(), std::greater()); - + for (i = 0; i < _pop.size(); ++i) { value()[tmp_pop[i].index] = _pop.size() - i; // set rank } - + // no point in calculcating niche penalty, as every distinct fitness value has a distinct rank } - + /** * Optimization for two objectives. Makes the algorithm run in * complexity O(n log n) where n is the population size * * This is the same complexity as for a single objective - * or truncation selection or sorting. + * or truncation selection or sorting. * * It will perform a sort on the two objectives seperately, * and from the information on the ranks of the individuals on @@ -129,15 +132,15 @@ private : * After that it is a simple exercise to calculate the distance * penalty */ - + void two_objectives(const eoPop& _pop) - { + { unsigned i; typedef typename EOT::Fitness::fitness_traits traits; assert(traits::nObjectives() == 2); - + std::vector sort1(_pop.size()); // index into population sorted on first objective - + for (i = 0; i < _pop.size(); ++i) { sort1[i] = i; @@ -146,34 +149,34 @@ private : std::sort(sort1.begin(), sort1.end(), Sorter(_pop)); // Ok, now the meat of the algorithm - + unsigned last_front = 0; - + double max1 = -1e+20; for (i = 0; i < _pop.size(); ++i) { max1 = std::max(max1, _pop[i].fitness()[1]); } - + max1 = max1 + 1.0; // add a bit to it so that it is a real upperbound - + unsigned prev_front = 0; std::vector d; d.resize(_pop.size(), max1); // initialize with the value max1 everywhere - + std::vector > fronts(_pop.size()); // to store indices into the front - + for (i = 0; i < _pop.size(); ++i) { unsigned index = sort1[i]; - - // check for clones and delete them + + // check for clones and delete them if (0 && i > 0) { unsigned prev = sort1[i-1]; if ( _pop[index].fitness() == _pop[prev].fitness()) { // it's a clone, give it the worst rank! - + if (nasty_declone_flag_that_only_is_implemented_for_two_objectives) //declone fronts.back().push_back(index); @@ -182,32 +185,32 @@ private : continue; } } - - double value2 = _pop[index].fitness()[1]; + + double value2 = _pop[index].fitness()[1]; if (traits::maximizing(1)) value2 = max1 - value2; - + // perform binary search using std::upper_bound, a log n operation for each member - std::vector::iterator it = + std::vector::iterator it = std::upper_bound(d.begin(), d.begin() + last_front, value2); - + unsigned front = unsigned(it - d.begin()); if (front == last_front) ++last_front; - + assert(it != d.end()); - + *it = value2; //update d fronts[front].push_back(index); // add it to the front - + prev_front = front; } - + // ok, and finally the niche penalty for (i = 0; i < fronts.size(); ++i) { - if (fronts[i].size() == 0) continue; + if (fronts[i].size() == 0) continue; // Now we have the indices to the current front in current_front, do the niching std::vector niche_count = niche_penalty(fronts[i], _pop); @@ -224,31 +227,31 @@ private : { value()[fronts[i][j]] = i + niche_count[j] / (max_niche + 1.); // divide by max_niche + 1 to ensure that this front does not overlap with the next } - + } - + // invert ranks to obtain a 'bigger is better' score rank_to_worth(); } - + class Sorter - { + { public: Sorter(const eoPop& _pop) : pop(_pop) {} bool operator()(unsigned i, unsigned j) const { typedef typename EOT::Fitness::fitness_traits traits; - + double diff = pop[i].fitness()[0] - pop[j].fitness()[0]; - + if (fabs(diff) < traits::tol()) { diff = pop[i].fitness()[1] - pop[j].fitness()[1]; if (fabs(diff) < traits::tol()) return false; - + if (traits::maximizing(1)) return diff > 0.; return diff < 0.; @@ -261,7 +264,7 @@ private : const eoPop& pop; }; - + void m_objectives(const eoPop& _pop) { unsigned i; @@ -348,7 +351,7 @@ private : rank_to_worth(); } - + void rank_to_worth() { // now all that's left to do is to transform lower rank into higher worth @@ -356,7 +359,7 @@ private : // but make sure it's an integer upper bound, so that all ranks inside the highest integer are the front max_fitness = ceil(max_fitness); - + for (unsigned i = 0; i < value().size(); ++i) { value()[i] = max_fitness - value()[i]; @@ -409,21 +412,26 @@ public : double nicheSize; }; -/** - Adapted from Deb, Agrawal, Pratab and Meyarivan: A Fast Elitist Non-Dominant Sorting Genetic Algorithm for MultiObjective Optimization: NSGA-II - KanGAL Report No. 200001 +/** @brief Fast Elitist Non-Dominant Sorting Genetic Algorithm - Note that this class does not do the sorting per se, but the sorting of it worth_std::vector will give the right order + Adapted from Deb, Agrawal, Pratab and Meyarivan: A Fast Elitist + Non-Dominant Sorting Genetic Algorithm for MultiObjective + Optimization: NSGA-II KanGAL Report No. 200001 - The crowding distance is calculated as the sum of the distances to the nearest neighbours. As we need to return the - penalty value, we have to invert that and invert it again in the base class, but such is life, sigh + Note that this class does not do the sorting per se, but the sorting + of it worth_std::vector will give the right order + + The crowding distance is calculated as the sum of the distances to + the nearest neighbours. As we need to return the penalty value, we + have to invert that and invert it again in the base class, but such + is life, sigh */ template class eoNDSorting_II : public eoNDSorting { - public: +public: - typedef std::pair double_index_pair; + typedef std::pair double_index_pair; class compare_nodes { @@ -441,7 +449,7 @@ class eoNDSorting_II : public eoNDSorting unsigned i; std::vector niche_count(_cf.size(), 0.); - + unsigned nObjectives = traits::nObjectives(); //_pop[_cf[0]].fitness().size(); for (unsigned o = 0; o < nObjectives; ++o) diff --git a/eo/src/eoOpContainer.h b/eo/src/eoOpContainer.h index 00a3addf..8f19e163 100644 --- a/eo/src/eoOpContainer.h +++ b/eo/src/eoOpContainer.h @@ -87,55 +87,57 @@ class eoOpContainer : public eoGenOp template class eoSequentialOp : public eoOpContainer { - public : - typedef unsigned position_type; +public: + + using eoOpContainer< EOT >::ops; + using eoOpContainer< EOT >::rates; + + typedef unsigned position_type; - void apply(eoPopulator& _pop) - { - position_type pos = _pop.tellp(); + void apply(eoPopulator& _pop) { + position_type pos = _pop.tellp(); + for (size_t i = 0; i < rates.size(); ++i) { + _pop.seekp(pos); + do { + if (eo::rng.flip(rates[i])) { + // try + // { + // apply it to all the guys in the todo std::list + (*ops[i])(_pop); + // } + // check for out of individuals and do nothing with that... + // catch(eoPopulator::OutOfIndividuals&) + // { + // std::cout << "Warning: not enough individuals to handle\n"; + // return ; + // } + } - for (size_t i = 0; i < rates.size(); ++i) - { - _pop.seekp(pos); - - do - { - if (eo::rng.flip(rates[i])) - { - // try - // { - // apply it to all the guys in the todo std::list - (*ops[i])(_pop); - // } - // check for out of individuals and do nothing with that... - // catch(eoPopulator::OutOfIndividuals&) - // { - // std::cout << "Warning: not enough individuals to handle\n"; - // return ; - // } - } - - if (!_pop.exhausted()) - ++_pop; + if (!_pop.exhausted()) + ++_pop; + } + while (!_pop.exhausted()); } - while (!_pop.exhausted()); - } - } - virtual std::string className() const {return "SequentialOp";} + } + virtual std::string className() const {return "SequentialOp";} - private : +private: - std::vector to_apply; - std::vector production; + std::vector to_apply; + std::vector production; }; + /** The proportional versions: easy! */ template class eoProportionalOp : public eoOpContainer { - public : +public: + + using eoOpContainer< EOT >::ops; + using eoOpContainer< EOT >::rates; void apply(eoPopulator& _pop) { diff --git a/eo/src/eoParetoRanking.h b/eo/src/eoParetoRanking.h index 60063fab..63e7298b 100644 --- a/eo/src/eoParetoRanking.h +++ b/eo/src/eoParetoRanking.h @@ -39,10 +39,13 @@ template class eoParetoRanking : public eoPerf2WorthCached { - public : +public: - eoParetoRanking(eoDominanceMap& _dominanceMap) : - eoPerf2WorthCached(), dominanceMap(_dominanceMap) {} + using eoParetoRanking< EOT>::value; + + eoParetoRanking(eoDominanceMap& _dominanceMap) + : eoPerf2WorthCached(), dominanceMap(_dominanceMap) + {} void calculate_worths(const eoPop& _pop) { diff --git a/eo/src/eoPerf2Worth.h b/eo/src/eoPerf2Worth.h index ec0df662..3e1a5657 100644 --- a/eo/src/eoPerf2Worth.h +++ b/eo/src/eoPerf2Worth.h @@ -35,20 +35,24 @@ #include #include -/** Base class to transform raw fitnesses into fitness for selection +/** @brief Base class to transform raw fitnesses into fitness for selection @see eoSelectFromWorth */ template class eoPerf2Worth : public eoUF&, void>, public eoValueParam > { - public: - eoPerf2Worth(std::string _description = "Worths"):eoValueParam >(std::vector(0), - _description) {} +public: - /** - Sort population according to worth, will keep the worths and fitness_cache in sync with the population. - */ + using eoPerf2Worth::value; + + /** @brief default constructor */ + eoPerf2Worth(std::string _description = "Worths") + : eoValueParam >(std::vector(0), _description) + {} + + /** Sort population according to worth, will keep the worths and + fitness_cache in sync with the population. */ virtual void sort_pop(eoPop& _pop) { // start with a std::vector of indices std::vector indices(_pop.size()); @@ -75,28 +79,28 @@ class eoPerf2Worth : public eoUF&, void>, public eoValueParam& _worths) : worths(_worths) {} - - bool operator()(unsigned a, unsigned b) const + /** helper class used to sort indices into populations/worths */ + class compare_worth { - return worths[b] < worths[a]; // sort in descending (!) order - } + public: - private : + compare_worth(const std::vector& _worths) : worths(_worths) {} - const std::vector& worths; - }; + bool operator()(unsigned a, unsigned b) const { + return worths[b] < worths[a]; // sort in descending (!) order + } - virtual void resize(eoPop& _pop, unsigned sz) - { - _pop.resize(sz); - value().resize(sz); - } + private: + + const std::vector& worths; + }; + + + + virtual void resize(eoPop& _pop, unsigned sz) { + _pop.resize(sz); + value().resize(sz); + }; }; @@ -106,8 +110,11 @@ Perf2Worth with fitness cache template class eoPerf2WorthCached : public eoPerf2Worth { - public: - eoPerf2WorthCached(std::string _description = "Worths") : eoPerf2Worth(_description) {} +public: + + using eoPerf2Worth::value; + + eoPerf2WorthCached(std::string _description = "Worths") : eoPerf2Worth(_description) {} /** @@ -164,7 +171,7 @@ class eoPerf2WorthCached : public eoPerf2Worth indices[i] = i; } - std::sort(indices.begin(), indices.end(), eoPerf2Worth::compare_worth(value())); + std::sort(indices.begin(), indices.end(), compare_worth(value())); eoPop tmp_pop; tmp_pop.resize(_pop.size()); @@ -216,22 +223,25 @@ class eoPerf2WorthCached : public eoPerf2Worth std::vector fitness_cache; }; -/** - A dummy perf2worth, just in case you need it -*/ + + +/** A dummy perf2worth, just in case you need it */ template class eoNoPerf2Worth : public eoPerf2Worth { - public: +public: + + using eoValueParam< EOT >::value; // default behaviour, just copy fitnesses - void operator()(const eoPop& _pop) - { - unsigned i; - value.resize(_pop.size()); - for (i = 0; i < _pop.size(); ++i) - value()[i]=_pop[i]; + void operator()(const eoPop& _pop) { + unsigned i; + value().resize(_pop.size()); + for (i = 0; i < _pop.size(); ++i) + value()[i]=_pop[i]; } }; + + #endif diff --git a/eo/src/eoPopulator.h b/eo/src/eoPopulator.h index 8c97c5ab..4a04c354 100644 --- a/eo/src/eoPopulator.h +++ b/eo/src/eoPopulator.h @@ -1,9 +1,9 @@ // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- //----------------------------------------------------------------------------- -// eoPopulator.h +// eoPopulator.h // (c) Maarten Keijzer and Marc Schoenauer, 2001 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -120,15 +120,15 @@ public : */ virtual const EOT& select() = 0; -protected : - eoPop& dest; - typename eoPop::iterator current; - const eoPop& src; +protected: + eoPop& dest; + typename eoPop::iterator current; + const eoPop& src; -private : - void get_next() - { - if (current == dest.end()) +private: + + void get_next() { + if(current == dest.end()) { // get new individual from derived class select() dest.push_back(select()); current = dest.end(); @@ -143,31 +143,34 @@ private : }; -/** SeqPopulator: an eoPopulator that sequentially goes through the population -is supposed to be used after a batch select of a whole bunch or genitors - */ +/** SeqPopulator: an eoPopulator that sequentially goes through the + population is supposed to be used after a batch select of a whole + bunch or genitors +*/ template class eoSeqPopulator : public eoPopulator { -public : +public: - eoSeqPopulator(const eoPop& _pop, eoPop& _dest) : - eoPopulator(_pop, _dest), current(0) {} + eoSeqPopulator(const eoPop& _pop, eoPop& _dest) : + eoPopulator(_pop, _dest), current(0) {} - /** the select method simply returns next individual in the src pop */ - const EOT& select(void) - { - if (current >= src.size()) - { - throw OutOfIndividuals(); - } + /** the select method simply returns next individual in the src pop */ + const EOT& select(void) { + if(current >= eoPopulator< EOT >::src.size()) { + throw OutOfIndividuals(); + } - const EOT& res = src[current++]; - return res; - } + const EOT& res = eoPopulator< EOT >::src[current++]; + return res; + } -private : - unsigned current; + +private: + + struct OutOfIndividuals {}; + + unsigned current; }; @@ -178,20 +181,22 @@ template class eoSelectivePopulator : public eoPopulator { public : - eoSelectivePopulator(const eoPop& _pop, eoPop& _dest, eoSelectOne& _sel) - : eoPopulator(_pop, _dest), sel(_sel) - { - sel.setup(_pop); + + using eoPopulator< EOT >::src; + + eoSelectivePopulator(const eoPop& _pop, eoPop& _dest, eoSelectOne& _sel) + : eoPopulator(_pop, _dest), sel(_sel) + { sel.setup(_pop); }; + + /** the select method actually selects one guy from the src pop */ + const EOT& select() { + return sel(src); } - /** the select method actually selects one guy from the src pop */ - const EOT& select() - { - return sel(src); - } -private : - eoSelectOne& sel; +private: + + eoSelectOne& sel; }; #endif diff --git a/eo/src/eoRanking.h b/eo/src/eoRanking.h index 3918cc53..3f06fd9f 100644 --- a/eo/src/eoRanking.h +++ b/eo/src/eoRanking.h @@ -38,6 +38,9 @@ template class eoRanking : public eoPerf2Worth // false: do not cache fitness { public: + + using eoRanking< EOT >::value; + /* Ctor: @param _p selective pressure (in (1,2] @param _e exponent (1 == linear) @@ -91,7 +94,7 @@ public: { int which = lookfor(rank[i], _pop); // value in in [0,1] - double tmp = ((double)(pSize-i))/pSize; + double tmp = ((double)(pSize-i))/pSize; // to the exponent, and back to [m,M] value()[which] = gamma*pow(tmp, exponent)+beta; } diff --git a/eo/src/eoScalarFitnessAssembled.h b/eo/src/eoScalarFitnessAssembled.h index 88b7da50..8eacf0b2 100644 --- a/eo/src/eoScalarFitnessAssembled.h +++ b/eo/src/eoScalarFitnessAssembled.h @@ -11,16 +11,16 @@ modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. - + This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - + You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - + Contact: todos@geneura.ugr.es, http://geneura.ugr.es Marc.Schoenauer@inria.fr mak@dhi.dk @@ -43,33 +43,33 @@ class eoScalarFitnessAssembledTraits{ public: - + typedef std::vector::size_type size_type; - static void setDescription( size_type _idx, std::string _descr ) { + static void setDescription( size_type _idx, std::string _descr ) { if ( _idx < TermDescriptions.size() ) - TermDescriptions[_idx] = _descr; + TermDescriptions[_idx] = _descr; else{ TermDescriptions.resize(_idx, "Unnamed variable" ); TermDescriptions[_idx] = _descr; } } - static std::string getDescription( size_type _idx) { + static std::string getDescription( size_type _idx) { if ( _idx < TermDescriptions.size() ) - return TermDescriptions[_idx ]; + return TermDescriptions[_idx ]; else return "Unnamed Variable"; } - - static void resize( size_type _n, const std::string& _descr) { - TermDescriptions.resize(_n, _descr); + + static void resize( size_type _n, const std::string& _descr) { + TermDescriptions.resize(_n, _descr); } - + static size_type size() { return TermDescriptions.size(); } static std::vector getDescriptionVector() { return TermDescriptions; } - + private: static std::vector TermDescriptions; }; @@ -80,7 +80,7 @@ private: maximizing (using less) or minimizing (using greater). - Stores all kinda different values met during fitness assembly, to be defined in eoEvalFunc. - It overrides operator<() to use the Compare template argument. - - Suitable constructors and assignments and casts are defined to work + - Suitable constructors and assignments and casts are defined to work with this quantity as if it were a ScalarType. - Global fitness value is stored as first element in the vector */ @@ -88,26 +88,32 @@ template class eoScalarFitnessAssembled : public std::vector { public: + + using std::vector< ScalarType >::empty; + using std::vector< ScalarType >::front; + using std::vector< ScalarType >::size; + + typedef typename std::vector baseVector; typedef typename baseVector::size_type size_type; // Basic constructors and assignments - eoScalarFitnessAssembled() + eoScalarFitnessAssembled() : baseVector( FitnessTraits::size() ), feasible(true), failed(false), msg("") {} - eoScalarFitnessAssembled( size_type _n, + eoScalarFitnessAssembled( size_type _n, const ScalarType& _val, const std::string& _descr="Unnamed variable" ) : baseVector(_n, _val), feasible(true), failed(false), msg("") - { + { if ( _n > FitnessTraits::size() ) FitnessTraits::resize(_n, _descr); } - - eoScalarFitnessAssembled( const eoScalarFitnessAssembled& other) + + eoScalarFitnessAssembled( const eoScalarFitnessAssembled& other) : baseVector( other ), feasible(other.feasible), failed(other.failed), @@ -121,27 +127,26 @@ public: msg = other.msg; return *this; } - + // Constructors and assignments to work with scalar type - eoScalarFitnessAssembled( const ScalarType& v ) + eoScalarFitnessAssembled( const ScalarType& v ) : baseVector( 1, v ), feasible(true), failed(false), msg("") {} - + eoScalarFitnessAssembled& operator=( const ScalarType& v ) { - - if ( empty() ) - push_back( v ); - else - front() = v; - - return *this; + + if( empty() ) + push_back( v ); + else + front() = v; + return *this; } - + //! Overload push_back() void push_back(const ScalarType& _val ){ baseVector::push_back( _val ); - if ( size() > FitnessTraits::size() ) + if ( size() > FitnessTraits::size() ) FitnessTraits::setDescription( size()-1, "Unnamed variable"); } @@ -156,46 +161,46 @@ public: baseVector::resize(_n, _val); FitnessTraits::resize(_n, _descr); } - + //! Set description - void setDescription( size_type _idx, std::string _descr ) { + void setDescription( size_type _idx, std::string _descr ) { FitnessTraits::setDescription( _idx, _descr ); } - + //! Get description std::string getDescription( size_type _idx ){ return FitnessTraits::getDescription( _idx ); } //! Get vector with descriptions std::vector getDescriptionVector() { return FitnessTraits::getDescriptionVector(); } - + //! Feasibility boolean /** - * Can be specified anywhere in fitness evaluation + * Can be specified anywhere in fitness evaluation * as an indicator if the individual is in some feasible range. */ bool feasible; - + //! Failed boolean /** * Can be specified anywhere in fitness evaluation * as an indicator if the evaluation of the individual failed */ bool failed; - + //! Message - /** + /** * Can be specified anywhere in fitness evaluation. * Typically used to store some sort of error messages, if evaluation of individual failed. */ std::string msg; - + // Scalar type access - operator ScalarType(void) const { + operator ScalarType(void) const { if ( empty() ) return 0.0; else - return front(); + return front(); } //! Print term values and descriptions @@ -205,11 +210,11 @@ public: } // Comparison, using less by default - bool operator<(const eoScalarFitnessAssembled& other) const{ + bool operator<(const eoScalarFitnessAssembled& other) const{ if ( empty() || other.empty() ) return false; else - return Compare()( front() , other.front() ); + return Compare()( front() , other.front() ); } // implementation of the other operators @@ -237,10 +242,10 @@ std::ostream& operator<<(std::ostream& os, const eoScalarFitnessAssembled>(std::istream& is, eoScalarFitnessAssembled> value; f[i] = value; } - + is >> f.feasible; is >> f.failed; - + return is; } diff --git a/eo/src/eoSelectFromWorth.h b/eo/src/eoSelectFromWorth.h index 2ccc9de8..4577b822 100644 --- a/eo/src/eoSelectFromWorth.h +++ b/eo/src/eoSelectFromWorth.h @@ -1,9 +1,9 @@ /** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- ----------------------------------------------------------------------------- - eoSelectFromWorth.h + eoSelectFromWorth.h (c) Maarten Keijzer, Marc Schoenauer, 2001 - + This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -33,9 +33,9 @@ #include //----------------------------------------------------------------------------- -/** selects one element from a population (is an eoSelectOne) -but the selection is based on a std::vector of Worth that is different -from the fitnesses (e.g. EO fitness is what Koza terms "raw fitness", +/** selects one element from a population (is an eoSelectOne) +but the selection is based on a std::vector of Worth that is different +from the fitnesses (e.g. EO fitness is what Koza terms "raw fitness", Worth is what the selection is based upon). see class eoPerf2Worth: an eoStat that transforms fitnesses into Worthes @@ -51,40 +51,36 @@ template class eoSelectFromWorth : public eoSelectOne { public: - /* Default ctor from an eoPerf2Worth object - */ - eoSelectFromWorth(eoPerf2Worth & _perf2Worth) : - perf2Worth(_perf2Worth) {} - /* setup the worthes */ - virtual void setup(const eoPop& _pop) - { - perf2Worth(_pop); + /* Default ctor from an eoPerf2Worth object */ + eoSelectFromWorth(eoPerf2Worth& _perf2Worth) + : perf2Worth(_perf2Worth) + {} + /* setup the worthes */ + virtual void setup(const eoPop& pop) { + perf2Worth(pop); #ifndef NDEBUG - fitness.resize(_pop.size()); - for (unsigned i = 0; i < _pop.size(); ++i) - { - fitness[i] = _pop[i].fitness(); - } + fitness.resize(pop.size()); + for (unsigned i = 0; i < pop.size(); ++i) { + fitness[i] = pop[i].fitness(); + } #endif - } + } + protected: - eoPerf2Worth & perf2Worth; + + eoPerf2Worth& perf2Worth; #ifndef NDEBUG - std::vector fitness; - void check_sync(unsigned index, const EOT& _eo) - { - if (fitness[index] != _eo.fitness()) - { - throw std::runtime_error("eoSelectFromWorth: fitnesses are not in sync"); + std::vector fitness; + void check_sync(unsigned index, const EOT& _eo) { + if (fitness[index] != _eo.fitness()) { + throw std::runtime_error("eoSelectFromWorth: fitnesses are not in sync"); + } } - } - #endif - }; @@ -95,36 +91,34 @@ template class eoDetTournamentWorthSelect : public eoSelectFromWorth { public: - typedef typename std::vector::iterator worthIterator; - /* Default ctor from an eoPerf2Worth object + tournament size - */ - eoDetTournamentWorthSelect(eoPerf2Worth &_perf2Worth, - unsigned _tSize) : - eoSelectFromWorth(_perf2Worth), tSize(_tSize) {} + using eoSelectFromWorth::perf2Worth; - /* Perform deterministic tournament on worthes - by calling the appropriate fn - see selectors.h - */ - virtual const EOT& operator()(const eoPop& _pop) - { - worthIterator it = deterministic_tournament( - perf2Worth.value().begin(), - perf2Worth.value().end(), tSize); + typedef typename std::vector::iterator worthIterator; - unsigned index = it - perf2Worth.value().begin(); + /* Default ctor from an eoPerf2Worth object + tournament size */ + eoDetTournamentWorthSelect(eoPerf2Worth& perf2Worth, + unsigned _tSize) + : eoSelectFromWorth(perf2Worth), tSize(_tSize) {} + /* Perform deterministic tournament on worthes by calling the + appropriate fn see selectors.h */ + virtual const EOT& operator()(const eoPop& pop) { + worthIterator it = deterministic_tournament(perf2Worth.value().begin(), + perf2Worth.value().end(), + tSize); + unsigned index = it - perf2Worth.value().begin(); #ifndef NDEBUG - // check whether the stuff is still in sync - check_sync(index, _pop[index]); + // check whether the stuff is still in sync + check_sync(index, pop[index]); #endif + return pop[index]; + } - return _pop[index]; - } private: - unsigned tSize; + + unsigned tSize; }; /** An instance of eoSelectPerf2Worth that does selection from the Worthes @@ -134,24 +128,25 @@ template class eoStochTournamentWorthSelect : public eoSelectFromWorth { public: - typedef typename std::vector::iterator worthIterator; - /* Default ctor from an eoPerf2Worth object + tournament rate - */ - eoStochTournamentWorthSelect(eoPerf2Worth &_perf2Worth, - double _tRate) : - eoSelectFromWorth(_perf2Worth), tRate(_tRate) {} + using eoSelectFromWorth::perf2Worth; + + typedef typename std::vector::iterator worthIterator; + + /* Default ctor from an eoPerf2Worth object + tournament rate */ + eoStochTournamentWorthSelect(eoPerf2Worth &_perf2Worth, double _tRate) + : eoSelectFromWorth(_perf2Worth), tRate(_tRate) + {} /* Perform stochastic tournament on worthes by calling the appropriate fn in selectors.h */ - virtual const EOT& operator()(const eoPop& _pop) - { - worthIterator it = stochastic_tournament( - perf2Worth.value().begin(), - perf2Worth.value().end(), tRate); + virtual const EOT& operator()(const eoPop& _pop) { + worthIterator it = stochastic_tournament(perf2Worth.value().begin(), + perf2Worth.value().end(), + tRate); - unsigned index = it - perf2Worth.value().begin(); + unsigned index = it - perf2Worth.value().begin(); #ifndef NDEBUG // check whether the stuff is still in sync @@ -172,12 +167,16 @@ template class eoRouletteWorthSelect : public eoSelectFromWorth { public: - typedef typename std::vector::iterator worthIterator; - /* Default ctor from an eoPerf2Worth object - */ - eoRouletteWorthSelect(eoPerf2Worth &_perf2Worth) : - eoSelectFromWorth(_perf2Worth) {} + using eoSelectFromWorth::perf2Worth; + + typedef typename std::vector::iterator worthIterator; + + + /* Default ctor from an eoPerf2Worth object */ + eoRouletteWorthSelect(eoPerf2Worth &_perf2Worth) + : eoSelectFromWorth(_perf2Worth) + {} /* We have to override the default behavior to compute the total * only once! @@ -195,18 +194,16 @@ public: by calling the appropriate fn see selectors.h */ - virtual const EOT& operator()(const eoPop& _pop) - { -// cout << "On affiche les worths\n"; -// for (unsigned i=0; -// i& _pop) { + // cout << "On affiche les worths\n"; + // for (unsigned i=0; + // i #include -/** Sharing is a perf2worth class that implements +/** Sharing is a perf2worth class that implements * Goldberg and Richardson's basic sharing */ @@ -70,7 +70,7 @@ }; -/** Sharing is a perf2worth class that implements +/** Sharing is a perf2worth class that implements * Goldberg and Richardson's basic sharing * see eoSharingSelect for how to use it * and test/t-eoSharing.cpp for a sample use of both @@ -78,10 +78,14 @@ template class eoSharing : public eoPerf2Worth { - public: +public: + + using eoSharing< EOT >::value; + + /* Ctor requires a distance - cannot have a default distance! */ - eoSharing(double _nicheSize, eoDistance & _dist) : eoPerf2Worth("Sharing"), - nicheSize(_nicheSize), + eoSharing(double _nicheSize, eoDistance & _dist) : eoPerf2Worth("Sharing"), + nicheSize(_nicheSize), dist(_dist) {} @@ -89,7 +93,7 @@ class eoSharing : public eoPerf2Worth */ void operator()(const eoPop& _pop) { - unsigned i, j, + unsigned i, j, pSize=_pop.size(); if (pSize <= 1) throw std::runtime_error("Apptempt to do sharing with population of size 1"); @@ -105,7 +109,7 @@ class eoSharing : public eoPerf2Worth for (j=0; jnicheSize ? 0 : 1-(d/nicheSize) ); } } @@ -123,7 +127,7 @@ class eoSharing : public eoPerf2Worth value()[i]=_pop[i].fitness()/sim[i]; } // private data of class eoSharing -private: +private: double nicheSize; eoDistance & dist; // specific distance }; diff --git a/eo/src/eoSurviveAndDie.h b/eo/src/eoSurviveAndDie.h index 1c4f766f..f99d646c 100644 --- a/eo/src/eoSurviveAndDie.h +++ b/eo/src/eoSurviveAndDie.h @@ -1,9 +1,9 @@ /** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- ----------------------------------------------------------------------------- - eoSurviveAndDie.h + eoSurviveAndDie.h (c) Maarten Keijzer, Marc Schoenauer, GeNeura Team, 2000 - + This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -37,8 +37,8 @@ //----------------------------------------------------------------------------- /** -eoSurviveAndDie: takes a population (first argument), -kills the ones that are to die, +eoSurviveAndDie: takes a population (first argument), +kills the ones that are to die, puts the ones that are to survive into the second argument removes them from the first pop argument @@ -54,32 +54,35 @@ class eoSurviveAndDie : public eoBF &, eoPop &, void> { public: eoSurviveAndDie(double _survive, double _die, bool _interpret_as_rate = true): - howmanySurvive(_survive, _interpret_as_rate), + howmanySurvive(_survive, _interpret_as_rate), howmanyDie(_die, _interpret_as_rate) {} protected: eoHowMany howmanySurvive; eoHowMany howmanyDie; - + }; -/** -an instance (theonly one as of today, Dec. 20, 2000) of an eoSurviveAndDie, -that does everything deterministically +/** An instance (theonly one as of today, Dec. 20, 2000) of an + eoSurviveAndDie, that does everything deterministically -used in eoDeterministicSaDReplacement + Used in eoDeterministicSaDReplacement. */ - template class eoDeterministicSurviveAndDie : public eoSurviveAndDie { public: - eoDeterministicSurviveAndDie(double _survive, double _die, - bool _interpret_as_rate = true): - eoSurviveAndDie(_survive, _die, _interpret_as_rate) + + using eoSurviveAndDie< EOT >::howmanyDie; + using eoSurviveAndDie< EOT >::howmanySurvive; + + /** constructor */ + eoDeterministicSurviveAndDie(double _survive, double _die, bool _interpret_as_rate = true) + : eoSurviveAndDie< EOT >(_survive, _die, _interpret_as_rate) {} + void operator()(eoPop & _pop, eoPop & _luckyGuys) { unsigned pSize = _pop.size(); @@ -88,7 +91,7 @@ public: if (nbSurvive) { _pop.nth_element(nbSurvive); - // copy best + // copy best _luckyGuys.resize(nbSurvive); std::copy(_pop.begin(), _pop.begin()+nbSurvive, _luckyGuys.begin()); // erase them from pop @@ -100,7 +103,7 @@ public: unsigned nbDie = std::min(howmanyDie(pSize), pSize-nbSurvive); if (nbDie > nbRemaining) throw std::logic_error("eoDeterministicSurviveAndDie: Too many to kill!\n"); - + if (!nbDie) { return; @@ -118,33 +121,33 @@ eoDeterministicSaDReplacement: replacement strategy that is just, in sequence saves best and kill worse from parents + saves best and kill worse from offspring + merge remaining (neither save nor killed) parents and offspring -+ reduce that merged population ++ reduce that merged population = returns reduced pop + best parents + best offspring -An obvious use is as strong elitist strategy, - i.e. preserving best parents, and reducing +An obvious use is as strong elitist strategy, + i.e. preserving best parents, and reducing (either offspring or parents+offspring) */ template class eoDeterministicSaDReplacement : public eoReplacement { public: - /** Constructor with reduce */ - eoDeterministicSaDReplacement(eoReduce& _reduceGlobal, - double _surviveParents, double _dieParents=0, + /** Constructor with reduce */ + eoDeterministicSaDReplacement(eoReduce& _reduceGlobal, + double _surviveParents, double _dieParents=0, double _surviveOffspring=0, double _dieOffspring=0, bool _interpret_as_rate = true ) : - reduceGlobal(_reduceGlobal), + reduceGlobal(_reduceGlobal), sAdParents(_surviveParents, _dieParents, _interpret_as_rate), sAdOffspring(_surviveOffspring, _dieOffspring, _interpret_as_rate) {} - /** Constructor with default truncate used as reduce */ + /** Constructor with default truncate used as reduce */ eoDeterministicSaDReplacement( - double _surviveParents, double _dieParents=0, + double _surviveParents, double _dieParents=0, double _surviveOffspring=0, double _dieOffspring=0, bool _interpret_as_rate = true ) : - reduceGlobal(truncate), + reduceGlobal(truncate), sAdParents(_surviveParents, _dieParents, _interpret_as_rate), sAdOffspring(_surviveOffspring, _dieOffspring, _interpret_as_rate) {} diff --git a/eo/src/eoVector.h b/eo/src/eoVector.h index 9211006c..b4ce1b9a 100644 --- a/eo/src/eoVector.h +++ b/eo/src/eoVector.h @@ -22,7 +22,7 @@ Marc.Schoenauer@polytechnique.fr mak@dhi.dk - CVS Info: $Date: 2003-03-18 16:57:17 $ $Header: /home/nojhan/dev/eodev/eodev_cvs/eo/src/eoVector.h,v 1.15 2003-03-18 16:57:17 maartenkeijzer Exp $ $Author: maartenkeijzer $ + CVS Info: $Date: 2004-12-23 15:29:06 $ $Header: /home/nojhan/dev/eodev/eodev_cvs/eo/src/eoVector.h,v 1.16 2004-12-23 15:29:06 kuepper Exp $ $Author: kuepper $ */ //----------------------------------------------------------------------------- @@ -39,20 +39,32 @@ Base class for fixed length chromosomes, just derives from EO and std::vector and redirects the smaller than operator to EO (fitness based comparison). GeneType must have the following methods: void ctor (needed for the std::vector<>), copy ctor, - - + + */ template class eoVector : public EO, public std::vector { - public : +public: + + using EO::invalidate; + using std::vector::operator[]; + using std::vector::begin; + using std::vector::end; + using std::vector::resize; + using std::vector::size; typedef GeneType AtomType; typedef std::vector ContainerType; + /** default constructor - eoVector(unsigned size = 0, GeneType value = GeneType()) : EO(), std::vector(size, value) - {} + @param size Length of vector (default is 0) + @param value Initial value of all elements (default is default value of type GeneType) + */ + eoVector(unsigned size = 0, GeneType value = GeneType()) + : EO(), std::vector(size, value) + {} /// copy ctor abstracting from the FitT template diff --git a/eo/src/es/eoEsFull.h b/eo/src/es/eoEsFull.h index 7c5b5faf..92e4ac0c 100644 --- a/eo/src/es/eoEsFull.h +++ b/eo/src/es/eoEsFull.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoEsFull.h // (c) GeNeura Team, 2000 - EEAAX 1999 - Maarten Keijzer 2000 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -39,7 +39,11 @@ rates and correlated mutations. template class eoEsFull : public eoVector { - public : +public: + + using eoEsFull< Fit >::size; + + typedef double Type; eoEsFull(void) : eoVector() {} diff --git a/eo/src/es/eoEsStdev.h b/eo/src/es/eoEsStdev.h index 277b2d90..5a3d031d 100644 --- a/eo/src/es/eoEsStdev.h +++ b/eo/src/es/eoEsStdev.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoEsStdev.h // (c) GeNeura Team, 2000 - EEAAX 1999 - Maarten Keijzer 2000 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -39,7 +39,9 @@ deviations. template class eoEsStdev : public eoVector { - public : +public: + + using eoEsStdev< Fit >::size; typedef double Type; diff --git a/eo/src/es/eoNormalMutation.h b/eo/src/es/eoNormalMutation.h index 3b9b4888..ba807b24 100644 --- a/eo/src/es/eoNormalMutation.h +++ b/eo/src/es/eoNormalMutation.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoNormalMutation.h // (c) EEAAX 2001 - Maarten Keijzer 2000 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -37,7 +37,7 @@ //----------------------------------------------------------------------------- /** Simple normal mutation of a std::vector of real values. - * The stDev is fixed - but it is passed ans stored as a reference, + * The stDev is fixed - but it is passed ans stored as a reference, * to enable dynamic mutations (see eoOenFithMutation below). * * As for the bounds, the values are here folded back into the bounds. @@ -68,7 +68,7 @@ template class eoNormalVecMutation: public eoMonOp */ eoNormalVecMutation(eoRealVectorBounds & _bounds, double _sigma, const double& _p_change = 1.0): - sigma(_bounds.size(), _sigma), bounds(_bounds), p_change(_p_change) + sigma(_bounds.size(), _sigma), bounds(_bounds), p_change(_p_change) { // scale to the range - if any for (unsigned i=0; i class eoNormalMutation: public eoMonOp +template class eoNormalMutation + : public eoMonOp { - public: +public: /** * (Default) Constructor. * The bounds are initialized with the global object that says: no bounds. @@ -173,11 +174,14 @@ private: * increase sigma if more than threshold (1/5 !) */ -template class eoOneFifthMutation : +template class eoOneFifthMutation : public eoNormalMutation, public eoUpdatable { public: - typedef typename EOT::Fitness Fitness; + + using eoNormalMutation< EOT >::Sigma; + + typedef typename EOT::Fitness Fitness; /** * (Default) Constructor. @@ -186,14 +190,14 @@ public: * @param _sigmaInit the initial value for uniform mutation * @param _windowSize the size of the window for statistics * @param _threshold the threshold (the 1/5 - 0.2) - * @param _updateFactor multiplicative update factor for sigma + * @param _updateFactor multiplicative update factor for sigma */ - eoOneFifthMutation(eoEvalFunc & _eval, double & _sigmaInit, + eoOneFifthMutation(eoEvalFunc & _eval, double & _sigmaInit, unsigned _windowSize = 10, double _updateFactor=0.83, - double _threshold=0.2): - eoNormalMutation(_sigmaInit), eval(_eval), - threshold(_threshold), updateFactor(_updateFactor), - nbMut(_windowSize, 0), nbSuccess(_windowSize, 0), genIndex(0) + double _threshold=0.2): + eoNormalMutation(_sigmaInit), eval(_eval), + threshold(_threshold), updateFactor(_updateFactor), + nbMut(_windowSize, 0), nbSuccess(_windowSize, 0), genIndex(0) { // minimal check if (updateFactor>=1) @@ -209,7 +213,7 @@ public: * * @param _eo The chromosome undergoing the mutation */ - bool operator()(EOT & _eo) + bool operator()(EOT & _eo) { if (_eo.invalid()) // due to some crossover??? eval(_eo); @@ -227,8 +231,8 @@ public: } return false; // because eval has reset the validity flag } - - /** the method that will be called every generation + + /** the method that will be called every generation * if the object is added to the checkpoint */ void update() @@ -255,12 +259,12 @@ public: nbMut[genIndex] = nbSuccess[genIndex] = 0; } - + private: eoEvalFunc & eval; double threshold; // 1/5 ! double updateFactor ; // the multiplicative factor - std::vector nbMut; // total number of mutations per gen + std::vector nbMut; // total number of mutations per gen std::vector nbSuccess; // number of successful mutations per gen unsigned genIndex ; // current index in std::vectors (circular) }; diff --git a/eo/src/ga/eoBit.h b/eo/src/ga/eoBit.h index 96383c02..fbe0b44a 100644 --- a/eo/src/ga/eoBit.h +++ b/eo/src/ga/eoBit.h @@ -20,9 +20,9 @@ Marc.Schoenauer@polytechnique.fr */ -/* MS, Nov. 23, 2000 +/* MS, Nov. 23, 2000 Added the calls to base class I/O routines that print the fitness - Left printing/reading of the size of the bitstring, + Left printing/reading of the size of the bitstring, for backward compatibility, and as it is a general practice in EO MS, Feb. 7, 2001 @@ -54,7 +54,11 @@ */ template class eoBit: public eoVector { - public: +public: + + using eoVector< FitT, bool >::begin; + using eoVector< FitT, bool >::end; + using eoVector< FitT, bool >::size; /** * (Default) Constructor. @@ -104,3 +108,9 @@ template class eoBit: public eoVector //----------------------------------------------------------------------------- #endif //eoBit_h + + +// Local Variables: +// mode: C++ +// c-file-style: "Stroustrup" +// End: diff --git a/eo/src/ga/eoPBILAdditive.h b/eo/src/ga/eoPBILAdditive.h index 29b3fdd6..bea4c506 100644 --- a/eo/src/ga/eoPBILAdditive.h +++ b/eo/src/ga/eoPBILAdditive.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoPBILAdditive.h // (c) Marc Schoenauer, Maarten Keijzer, 2001 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -30,10 +30,10 @@ #include /** - * Distribution Class for PBIL algorithm + * Distribution Class for PBIL algorithm * (Population-Based Incremental Learning, Baluja and Caruana 96) * - * This class implements an extended update rule: + * This class implements an extended update rule: * in the original paper, the authors used * * p(i)(t+1) = (1-LR)*p(i)(t) + LR*best(i) @@ -46,12 +46,12 @@ template class eoPBILAdditive : public eoDistribUpdater { public: - /** Ctor with parameters + /** Ctor with parameters * using the default values is equivalent to using eoPBILOrg */ - eoPBILAdditive(double _LRBest, unsigned _nbBest = 1, + eoPBILAdditive(double _LRBest, unsigned _nbBest = 1, double _tolerance=0.0, - double _LRWorst = 0.0, unsigned _nbWorst = 0 ) : + double _LRWorst = 0.0, unsigned _nbWorst = 0 ) : maxBound(1.0-_tolerance), minBound(_tolerance), LR(0.0), nbBest(_nbBest), nbWorst(_nbWorst) { @@ -75,7 +75,7 @@ public: } /** Update the distribution from the current population */ - virtual void operator()(eoDistribution & _distrib, eoPop& _pop) + virtual void operator()(eoDistribution & _distrib, eoPop& _pop) { eoPBILDistrib& distrib = dynamic_cast&>(_distrib); @@ -83,7 +83,7 @@ public: unsigned i, popSize=_pop.size(); std::vector result; - _pop.sort(result); // is it necessary to sort the whole population? + _pop.sort(result); // is it necessary to sort the whole population? // but I'm soooooooo lazy !!! for (unsigned g=0; g class eoParseTree : public EO, public parse_tree { -public : +public: + + using eoParseTree::back; + using eoParseTree::ebegin; + using eoParseTree::eend; + using eoParseTree::size; + typedef typename parse_tree::subtree Subtree; - /* For Compatibility with the intel C++ compiler for Linux 5.x */ - typedef Node reference; - typedef const reference const_reference; - - + /* For Compatibility with the intel C++ compiler for Linux 5.x */ + typedef Node reference; + typedef const reference const_reference; - /** * Default Constructor */ eoParseTree(void) {} - /** + + /** * Copy Constructor * @param tree The tree to copy */ eoParseTree(const parse_tree& tree) : parse_tree(tree) {} - + // eoParseTree(const eoParseTree& tree) : parse_tree(tree) {} /** * To prune me to a certain size @@ -90,7 +94,7 @@ public : while (size() > _size) { - back() = operator[](size()-2); + back() = operator[](size()-2); } } @@ -98,8 +102,8 @@ public : * To read me from a stream * @param is The std::istream */ - - eoParseTree(std::istream& is) : EO(), parse_tree() + + eoParseTree(std::istream& is) : EO(), parse_tree() { readFrom(is); } @@ -120,21 +124,21 @@ public : std::copy(ebegin(), eend(), std::ostream_iterator(os, " ")); } - + /** * To read me from a stream * @param is The std::istream */ - void readFrom(std::istream& is) + void readFrom(std::istream& is) { - - + + EO::readFrom(is); unsigned sz; is >> sz; - + std::vector v(sz); unsigned i; @@ -147,19 +151,19 @@ public : } parse_tree tmp(v.begin(), v.end()); swap(tmp); - + /* * old code which caused problems for paradisEO * * this can be removed once it has proved itself EO::readFrom(is); - - // even older code + + // even older code FType fit; is >> fit; fitness(fit); - + std::copy(std::istream_iterator(is), std::istream_iterator(), back_inserter(*this)); */ diff --git a/eo/src/gp/parse_tree.h b/eo/src/gp/parse_tree.h index eece67ed..e18d00c9 100644 --- a/eo/src/gp/parse_tree.h +++ b/eo/src/gp/parse_tree.h @@ -3,14 +3,14 @@ /** - * Parse_tree and subtree classes - * (c) copyright Maarten Keijzer 1999, 2000 + * Parse_tree and subtree classes + * (c) copyright Maarten Keijzer 1999, 2000 - * Permission to copy, use, modify, sell and distribute this software is granted provided + * Permission to copy, use, modify, sell and distribute this software is granted provided * this copyright notice appears in all copies. This software is provided "as is" without * express or implied warranty, and with no claim as to its suitability for * any purpose. - + * Permission to modify the code and to distribute modified code is granted, * provided the above notices as well as this one are retained, and a notice that the code was * modified is included with the above copyright notice. @@ -22,31 +22,31 @@ class Node (your node in the tree) must have the following implemented: ****** Arity ****** - + int arity(void) const - Note: the default constructor of a Node should provide a + Note: the default constructor of a Node should provide a Node with arity 0! ****** Evaluation ****** A parse_tree is evaluated through one of it's apply() members: - - 1) parse_tree::apply(RetVal) - - is the simplest evaluation, it will call - + + 1) parse_tree::apply(RetVal) + + is the simplest evaluation, it will call + RetVal Node::operator()(RetVal, subtree::const_iterator) - - (Unfortunately the first RetVal argument is mandatory (although you + + (Unfortunately the first RetVal argument is mandatory (although you might not need it. This is because MSVC does not support member template - functions properly. If it cannot deduce the template arguments (as is - the case in templatizing over return value) you are not allowed to + functions properly. If it cannot deduce the template arguments (as is + the case in templatizing over return value) you are not allowed to specify them. calling tree.apply() would result in a syntax error. That is why you have to call tree.apply(double()) instead.) - 2) parse_tree::apply(RetVal v, It values) + 2) parse_tree::apply(RetVal v, It values) will call: @@ -61,7 +61,7 @@ will call: RetVal Node::operator()(RetVal, subtree<... , It values, It2 moreValues) - + although I do not see the immediate use of this, however... 4) parse_tree::apply(RetVal, It values, It2 args, It3 adfs) @@ -70,10 +70,10 @@ RetVal Node::operator()(subtree<... , It values, It2 args, It3 adfs) - can be useful for implementing adfs. + can be useful for implementing adfs. - - In general it is a good idea to leave the specifics of the + + In general it is a good idea to leave the specifics of the arguments open so that different ways of evaluation remain possible. Implement the simplest eval as: @@ -85,24 +85,24 @@ A parse_tree has two template arguments: the Node and the ReturnValue produced by evaluating the node. The structure of the tree is defined through a subtree class that has the same two template arguments. - + The nodes are stored in a tree like : node4 / \ node3 node2 / \ - node1 node0 + node1 node0 where nodes 2 and 4 have arity 2 and nodes 0,1 and 3 arity 0 (terminals) The nodes are subtrees, containing the structure of the tree, together with its size and depth. They contain a Node, the user defined template argument. To access these nodes from a subtree, use operator-> or operator*. - - The numbers behind the nodes define a reverse-polish or postfix + + The numbers behind the nodes define a reverse-polish or postfix traversel through the tree. The parse_tree defines iterators - on the tree such that + on the tree such that tree.begin() points at the subtree at node0 and tree.back() returns the subtree at node4, the complete tree @@ -134,9 +134,9 @@ std::vector vec(tree.size()); copy(tree.ebegin(), tree.eend(), vec.begin()); - You can also copy it to an std::ostream_iterator with this + You can also copy it to an std::ostream_iterator with this technique, given that your Node implements an appropriate - operator<<. Reinitializing a tree with the std::vector is also + operator<<. Reinitializing a tree with the std::vector is also simple: tree.clear(); @@ -158,7 +158,7 @@ #ifdef _MSC_VER #pragma warning(disable : 4786) // disable this nagging warning about the limitations of the mirkosoft debugger #endif - + namespace gp_parse_tree { @@ -166,7 +166,7 @@ namespace gp_parse_tree /// This ones defined because gcc does not always implement namespaces template -inline void do_the_swap(T& a, T& b) +inline void do_the_swap(T& a, T& b) { T tmp = a; a = b; @@ -181,7 +181,7 @@ template class parse_tree class subtree { -/* +/* a bit nasty way to use a pool allocator (which would otherwise use slooow new and delete) TODO: use the std::allocator interface */ @@ -198,42 +198,42 @@ public : typedef subtree* iterator; typedef const subtree* const_iterator; - + /* Constructors, assignments */ - subtree(void) : content(node_allocator.allocate()), args(0), parent(0), _cumulative_size(0), _depth(0), _size(1) + subtree(void) : content(node_allocator.allocate()), args(0), parent(0), _cumulative_size(0), _depth(0), _size(1) {} - subtree(const subtree& s) - : content(node_allocator.allocate()), - args(0), - parent(0), - _cumulative_size(1), - _depth(1), - _size(1) + subtree(const subtree& s) + : content(node_allocator.allocate()), + args(0), + parent(0), + _cumulative_size(1), + _depth(1), + _size(1) { copy(s); - } + } subtree(const T& t) : content(node_allocator.allocate()), args(0), parent(0), _cumulative_size(0), _depth(0), _size(1) - { copy(t); } + { copy(t); } template - subtree(It b, It e) : content(node_allocator.allocate()), args(0), parent(0), _cumulative_size(0), _depth(0), _size(1) + subtree(It b, It e) : content(node_allocator.allocate()), args(0), parent(0), _cumulative_size(0), _depth(0), _size(1) { // initialize in prefix order for efficiency reasons init(b, --e); } virtual ~subtree(void) { tree_allocator.deallocate(args, arity()); node_allocator.deallocate(content); } - - subtree& operator=(const subtree& s) - { + + subtree& operator=(const subtree& s) + { if (s.get_root() == get_root()) { // from the same tree, maybe a child. Don't take any chances subtree anotherS = s; return copy(anotherS); } - copy(s); + copy(s); updateAfterInsert(); return *this; } @@ -242,9 +242,9 @@ public : /* Access to the nodes */ - T& operator*(void) { return *content; } + T& operator*(void) { return *content; } const T& operator*(void) const { return *content; } - T* operator->(void) { return content; } + T* operator->(void) { return content; } const T* operator->(void) const { return content; } /* Equality, inequality check, Node needs to implement operator== */ @@ -274,11 +274,11 @@ public : /* Evaluation with an increasing amount of user defined arguments */ template void apply(RetVal& v) const { (*content)(v, begin()); } - + template - void apply(RetVal& v, It values) const - { - (*content)(v, begin(), values); + void apply(RetVal& v, It values) const + { + (*content)(v, begin(), values); } template @@ -289,11 +289,11 @@ public : /* template - void apply(RetVal& v, It values, It2 moreValues) const + void apply(RetVal& v, It values, It2 moreValues) const { (*content)(v, begin(), values, moreValues); } template - void apply(RetVal& v, It values, It2 moreValues, It3 evenMoreValues) const + void apply(RetVal& v, It values, It2 moreValues, It3 evenMoreValues) const { (*content)(v, begin(), values, moreValues, evenMoreValues); } */ @@ -310,7 +310,7 @@ public : args[i].find_nodes(result, p); } } - + template void find_nodes(std::vector& result, Pred& p) const { @@ -324,7 +324,7 @@ public : args[i].find_nodes(result, p); } } - + /* Iterators */ iterator begin(void) { return args; } @@ -339,21 +339,21 @@ public : /* Some statistics */ size_t size(void) const { return _size; } - + size_t cumulative_size(void) const { return _cumulative_size; } size_t depth(void) const { return _depth; } - + const subtree& select_cumulative(size_t which) const { return imp_select_cumulative(which); } - subtree& select_cumulative(size_t which) + subtree& select_cumulative(size_t which) { return const_cast(imp_select_cumulative(which)); } subtree& get_node(size_t which) { return const_cast(imp_get_node(which));} const subtree& get_node(size_t which) const { return imp_get_node(which); } - + subtree* get_parent(void) { return parent; } const subtree* get_parent(void) const { return parent; } @@ -364,7 +364,7 @@ public : { do_the_swap(content, y.content); do_the_swap(args, y.args); - + adopt(); y.adopt(); @@ -381,7 +381,7 @@ protected : virtual void updateAfterInsert(void) { _depth = 0; - _size = 1; + _size = 1; _cumulative_size = 0; for (iterator it = begin(); it != end(); ++it) @@ -411,7 +411,7 @@ private : return args[i].imp_select_cumulative(which); which -= args[i]._cumulative_size; } - + return *this; // error! } @@ -419,7 +419,7 @@ private : { if (which == size() - 1) return *this; - + for (int i = arity() - 1; i >= 0; --i) { unsigned c_size = args[i].size(); @@ -442,9 +442,9 @@ private : subtree& copy(const subtree& s) { int old_arity = arity(); - + int new_arity = s.arity(); - + if (new_arity != old_arity) { tree_allocator.deallocate(args, old_arity); @@ -455,7 +455,7 @@ private : switch(new_arity) { case 3 : args[2].copy(s.args[2]); args[2].parent = this; // no break! - case 2 : args[1].copy(s.args[1]); args[1].parent = this; + case 2 : args[1].copy(s.args[1]); args[1].parent = this; case 1 : args[0].copy(s.args[0]); args[0].parent = this; case 0 : break; default : @@ -467,8 +467,8 @@ private : } } } - - *content = *s.content; + + *content = *s.content; _size = s._size; _depth = s._depth; _cumulative_size = s._cumulative_size; @@ -479,24 +479,24 @@ private : subtree& copy(const T& t) { int oldArity = arity(); - + if (content != &t) *content = t; else - oldArity = -1; - + oldArity = -1; + int ar = arity(); - + if (ar != oldArity) { if (oldArity != -1) tree_allocator.deallocate(args, oldArity); args = tree_allocator.allocate(ar); - + //if (ar > 0) // args = new subtree [ar]; - //else + //else // args = 0; } @@ -521,7 +521,7 @@ private : } } } - + } void adopt(void) @@ -539,7 +539,7 @@ private : it->parent = this; } } - } + } } template @@ -582,22 +582,22 @@ private : parse_tree(void) : _root(), pushed() {} parse_tree(const parse_tree& org) : _root(org._root), pushed(org.pushed) { } parse_tree(const subtree& sub) : _root(sub), pushed() { } - + template parse_tree(It b, It e) : _root(b, e), pushed() {} - + virtual ~parse_tree(void) {} parse_tree& operator=(const parse_tree& org) { return copy(org); } - parse_tree& operator=(const subtree& sub) + parse_tree& operator=(const subtree& sub) { return copy(sub); } - + /* Equality and inequality */ bool operator==(const parse_tree& other) const { return _root == other._root; } - + bool operator !=(const parse_tree& other) const { return !operator==(other); } @@ -610,13 +610,13 @@ private : /* Evaluation (application), with an increasing number of user defined arguments */ template - void apply(RetVal& v) const + void apply(RetVal& v) const { _root.apply(v); } template - void apply(RetVal& v, It varValues) const + void apply(RetVal& v, It varValues) const { _root.apply(v, varValues); } - + template void apply_mem_func(RetVal& v, It misc, void (T::* f)(RetVal&, typename subtree::iterator, It)) { @@ -624,11 +624,11 @@ private : } //template - // void apply(RetVal& v, It varValues, It2 moreValues) const + // void apply(RetVal& v, It varValues, It2 moreValues) const // { _root.apply(v, varValues, moreValues); } - + //template - // void apply(RetVal& v, It varValues, It2 moreValues, It3 evenMoreValues) const + // void apply(RetVal& v, It varValues, It2 moreValues, It3 evenMoreValues) const // { _root.apply(v, varValues, moreValues, evenMoreValues); } template @@ -636,13 +636,13 @@ private : { _root.find_nodes(result, p); } - + template void find_nodes(std::vector& result, Pred& p) const { _root.find_nodes(p); } - + /* Customized Swap */ void swap(parse_tree& other) { @@ -655,8 +655,8 @@ private : class base_iterator { public : - - base_iterator() {} + + base_iterator() {} base_iterator(subtree* n) { node = n; } base_iterator& operator=(const base_iterator& org) @@ -670,7 +670,7 @@ private : base_iterator operator+(size_t n) const { base_iterator tmp = *this; - + for(;n != 0; --n) { ++tmp; @@ -678,7 +678,7 @@ private : return tmp; } - + base_iterator& operator++(void) { subtree* parent = node->get_parent(); @@ -702,7 +702,7 @@ private : { node = &(--it)->get_node(0); } - + return *this; } @@ -719,13 +719,16 @@ private : class iterator : public base_iterator { - public : - typedef std::forward_iterator_tag iterator_category; - typedef subtree value_type; - typedef size_t distance_type; - typedef size_t difference_type; - typedef subtree* pointer; - typedef subtree& reference; + public: + + using base_iterator::node; + + typedef std::forward_iterator_tag iterator_category; + typedef subtree value_type; + typedef size_t distance_type; + typedef size_t difference_type; + typedef subtree* pointer; + typedef subtree& reference; iterator() : base_iterator() {} iterator(subtree* n): base_iterator(n) {} @@ -736,15 +739,20 @@ private : subtree* operator->(void) { return node; } }; + + class embedded_iterator : public base_iterator { - public : - typedef std::forward_iterator_tag iterator_category; - typedef T value_type; - typedef size_t distance_type; - typedef size_t difference_type; - typedef T* pointer; - typedef T& reference; + public: + + using base_iterator::node; + + typedef std::forward_iterator_tag iterator_category; + typedef T value_type; + typedef size_t distance_type; + typedef size_t difference_type; + typedef T* pointer; + typedef T& reference; embedded_iterator() : base_iterator() {} embedded_iterator(subtree* n): base_iterator(n) {} @@ -757,7 +765,8 @@ private : class base_const_iterator { - public : + public: + base_const_iterator() {} base_const_iterator(const subtree* n) { node = n; } @@ -802,19 +811,22 @@ private : } protected : - + const subtree* node; }; class const_iterator : public base_const_iterator { - public : - typedef std::forward_iterator_tag iterator_category; - typedef const subtree value_type; - typedef size_t distance_type; - typedef size_t difference_type; - typedef const subtree* pointer; - typedef const subtree& reference; + public: + + using base_iterator::node; + + typedef std::forward_iterator_tag iterator_category; + typedef const subtree value_type; + typedef size_t distance_type; + typedef size_t difference_type; + typedef const subtree* pointer; + typedef const subtree& reference; const_iterator() : base_const_iterator() {} const_iterator(const subtree* n): base_const_iterator(n) {} @@ -827,7 +839,10 @@ private : class embedded_const_iterator : public base_const_iterator { - public : + public: + + using base_const_iterator::node; + typedef std::forward_iterator_tag iterator_category; typedef const T value_type; typedef size_t distance_type; @@ -843,7 +858,7 @@ private : embedded_const_iterator operator+(size_t n) const { embedded_const_iterator tmp = *this; - + for(;n != 0; --n) { ++tmp; @@ -858,12 +873,12 @@ private : /* Iterator access */ - iterator begin(void) { return iterator(&operator[](0)); } + iterator begin(void) { return iterator(&operator[](0)); } const_iterator begin(void) const { return const_iterator(&operator[](0)); } iterator end(void) { return iterator(0); } const_iterator end(void) const { return const_iterator(0);} - embedded_iterator ebegin(void) { return embedded_iterator(&operator[](0)); } + embedded_iterator ebegin(void) { return embedded_iterator(&operator[](0)); } embedded_const_iterator ebegin(void) const { return embedded_const_iterator(&operator[](0)); } embedded_iterator eend(void) { return embedded_iterator(0); } embedded_const_iterator eend(void) const { return embedded_const_iterator(0);} @@ -885,12 +900,12 @@ private : { if (!empty()) pushed.push_back(_root); - + _root = t; for (typename subtree::iterator it = _root.begin(); it != _root.end(); it++) { - *it = pushed.back(); + *it = pushed.back(); pushed.pop_back(); } @@ -902,7 +917,7 @@ private : const subtree& back(void) const { return _root; } subtree& root(void) { return _root; } const subtree& root(void) const { return _root; } - + subtree& front(void) { return _root[0]; } const subtree& front(void) const { return _root[0]; } @@ -917,13 +932,13 @@ private : { return get_cumulative(i); } private : - + parse_tree& copy(const parse_tree& org) - { - _root = org._root; - pushed = org.pushed; - - return *this; + { + _root = org._root; + pushed = org.pushed; + + return *this; } parse_tree& copy(const subtree& sub) @@ -939,25 +954,25 @@ private : namespace std { // for use with stlport on MSVC -template inline +template inline std::forward_iterator_tag iterator_category(typename gp_parse_tree::parse_tree::embedded_iterator) { return std::forward_iterator_tag(); } -template inline +template inline ptrdiff_t* distance_type(typename gp_parse_tree::parse_tree::embedded_iterator) { return 0; } -template inline +template inline std::forward_iterator_tag iterator_category(typename gp_parse_tree::parse_tree::iterator) { return std::forward_iterator_tag(); } -template inline +template inline ptrdiff_t* distance_type(typename gp_parse_tree::parse_tree::iterator) { return 0; diff --git a/eo/src/other/eoExternalEO.h b/eo/src/other/eoExternalEO.h index 80380670..e2e2b2da 100644 --- a/eo/src/other/eoExternalEO.h +++ b/eo/src/other/eoExternalEO.h @@ -2,10 +2,10 @@ ----------------------------------------------------------------------------- eoExternalEO.h - Definition of an object that allows an external struct to be inserted in EO + Definition of an object that allows an external struct to be inserted in EO (c) Maarten Keijzer (mkeijzer@mad.scientist.com) and GeNeura Team, 1999, 2000 - + This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -28,7 +28,7 @@ #include // EO -/** +/** * Definition of an object that allows an external struct * to be inserted in EO. This struct or class can be of any * form, the only thing this class does is attach a fitness @@ -40,28 +40,33 @@ class eoExternalEO : public EO, virtual public External { public : - eoExternalEO(void) : EO(), External() {} + eoExternalEO(void) + : EO(), External() + {} - /** - Init externalEo with the struct itself and set fitness to zero - */ - eoExternalEO(const External& ext) : EO(), External(ext) {} - eoExternalEO(std::istream& is) : EO(), External(ext) { readFrom(is); } + /** Init externalEo with the struct itself and set fitness to zero */ + eoExternalEO(const External& ext) + : EO(), External(ext) + {} + + eoExternalEO(std::istream& is, const External& ext) + : EO(), External(ext) + { readFrom(is); } /** * Read object, the external struct needs to have an operator>> defined */ - virtual void readFrom(std::istream& _is) - { + virtual void readFrom(std::istream& _is) + { EO::readFrom(_is); _is >> static_cast(*this); } - + /** * Write object. Called printOn since it prints the object _on_ a stream. * @param _os A std::ostream. */ - virtual void printOn(std::ostream& _os) const + virtual void printOn(std::ostream& _os) const { EO::printOn(_os); _os << static_cast(*this); diff --git a/eo/src/other/eoString.h b/eo/src/other/eoString.h index 58f8c40d..e2aee758 100644 --- a/eo/src/other/eoString.h +++ b/eo/src/other/eoString.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoString.h // (c) GeNeura Team, 1998 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -26,7 +26,8 @@ #define _eoString_H // STL libraries -#include +#include +#include #include @@ -38,13 +39,14 @@ /** Adaptor that turns an STL std::string into an EO */ template -class eoString: public EO, public std::string +class eoString: public EO, public std::string { public: - typedef char Type; - typedef char AtomType; - typedef std::string ContainerType; + typedef char Type; + typedef char AtomType; + typedef std::string ContainerType; + /// Canonical part of the objects: several ctors, copy ctor, dtor and assignment operator //@{ @@ -58,7 +60,7 @@ public: EO::printOn(os); os << ' '; - os << size() << ' ' << substr() << endl; + os << size() << ' ' << substr() << std::endl; } @@ -66,12 +68,12 @@ public: readFrom and printOn are directly inherited from eo1d */ //@{ - /** Inherited from eoObject + /** Inherited from eoObject @see eoObject */ virtual std::string className() const {return "eoString";}; //@} - + }; diff --git a/eo/src/utils/eoAssembledFitnessStat.h b/eo/src/utils/eoAssembledFitnessStat.h index c44bb7b4..1b973c4b 100644 --- a/eo/src/utils/eoAssembledFitnessStat.h +++ b/eo/src/utils/eoAssembledFitnessStat.h @@ -38,25 +38,29 @@ /** Average fitness values of a population, where the fitness is - of type eoScalarAssembledFitness. Specify in the constructor, + of type eoScalarAssembledFitness. Specify in the constructor, for which fitness term (index) the average should be evaluated. Only values of object where the failed boolean = false is set are counted. */ -template +template class eoAssembledFitnessAverageStat : public eoStat { public : - - typedef typename EOT::Fitness Fitness; - - eoAssembledFitnessAverageStat(unsigned _whichTerm=0, std::string _description = "Average Fitness") - : eoStat(Fitness(), _description), whichFitnessTerm(_whichTerm) {} - - virtual void operator()(const eoPop& _pop){ - - if ( whichFitnessTerm >= _pop[0].fitness().size() ) - throw std::logic_error("Fitness term requested out of range"); - + + using eoAssembledFitnessAverageStat< EOT >::value; + + typedef typename EOT::Fitness Fitness; + + + eoAssembledFitnessAverageStat(unsigned _whichTerm=0, std::string _description = "Average Fitness") + : eoStat(Fitness(), _description), whichFitnessTerm(_whichTerm) + {} + + + virtual void operator()(const eoPop& _pop) { + if( whichFitnessTerm >= _pop[0].fitness().size() ) + throw std::logic_error("Fitness term requested out of range"); + double result =0.0; unsigned count = 0; for (typename eoPop::const_iterator it = _pop.begin(); it != _pop.end(); ++it){ @@ -68,7 +72,7 @@ public : value() = result / (double) count; } - + private: // Store an index of the fitness term to be evaluated in eoScalarFitnessAssembled unsigned whichFitnessTerm; @@ -76,29 +80,33 @@ private: /** Fitness values of best individuum in a population, where the fitness is - of type eoScalarAssembledFitness. Specify in the constructor, + of type eoScalarAssembledFitness. Specify in the constructor, for which fitness term (index) the value should be evaluated. */ -template +template class eoAssembledFitnessBestStat : public eoStat { -public : - typedef typename EOT::Fitness Fitness; - - eoAssembledFitnessBestStat(unsigned _whichTerm=0, std::string _description = "Best Fitness") - : eoStat(Fitness(), _description), whichFitnessTerm(_whichTerm) {} - - virtual void operator()(const eoPop& _pop){ - - if ( whichFitnessTerm >= _pop[0].fitness().size() ) - throw std::logic_error("Fitness term requested out of range"); +public: + + using eoAssembledFitnessBestStat< EOT >::value; + + typedef typename EOT::Fitness Fitness; + + eoAssembledFitnessBestStat(unsigned _whichTerm=0, std::string _description = "Best Fitness") + : eoStat(Fitness(), _description), whichFitnessTerm(_whichTerm) + {} + + virtual void operator()(const eoPop& _pop) { + if( whichFitnessTerm >= _pop[0].fitness().size() ) + throw std::logic_error("Fitness term requested out of range"); + + value() = _pop.best_element().fitness()[whichFitnessTerm]; + } - value() = _pop.best_element().fitness()[whichFitnessTerm]; - } - private: - // Store an index of the fitness term to be evaluated in eoScalarFitnessAssembled - unsigned whichFitnessTerm; + + // Store an index of the fitness term to be evaluated in eoScalarFitnessAssembled + unsigned whichFitnessTerm; }; #endif diff --git a/eo/src/utils/eoFDCStat.h b/eo/src/utils/eoFDCStat.h index 05964885..5de19187 100644 --- a/eo/src/utils/eoFDCStat.h +++ b/eo/src/utils/eoFDCStat.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoFDCStat.h // (c) Marc Schoenauer, Maarten Keijzer and GeNeura Team, 2000, 2001 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -38,9 +38,11 @@ so they can be snapshot by some eoGnuplotSnapshot ... template class eoFDCStat : public eoStat { -public : - /** Ctor without the optimum - */ +public: + + using eoFDCStat < EOT>::value; + + /** Ctor without the optimum */ eoFDCStat(eoDistance & _dist, std::string _description = "FDC") : eoStat(0, _description), dist(_dist), boolOpt(false) {} diff --git a/eo/src/utils/eoMOFitnessStat.h b/eo/src/utils/eoMOFitnessStat.h index dd77740f..4d473374 100644 --- a/eo/src/utils/eoMOFitnessStat.h +++ b/eo/src/utils/eoMOFitnessStat.h @@ -36,6 +36,9 @@ template class eoFitnessStat : public eoSortedStat > { public : + + using eoFitnessStat< EOT, FitT >::value; + eoFitnessStat(std::string _description = "AllFitnesses") : eoSortedStat >(std::vector(0), _description) {} @@ -62,7 +65,10 @@ class eoMOFitnessStat : public eoSortedStat > #endif { -public : +public: + + using eoMOFitnessStat< EOT, PartFitT >::value; + /** Ctor: say what component you want */ eoMOFitnessStat(unsigned _objective, std::string _description = "MO-Fitness") : diff --git a/eo/src/utils/eoPopStat.h b/eo/src/utils/eoPopStat.h index 983c8c1c..a4d1117b 100644 --- a/eo/src/utils/eoPopStat.h +++ b/eo/src/utils/eoPopStat.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoPopStat.h // (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2001 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -43,25 +43,28 @@ that can be used to dump to the screen /** Thanks to MS/VC++, eoParam mechanism is unable to handle std::vectors of stats. -This snippet is a workaround: +This snippet is a workaround: This class will "print" a whole population into a std::string - that you can later send to any stream This is the plain version - see eoPopString for the Sorted version -Note: this Stat should probably be used only within eoStdOutMonitor, and not +Note: this Stat should probably be used only within eoStdOutMonitor, and not inside an eoFileMonitor, as the eoState construct will work much better there. */ template class eoPopStat : public eoStat { -public : - /** default Ctor, void std::string by default, as it appears +public: + + using eoPopStat< EOT>::value; + + /** default Ctor, void std::string by default, as it appears on the description line once at beginning of evolution. and is meaningless there. _howMany defaults to 0, that is, the whole population*/ - eoPopStat(unsigned _howMany = 0, std::string _desc ="") + eoPopStat(unsigned _howMany = 0, std::string _desc ="") : eoStat("", _desc), combien( _howMany) {} - + /** Fills the value() of the eoParam with the dump of the population. Adds a \n before so it does not get mixed up with the rest of the stats that are written by the monitor it is probably used from. @@ -73,9 +76,9 @@ void operator()(const eoPop& _pop) unsigned howmany=combien?combien:_pop.size(); for (unsigned i = 0; i < howmany; ++i) { - std::ostringstream os; + std::ostringstream os; os << _pop[i] << std::endl; - + // paranoid: value() += os.str(); } @@ -91,7 +94,7 @@ void operator()(const eoPop& _pop) { std::ostrstream os(buffer, 1022); // leave space for emergency terminate os << _pop[i] << std::endl << std::ends; - + // paranoid: buffer[1022] = '\0'; value() += buffer; @@ -104,40 +107,45 @@ private: }; /** Thanks to MS/VC++, eoParam mechanism is unable to handle std::vectors of stats. -This snippet is a workaround: +This snippet is a workaround: This class will "print" a whole population into a std::string - that you can later send to any stream This is the Sorted version - see eoPopString for the plain version -Note: this Stat should probably be used only within eoStdOutMonitor, and not +Note: this Stat should probably be used only within eoStdOutMonitor, and not inside an eoFileMonitor, as the eoState construct will work much better there. */ template class eoSortedPopStat : public eoSortedStat { -public : - /** default Ctor, void std::string by default, as it appears - * on the description line once at beginning of evolution. and - * is meaningless there _howMany defaults to 0, that is, the whole - * population - */ - eoSortedPopStat(unsigned _howMany = 0, std::string _desc ="") : - eoSortedStat("", _desc) , combien( _howMany) {} - - /** Fills the value() of the eoParam with the dump of the population. - Adds a \n before so it does not get mixed up with the rest of the stats - that are written by the monitor it is probably used from. - */ +public: + + using eoSortedPopStat< EOT>::value; + + /** default Ctor, void std::string by default, as it appears on + the description line once at beginning of evolution. and is + meaningless there _howMany defaults to 0, that is, the whole + population + */ + eoSortedPopStat(unsigned _howMany = 0, std::string _desc ="") + : eoSortedStat("", _desc) , combien( _howMany) + {} + + /** Fills the value() of the eoParam with the dump of the + population. Adds a \n before so it does not get mixed up with + the rest of the stats that are written by the monitor it is + probably used from. + */ #ifdef HAVE_SSTREAM - void operator()(const std::vector& _pop) - { - value() = ""; // empty + void operator()(const std::vector& _pop) + { + value() = ""; // empty unsigned howMany=combien?combien:_pop.size(); for (unsigned i = 0; i < howMany; ++i) { - std::ostringstream os; + std::ostringstream os; os << *_pop[i] << std::endl; - + // paranoid: value() += os.str(); } @@ -146,13 +154,13 @@ public : void operator()(const std::vector& _pop) { char buffer[1023]; // about one K of space per member - value() = ""; // empty + value() = ""; // empty unsigned howMany=combien?combien:_pop.size(); for (unsigned i = 0; i < howMany; ++i) { std::ostrstream os(buffer, 1022); // leave space for emergency terminate os << *_pop[i] << std::endl << std::ends; - + // paranoid: buffer[1022] = '\0'; value() += buffer; diff --git a/eo/src/utils/eoScalarFitnessStat.h b/eo/src/utils/eoScalarFitnessStat.h index 83495833..06051cb1 100644 --- a/eo/src/utils/eoScalarFitnessStat.h +++ b/eo/src/utils/eoScalarFitnessStat.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoScalarFitnessStat.h // (c) Marc Schoenauer, Maarten Keijzer and GeNeura Team, 2000, 2001 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -36,13 +36,16 @@ template class eoScalarFitnessStat : public eoSortedStat > { -public : - eoScalarFitnessStat(std::string _description = "FitnessES", - eoRealVectorBounds & _bounds = eoDummyVectorNoBounds) : - eoSortedStat >(std::vector(0), _description) , +public: + + using eoScalarFitnessStat< EOT, FitT >::value; + + eoScalarFitnessStat(std::string _description = "FitnessES", + eoRealVectorBounds & _bounds = eoDummyVectorNoBounds) : + eoSortedStat >(std::vector(0), _description) , range(*_bounds[0]) {} - + virtual void operator()(const std::vector& _popPters) { value().resize(_popPters.size()); diff --git a/eo/src/utils/eoStat.h b/eo/src/utils/eoStat.h index 6a69f71d..b511f327 100644 --- a/eo/src/utils/eoStat.h +++ b/eo/src/utils/eoStat.h @@ -36,8 +36,8 @@ /** Base class for all statistics that need to be calculated - over the (unsorted) population - (I guess it is not really necessary? MS. + over the (unsorted) population + (I guess it is not really necessary? MS. Depstd::ends, there might be reasons to have a stat that is not an eoValueParam, but maybe I'm just kidding myself, MK) */ @@ -57,11 +57,18 @@ public: template class eoStat : public eoValueParam, public eoStatBase { -public : - eoStat(T _value, std::string _description) : eoValueParam(_value, _description) {} - virtual std::string className(void) const { return "eoStat"; } +public: + + eoStat(T _value, std::string _description) + : eoValueParam(_value, _description) + {} + + virtual std::string className(void) const + { return "eoStat"; } }; + + /** Base class for statistics calculated over a sorted snapshot of the population */ @@ -87,12 +94,12 @@ public : }; /** - Average fitness of a population. Fitness can be: + Average fitness of a population. Fitness can be: - double - - eoMinimizingFitness or eoMaximizingFitness + - eoMinimizingFitness or eoMaximizingFitness - eoParetoFitness: The average of each objective is evaluated. - + ( For eoScalarFitnessAssembled user eoAssembledFitnessStat classes.) */ #ifdef _MSC_VER @@ -102,9 +109,12 @@ template class eoAverageStat : public eoStat::value; + typedef typename EOT::Fitness Fitness; - eoAverageStat(std::string _description = "Average Fitness") + eoAverageStat(std::string _description = "Average Fitness") : eoStat(Fitness(), _description) {} static Fitness sumFitness(double _sum, const EOT& _eot){ @@ -114,15 +124,15 @@ public : eoAverageStat(double _value, std::string _desc) : eoStat(_value, _desc) {} - virtual void operator()(const eoPop& _pop){ + virtual void operator()(const eoPop& _pop){ doit(_pop, Fitness()); // specializations for scalar and std::vector } virtual std::string className(void) const { return "eoAverageStat"; } private : - - // Specialization for pareto fitness + + // Specialization for pareto fitness template void doit(const eoPop& _pop, eoParetoFitness) { @@ -139,7 +149,7 @@ private : value()[o] /= _pop.size(); } } - + // Default behavior template void doit(const eoPop& _pop, T) @@ -158,10 +168,16 @@ template class eoSecondMomentStats : public eoStat > { public : + + using eoSecondMomentStats< EOT >::value; + typedef typename EOT::Fitness fitness_type; - + typedef std::pair SquarePair; - eoSecondMomentStats(std::string _description = "Average & Stdev") : eoStat(std::make_pair(0.0,0.0), _description) {} + + eoSecondMomentStats(std::string _description = "Average & Stdev") + : eoStat(std::make_pair(0.0,0.0), _description) + {} static SquarePair sumOfSquares(SquarePair _sq, const EOT& _eo) { @@ -187,7 +203,7 @@ public : /** The n_th element fitness in the population (see eoBestFitnessStat) */ -#ifdef _MSC_VER +#ifdef _MSC_VER template class eoNthElementFitnessStat : public eoSortedStat #else @@ -196,9 +212,11 @@ class eoNthElementFitnessStat : public eoSortedStat #endif { public : + using eoNthElementFitnessStat< EOT >::value; + typedef typename EOT::Fitness Fitness; - eoNthElementFitnessStat(unsigned _whichElement, std::string _description = "nth element fitness") + eoNthElementFitnessStat(unsigned _whichElement, std::string _description = "nth element fitness") : eoSortedStat(Fitness(), _description), whichElement(_whichElement) {} virtual void operator()(const std::vector& _pop) @@ -211,7 +229,7 @@ public : virtual std::string className(void) const { return "eoNthElementFitnessStat"; } private : - + struct CmpFitness { CmpFitness(unsigned _whichElement, bool _maxim) : whichElement(_whichElement), maxim(_maxim) {} @@ -246,7 +264,7 @@ private : value()[o] = (*nth)->fitness()[o]; } } - + // for everything else template void doit(const std::vector& _pop, T) @@ -263,7 +281,7 @@ private : But then again, if another stat needs sorted fitness anyway, getting the best out would be very fast. MK - 09/01/03 - + template class eoBestFitnessStat : public eoStat { @@ -282,9 +300,9 @@ public : */ /** - Best fitness of a population. Fitness can be: + Best fitness of a population. Fitness can be: - double - - eoMinimizingFitness or eoMaximizingFitness + - eoMinimizingFitness or eoMaximizingFitness - eoParetoFitness: ( For eoScalarFitnessAssembled look at eoAssembledFitnessStat ) @@ -298,17 +316,23 @@ template class eoBestFitnessStat : public eoStat #endif { -public : +public: + + using eoBestFitnessStat< EOT >::value; + typedef typename EOT::Fitness Fitness; - eoBestFitnessStat(std::string _description = "Best ") - : eoStat(Fitness(), _description) {} - - void operator()(const eoPop& _pop){ - doit(_pop, Fitness() ); // specializations for scalar and std::vector + eoBestFitnessStat(std::string _description = "Best ") + : eoStat(Fitness(), _description) + {} + + void operator()(const eoPop& _pop) { + doit(_pop, Fitness() ); // specializations for scalar and std::vector } - virtual std::string className(void) const { return "eoBestFitnessStat"; } + virtual std::string className(void) const { return "eoBestFitnessStat"; } + + private : struct CmpFitness @@ -340,7 +364,7 @@ private : value()[o] = it->fitness()[o]; } } - + // default template void doit(const eoPop& _pop, T) @@ -353,8 +377,13 @@ private : template class eoDistanceStat : public eoStat { -public : - eoDistanceStat(std::string _name = "distance") : eoStat(0.0, _name) {} +public: + + using eoDistanceStat< EOT >::value; + + eoDistanceStat(std::string _name = "distance") + : eoStat(0.0, _name) + {} template double distance(T a, T b) @@ -405,7 +434,7 @@ public : virtual void operator()(const eoPop& _pop) { SquarePair result = std::accumulate(pop.begin(), pop.end(), std::make_pair(0.0, 0.0), eoSecondMomentStats::sumOfSquares); - + double n = pop.size(); value() = sqrt( (result.second - (result.first / n)) / (n - 1.0)); // stdev } diff --git a/eo/src/utils/eoUpdater.h b/eo/src/utils/eoUpdater.h index 490d0831..c031bb24 100644 --- a/eo/src/utils/eoUpdater.h +++ b/eo/src/utils/eoUpdater.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoUpdater.h // (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2000 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -48,7 +48,7 @@ public: */ template class eoIncrementor : public eoUpdater -{public : +{public : /** Default Ctor - requires a reference to the thing to increment */ eoIncrementor(T& _counter, T _stepsize = 1) : counter(_counter), stepsize(_stepsize) {} @@ -70,23 +70,26 @@ private: template class eoIncrementorParam : public eoUpdater, public eoValueParam { -public : +public: + + using eoIncrementorParam< T >::value; + /** Default Ctor : a name and optionally an increment*/ - eoIncrementorParam( std::string _name, T _stepsize = 1) : + eoIncrementorParam( std::string _name, T _stepsize = 1) : eoValueParam(T(0), _name), stepsize(_stepsize) {} - - /** Ctor with a name and non-zero initial value + + /** Ctor with a name and non-zero initial value * and mandatory stepSize to remove ambiguity */ - eoIncrementorParam( std::string _name, T _countValue, T _stepsize) : + eoIncrementorParam( std::string _name, T _countValue, T _stepsize) : eoValueParam(_countValue, _name), stepsize(_stepsize) {} /** Simply increments */ virtual void operator()() { - value() += stepsize; + value() += stepsize; } - + virtual std::string className(void) const { return "eoIncrementorParam"; } private: @@ -101,7 +104,7 @@ private: class eoTimedStateSaver : public eoUpdater { public : - eoTimedStateSaver(time_t _interval, const eoState& _state, std::string _prefix = "state", std::string _extension = "sav") : state(_state), + eoTimedStateSaver(time_t _interval, const eoState& _state, std::string _prefix = "state", std::string _extension = "sav") : state(_state), interval(_interval), last_time(time(0)), first_time(time(0)), prefix(_prefix), extension(_extension) {} @@ -124,12 +127,12 @@ private : class eoCountedStateSaver : public eoUpdater { public : - eoCountedStateSaver(unsigned _interval, const eoState& _state, std::string _prefix, bool _saveOnLastCall, std::string _extension = "sav", unsigned _counter = 0) - : state(_state), interval(_interval), counter(_counter), + eoCountedStateSaver(unsigned _interval, const eoState& _state, std::string _prefix, bool _saveOnLastCall, std::string _extension = "sav", unsigned _counter = 0) + : state(_state), interval(_interval), counter(_counter), saveOnLastCall(_saveOnLastCall), prefix(_prefix), extension(_extension) {} - eoCountedStateSaver(unsigned _interval, const eoState& _state, std::string _prefix = "state", std::string _extension = "sav", unsigned _counter = 0) + eoCountedStateSaver(unsigned _interval, const eoState& _state, std::string _prefix = "state", std::string _extension = "sav", unsigned _counter = 0) : state(_state), interval(_interval), counter(_counter), saveOnLastCall(true), prefix(_prefix), extension(_extension) {} @@ -145,7 +148,7 @@ private : const unsigned interval; unsigned counter; bool saveOnLastCall; - + const std::string prefix; const std::string extension; }; diff --git a/eo/src/utils/selectors.h b/eo/src/utils/selectors.h index f12dd771..2114a458 100644 --- a/eo/src/utils/selectors.h +++ b/eo/src/utils/selectors.h @@ -9,7 +9,7 @@ template const EOT& select(const eoPop& pop, params, eoRng& gen = rng); - + template EOT& select(eoPop& pop, params, eoRng& gen = rng); @@ -17,7 +17,7 @@ and stochastic_tournament (at the moment). (c) Maarten Keijzer (mak@dhi.dk) and GeNeura Team, 1999, 2000 - + This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -50,32 +50,32 @@ template bool minimizing_fitness() { EOT eo1; // Assuming people don't do anything fancy in the default constructor! - EOT eo2; + EOT eo2; - /* Dear user, when the two line below do not compile you are most + /* Dear user, when the two line below do not compile you are most likely not working with scalar fitness values. In that case we're sorry but you cannot use lottery or roulette_wheel selection... */ #ifdef _MSC_VER - eo1.fitness( EOT::Fitness(0.0) ); - eo2.fitness( EOT::Fitness(1.0) ); + eo1.fitness( EOT::Fitness(0.0) ); + eo2.fitness( EOT::Fitness(1.0) ); #else - eo1.fitness( typename EOT::Fitness(0.0) ); // tried to cast it to an EOT::Fitness, but for some reason GNU barfs on this - eo2.fitness( typename EOT::Fitness(1.0) ); + eo1.fitness( typename EOT::Fitness(0.0) ); // tried to cast it to an EOT::Fitness, but for some reason GNU barfs on this + eo2.fitness( typename EOT::Fitness(1.0) ); #endif - + return eo2 < eo1; // check whether we have a minimizing fitness }; -inline double scale_fitness(const std::pair& _minmax, double _value) +inline double scale_fitness(const std::pair& _minmax, double _value) { if (_minmax.first == _minmax.second) { return 0.0; // no differences in fitness, population converged! } // else - + return (_value - _minmax.first) / (_minmax.second - _minmax.first); } @@ -104,6 +104,8 @@ double sum_fitness(const eoPop& _pop) template double sum_fitness(const eoPop& _pop, std::pair& _minmax) { + double rawTotal, scaledTotal; + typename eoPop::const_iterator it = _pop.begin(); _minmax.first = it->fitness(); @@ -112,13 +114,13 @@ double sum_fitness(const eoPop& _pop, std::pair& _minmax) for(; it != _pop.end(); ++it) { double v = static_cast(it->fitness()); - + _minmax.first = std::min(_minmax.first, v); - _minmax.second = max(_minmax.second, v); - + _minmax.second = std::max(_minmax.second, v); + rawTotal += v; } - + if (minimizing_fitness()) { std::swap(_minmax.first, _minmax.second); @@ -129,10 +131,12 @@ double sum_fitness(const eoPop& _pop, std::pair& _minmax) // unfortunately a second loop is neccessary to scale the fitness for (it = _pop.begin(); it != _pop.end(); ++it) { - double v = scale_fitness(static_cast(it->fitness())); + double v = scale_fitness(_minmax, static_cast(it->fitness())); scaledTotal += v; } + + return scaledTotal; } template @@ -143,14 +147,14 @@ It roulette_wheel(It _begin, It _end, double total, eoRng& _gen = rng) if (roulette == 0.0) // covers the case where total==0.0 return _begin + _gen.random(_end - _begin); // uniform choice - + It i = _begin; - + while (roulette > 0.0) { roulette -= static_cast(*(i++)); } - + return --i; } @@ -158,43 +162,43 @@ template const EOT& roulette_wheel(const eoPop& _pop, double total, eoRng& _gen = rng) { float roulette = _gen.uniform(total); - + if (roulette == 0.0) // covers the case where total==0.0 return _pop[_gen.random(_pop.size())]; // uniform choice - + typename eoPop::const_iterator i = _pop.begin(); - + while (roulette > 0.0) { roulette -= static_cast((i++)->fitness()); } - + return *--i; -} +} template EOT& roulette_wheel(eoPop& _pop, double total, eoRng& _gen = rng) { float roulette = _gen.uniform(total); - + if (roulette == 0.0) // covers the case where total==0.0 return _pop[_gen.random(_pop.size())]; // uniform choice - + typename eoPop::iterator i = _pop.begin(); - + while (roulette > 0.0) { roulette -= static_cast((i++)->fitness()); } - + return *--i; -} +} template It deterministic_tournament(It _begin, It _end, unsigned _t_size, eoRng& _gen = rng) { - It best = _begin + _gen.random(_end - _begin); - + It best = _begin + _gen.random(_end - _begin); + for (unsigned i = 0; i < _t_size - 1; ++i) { It competitor = _begin + _gen.random(_end - _begin); @@ -223,8 +227,8 @@ EOT& deterministic_tournament(eoPop& _pop, unsigned _t_size, eoRng& _gen = template It inverse_deterministic_tournament(It _begin, It _end, unsigned _t_size, eoRng& _gen = rng) { - It worst = _begin + _gen.random(_end - _begin); - + It worst = _begin + _gen.random(_end - _begin); + for (unsigned i = 1; i < _t_size; ++i) { It competitor = _begin + _gen.random(_end - _begin); @@ -257,27 +261,27 @@ EOT& inverse_deterministic_tournament(eoPop& _pop, unsigned _t_size, eoRng& } template -It stochastic_tournament(It _begin, It _end, double _t_rate, eoRng& _gen = rng) +It stochastic_tournament(It _begin, It _end, double _t_rate, eoRng& _gen = rng) { It i1 = _begin + _gen.random(_end - _begin); It i2 = _begin + _gen.random(_end - _begin); bool return_better = _gen.flip(_t_rate); - if (*i1 < *i2) + if (*i1 < *i2) { if (return_better) return i2; // else return i1; } - else + else { if (return_better) return i1; // else } // else - + return i2; } @@ -294,27 +298,27 @@ EOT& stochastic_tournament(eoPop& _pop, double _t_rate, eoRng& _gen = rng) } template -It inverse_stochastic_tournament(It _begin, It _end, double _t_rate, eoRng& _gen = rng) +It inverse_stochastic_tournament(It _begin, It _end, double _t_rate, eoRng& _gen = rng) { It i1 = _begin + _gen.random(_end - _begin); It i2 = _begin + _gen.random(_end - _begin); bool return_worse = _gen.flip(_t_rate); - if (*i1 < *i2) + if (*i1 < *i2) { if (return_worse) return i1; // else return i2; } - else + else { if (return_worse) return i2; // else } // else - + return i1; } diff --git a/eo/test/t-MGE1bit.cpp b/eo/test/t-MGE1bit.cpp index 3e1da98a..f50b9de4 100644 --- a/eo/test/t-MGE1bit.cpp +++ b/eo/test/t-MGE1bit.cpp @@ -29,25 +29,25 @@ int main() unsigned i; eoBooleanGenerator gen; - // the populations: - eoPop pop; + // the populations: + eoPop pop; // Evaluation - RoyalRoad rr( 8 ); + RoyalRoad rr( 8 ); eoEvalFuncCounter eval( rr ); - eoInitVirus1bit random(CHROM_SIZE, gen); + eoInitVirus1bit random(CHROM_SIZE, gen); for (i = 0; i < POP_SIZE; ++i) { Chrom chrom; random(chrom); eval(chrom); pop.push_back(chrom); } - + std::cout << "population:" << std::endl; for (i = 0; i < pop.size(); ++i) std::cout << "\t" << pop[i] << " " << pop[i].fitness() << std::endl; - + // selection eoStochTournamentSelect lottery(0.9 ); @@ -62,14 +62,14 @@ int main() propSel.add(vf, 0.05); propSel.add(vt, 0.05); propSel.add(xover, 0.1); - + // Replace a single one eoCommaReplacement replace; // Terminators eoGenContinue continuator1(10); eoFitContinue continuator2(CHROM_SIZE); - eoCombinedContinue continuator(continuator1, continuator2); + eoCombinedContinue continuator(continuator1, continuator2); eoCheckPoint checkpoint(continuator); eoStdoutMonitor monitor; checkpoint.add(monitor); @@ -83,22 +83,26 @@ int main() eoEasyEA ea(checkpoint, eval, breeder, replace); // evolution - try - { + try { ea(pop); - } - catch (std::exception& e) - { - std::cout << "exception: " << e.what() << std::endl;; + } catch (std::exception& e) { + std::cerr << "exception: " << e.what() << std::endl;; exit(EXIT_FAILURE); } - + std::cout << "pop" << std::endl; for (i = 0; i < pop.size(); ++i) - std::cout << "\t" << pop[i] << " " << pop[i].fitness() << std::endl; + std::cout << "\t" << pop[i] << " " << pop[i].fitness() << std::endl; std::cout << "\n --> Number of Evaluations = " << eval.getValue() << std::endl; - return 0; + return EXIT_SUCCESS; } //----------------------------------------------------------------------------- + + + +// Local Variables: +// mode: C++ +// c-file-style: "Stroustrup" +// End: diff --git a/eo/test/t-eoPareto.cpp b/eo/test/t-eoPareto.cpp index e9a290b6..be61e71d 100644 --- a/eo/test/t-eoPareto.cpp +++ b/eo/test/t-eoPareto.cpp @@ -79,17 +79,27 @@ class Init : public eoInit } }; -// Trying out an elitist non-dominated sorted replacement scheme +/** @brief An elitist non-dominated sorted replacement scheme. + +Trying out an elitist non-dominated sorted replacement scheme. +*/ template class eoNDPlusReplacement : public eoReplacement { public: - eoNDPlusReplacement(eoPerf2Worth& _perf2worth) : perf2worth(_perf2worth) {} - struct WorthPair : public pair - { - bool operator<(const WorthPair& other) const { return other.first < first; } - }; + // using eoNDPlusReplacement< EOT, WorthT >::first; + + eoNDPlusReplacement(eoPerf2Worth& _perf2worth) + : perf2worth(_perf2worth) + {} + + struct WorthPair : public pair + { + bool operator<(const WorthPair& other) const + { return other.first < this->first; } + }; + void operator()(eoPop& _parents, eoPop& _offspring) { @@ -106,7 +116,7 @@ public: } private : - eoPerf2Worth& perf2worth; + eoPerf2Worth& perf2worth; }; template @@ -232,3 +242,9 @@ int main(int argc, char* argv[]) } } + + +// Local Variables: +// mode: C++ +// c-file-style: "Stroustrup" +// End: