Changed some files for compatibility with MSVC 2003 and 2005

This commit is contained in:
jeggermo 2006-11-20 13:25:46 +00:00
commit 219e9bd648
7 changed files with 890 additions and 876 deletions

View file

@ -1,291 +1,292 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// make_checkpoint.h // make_checkpoint.h
// (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2000 // (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2000
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version. version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es Contact: todos@geneura.ugr.es, http://geneura.ugr.es
Marc.Schoenauer@polytechnique.fr Marc.Schoenauer@polytechnique.fr
mkeijzer@dhi.dk mkeijzer@dhi.dk
*/ */
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#ifndef _make_checkpoint_h #ifndef _make_checkpoint_h
#define _make_checkpoint_h #define _make_checkpoint_h
#include <eoScalarFitness.h> #include <eoScalarFitness.h>
#include <utils/selectors.h> // for minimizing_fitness() #include <utils/selectors.h> // for minimizing_fitness()
#include <EO.h> #include <EO.h>
#include <eoEvalFuncCounter.h> #include <eoEvalFuncCounter.h>
#include <utils/checkpointing> #include <utils/checkpointing>
// at the moment, in utils/make_help.cpp // at the moment, in utils/make_help.cpp
// this should become some eoUtils.cpp with corresponding eoUtils.h // this should become some eoUtils.cpp with corresponding eoUtils.h
bool testDirRes(std::string _dirName, bool _erase); bool testDirRes(std::string _dirName, bool _erase);
/////////////////// The checkpoint and other I/O ////////////// /////////////////// The checkpoint and other I/O //////////////
template <class EOT> template <class EOT>
eoCheckPoint<EOT>& do_make_checkpoint(eoParser& _parser, eoState& _state, eoEvalFuncCounter<EOT>& _eval, eoContinue<EOT>& _continue) eoCheckPoint<EOT>& do_make_checkpoint(eoParser& _parser, eoState& _state, eoEvalFuncCounter<EOT>& _eval, eoContinue<EOT>& _continue)
{ {
// first, create a checkpoint from the eoContinue // first, create a checkpoint from the eoContinue
eoCheckPoint<EOT> *checkpoint = new eoCheckPoint<EOT>(_continue); eoCheckPoint<EOT> *checkpoint = new eoCheckPoint<EOT>(_continue);
_state.storeFunctor(checkpoint); _state.storeFunctor(checkpoint);
/////////////////// ///////////////////
// Counters // Counters
////////////////// //////////////////
// is nb Eval to be used as counter? // is nb Eval to be used as counter?
eoValueParam<bool>& useEvalParam = _parser.createParam(true, "useEval", "Use nb of eval. as counter (vs nb of gen.)", '\0', "Output"); eoValueParam<bool>& useEvalParam = _parser.createParam(true, "useEval", "Use nb of eval. as counter (vs nb of gen.)", '\0', "Output");
eoValueParam<bool>& useTimeParam = _parser.createParam(true, "useTime", "Display time (s) every generation", '\0', "Output"); eoValueParam<bool>& useTimeParam = _parser.createParam(true, "useTime", "Display time (s) every generation", '\0', "Output");
// if we want the time, we need an eoTimeCounter // if we want the time, we need an eoTimeCounter
eoTimeCounter * tCounter = NULL; eoTimeCounter * tCounter = NULL;
// Create anyway a generation-counter // Create anyway a generation-counter
// Recent change (03/2002): it is now an eoIncrementorParam, both // Recent change (03/2002): it is now an eoIncrementorParam, both
// a parameter AND updater so you can store it into the eoState // a parameter AND updater so you can store it into the eoState
eoIncrementorParam<unsigned> *generationCounter = new eoIncrementorParam<unsigned>("Gen."); eoIncrementorParam<unsigned> *generationCounter = new eoIncrementorParam<unsigned>("Gen.");
// store it in the state // store it in the state
_state.storeFunctor(generationCounter); _state.storeFunctor(generationCounter);
// And add it to the checkpoint, // And add it to the checkpoint,
checkpoint->add(*generationCounter); checkpoint->add(*generationCounter);
// dir for DISK output // dir for DISK output
eoValueParam<std::string>& dirNameParam = _parser.createParam(std::string("Res"), "resDir", "Directory to store DISK outputs", '\0', "Output - Disk"); eoValueParam<std::string>& dirNameParam = _parser.createParam(std::string("Res"), "resDir", "Directory to store DISK outputs", '\0', "Output - Disk");
// shoudl we empty it if exists // shoudl we empty it if exists
eoValueParam<bool>& eraseParam = _parser.createParam(true, "eraseDir", "erase files in dirName if any", '\0', "Output - Disk"); eoValueParam<bool>& eraseParam = _parser.createParam(true, "eraseDir", "erase files in dirName if any", '\0', "Output - Disk");
bool dirOK = false; // not tested yet bool dirOK = false; // not tested yet
///////////////////////////////////////// /////////////////////////////////////////
// now some statistics on the population: // now some statistics on the population:
///////////////////////////////////////// /////////////////////////////////////////
/** /**
* existing stats as of today, April 10. 2001 * existing stats as of today, April 10. 2001
* *
* eoBestFitnessStat : best value in pop - type EOT::Fitness * eoBestFitnessStat : best value in pop - type EOT::Fitness
* eoAverageStat : average value in pop - type EOT::Fitness * eoAverageStat : average value in pop - type EOT::Fitness
* eoSecondMomentStat: average + stdev - type std::pair<double, double> * eoSecondMomentStat: average + stdev - type std::pair<double, double>
* eoSortedPopStat : whole population - type std::string (!!) * eoSortedPopStat : whole population - type std::string (!!)
* eoScalarFitnessStat: the fitnesses - type std::vector<double> * eoScalarFitnessStat: the fitnesses - type std::vector<double>
*/ */
// Best fitness in population // Best fitness in population
//--------------------------- //---------------------------
eoValueParam<bool>& printBestParam = _parser.createParam(true, "printBestStat", "Print Best/avg/stdev every gen.", '\0', "Output"); eoValueParam<bool>& printBestParam = _parser.createParam(true, "printBestStat", "Print Best/avg/stdev every gen.", '\0', "Output");
eoValueParam<bool>& plotBestParam = _parser.createParam(false, "plotBestStat", "Plot Best/avg Stat", '\0', "Output - Graphical"); eoValueParam<bool>& plotBestParam = _parser.createParam(false, "plotBestStat", "Plot Best/avg Stat", '\0', "Output - Graphical");
eoValueParam<bool>& fileBestParam = _parser.createParam(false, "fileBestStat", "Output bes/avg/std to file", '\0', "Output - Disk"); eoValueParam<bool>& fileBestParam = _parser.createParam(false, "fileBestStat", "Output bes/avg/std to file", '\0', "Output - Disk");
eoBestFitnessStat<EOT> *bestStat = NULL; eoBestFitnessStat<EOT> *bestStat = NULL;
if ( printBestParam.value() || plotBestParam.value() || fileBestParam.value() ) if ( printBestParam.value() || plotBestParam.value() || fileBestParam.value() )
// we need the bestStat for at least one of the 3 above // we need the bestStat for at least one of the 3 above
{ {
bestStat = new eoBestFitnessStat<EOT>; bestStat = new eoBestFitnessStat<EOT>;
// store it // store it
_state.storeFunctor(bestStat); _state.storeFunctor(bestStat);
// add it to the checkpoint // add it to the checkpoint
checkpoint->add(*bestStat); checkpoint->add(*bestStat);
} }
// Average fitness alone // Average fitness alone
//---------------------- //----------------------
eoAverageStat<EOT> *averageStat = NULL; // do we need averageStat? eoAverageStat<EOT> *averageStat = NULL; // do we need averageStat?
if ( plotBestParam.value() ) // we need it for gnuplot output if ( plotBestParam.value() ) // we need it for gnuplot output
{ {
averageStat = new eoAverageStat<EOT>; averageStat = new eoAverageStat<EOT>;
// store it // store it
_state.storeFunctor(averageStat); _state.storeFunctor(averageStat);
// add it to the checkpoint // add it to the checkpoint
checkpoint->add(*averageStat); checkpoint->add(*averageStat);
} }
// Second moment stats: average and stdev // Second moment stats: average and stdev
//--------------------------------------- //---------------------------------------
eoSecondMomentStats<EOT> *secondStat = NULL; eoSecondMomentStats<EOT> *secondStat = NULL;
if ( printBestParam.value() ) // we need it for sreen output if ( printBestParam.value() ) // we need it for sreen output
{ {
secondStat = new eoSecondMomentStats<EOT>; secondStat = new eoSecondMomentStats<EOT>;
// store it // store it
_state.storeFunctor(secondStat); _state.storeFunctor(secondStat);
// add it to the checkpoint // add it to the checkpoint
checkpoint->add(*secondStat); checkpoint->add(*secondStat);
} }
// Dump of the whole population // Dump of the whole population
//----------------------------- //-----------------------------
eoSortedPopStat<EOT> *popStat = NULL; eoSortedPopStat<EOT> *popStat = NULL;
eoValueParam<bool>& printPopParam = _parser.createParam(false, "printPop", "Print sorted pop. every gen.", '\0', "Output"); eoValueParam<bool>& printPopParam = _parser.createParam(false, "printPop", "Print sorted pop. every gen.", '\0', "Output");
if ( printPopParam.value() ) // we do want pop dump if ( printPopParam.value() ) // we do want pop dump
{ {
popStat = new eoSortedPopStat<EOT>; popStat = new eoSortedPopStat<EOT>;
// store it // store it
_state.storeFunctor(popStat); _state.storeFunctor(popStat);
// add it to the checkpoint // add it to the checkpoint
checkpoint->add(*popStat); checkpoint->add(*popStat);
} }
// do we wnat some histogram of fitnesses snpashots? // do we wnat some histogram of fitnesses snpashots?
eoValueParam<bool> plotHistogramParam = _parser.createParam(false, "plotHisto", "Plot histogram of fitnesses", '\0', "Output - Graphical"); eoValueParam<bool> plotHistogramParam = _parser.createParam(false, "plotHisto", "Plot histogram of fitnesses", '\0', "Output - Graphical");
/////////////// ///////////////
// The monitors // The monitors
/////////////// ///////////////
// do we want an eoStdoutMonitor? // do we want an eoStdoutMonitor?
bool needStdoutMonitor = printBestParam.value() bool needStdoutMonitor = printBestParam.value()
|| printPopParam.value() ; || printPopParam.value() ;
// The Stdout monitor will print parameters to the screen ... // The Stdout monitor will print parameters to the screen ...
if ( needStdoutMonitor ) if ( needStdoutMonitor )
{ {
eoStdoutMonitor *monitor = new eoStdoutMonitor(false); eoStdoutMonitor *monitor = new eoStdoutMonitor(false);
_state.storeFunctor(monitor); _state.storeFunctor(monitor);
// when called by the checkpoint (i.e. at every generation) // when called by the checkpoint (i.e. at every generation)
checkpoint->add(*monitor); checkpoint->add(*monitor);
// the monitor will output a series of parameters: add them // the monitor will output a series of parameters: add them
monitor->add(*generationCounter); monitor->add(*generationCounter);
if (useEvalParam.value()) // we want nb of evaluations if (useEvalParam.value()) // we want nb of evaluations
monitor->add(_eval); monitor->add(_eval);
if (useTimeParam.value()) // we want time if (useTimeParam.value()) // we want time
{ {
tCounter = new eoTimeCounter; tCounter = new eoTimeCounter;
_state.storeFunctor(tCounter); _state.storeFunctor(tCounter);
checkpoint->add(*tCounter); checkpoint->add(*tCounter);
monitor->add(*tCounter); monitor->add(*tCounter);
} }
if (printBestParam.value()) if (printBestParam.value())
{ {
monitor->add(*bestStat); monitor->add(*bestStat);
monitor->add(*secondStat); monitor->add(*secondStat);
} }
if ( printPopParam.value()) if ( printPopParam.value())
monitor->add(*popStat); monitor->add(*popStat);
} }
// first handle the dir test - if we need at least one file // first handle the dir test - if we need at least one file
if ( ( fileBestParam.value() || plotBestParam.value() || if ( ( fileBestParam.value() || plotBestParam.value() ||
plotHistogramParam.value() ) plotHistogramParam.value() )
&& !dirOK ) // just in case we add something before && !dirOK ) // just in case we add something before
dirOK = testDirRes(dirNameParam.value(), eraseParam.value()); // TRUE dirOK = testDirRes(dirNameParam.value(), eraseParam.value()); // TRUE
if (fileBestParam.value()) // A file monitor for best & secondMoment if (fileBestParam.value()) // A file monitor for best & secondMoment
{ {
#ifdef _MSVC #ifdef _MSVC
std::string stmp = dirNameParam.value() + "\best.xg"; std::string stmp = dirNameParam.value() + "\best.xg";
#else #else
std::string stmp = dirNameParam.value() + "/best.xg"; std::string stmp = dirNameParam.value() + "/best.xg";
#endif #endif
eoFileMonitor *fileMonitor = new eoFileMonitor(stmp); eoFileMonitor *fileMonitor = new eoFileMonitor(stmp);
// save and give to checkpoint // save and give to checkpoint
_state.storeFunctor(fileMonitor); _state.storeFunctor(fileMonitor);
checkpoint->add(*fileMonitor); checkpoint->add(*fileMonitor);
// and feed with some statistics // and feed with some statistics
fileMonitor->add(*generationCounter); fileMonitor->add(*generationCounter);
fileMonitor->add(_eval); fileMonitor->add(_eval);
if (tCounter) // we want the time as well if (tCounter) // we want the time as well
{ {
// std::cout << "On met timecounter\n"; // std::cout << "On met timecounter\n";
fileMonitor->add(*tCounter); fileMonitor->add(*tCounter);
} }
fileMonitor->add(*bestStat); fileMonitor->add(*bestStat);
fileMonitor->add(*secondStat); fileMonitor->add(*secondStat);
} }
if (plotBestParam.value()) // an eoGnuplot1DMonitor for best & average #if !defined(NO_GNUPLOT)
{ if (plotBestParam.value()) // an eoGnuplot1DMonitor for best & average
std::string stmp = dirNameParam.value() + "/gnu_best.xg"; {
eoGnuplot1DMonitor *gnuMonitor = new eoGnuplot1DMonitor(stmp,minimizing_fitness<EOT>()); std::string stmp = dirNameParam.value() + "/gnu_best.xg";
// save and give to checkpoint eoGnuplot1DMonitor *gnuMonitor = new eoGnuplot1DMonitor(stmp,minimizing_fitness<EOT>());
_state.storeFunctor(gnuMonitor); // save and give to checkpoint
checkpoint->add(*gnuMonitor); _state.storeFunctor(gnuMonitor);
// and feed with some statistics checkpoint->add(*gnuMonitor);
if (useEvalParam.value()) // do we want eval as X coordinate // and feed with some statistics
gnuMonitor->add(_eval); if (useEvalParam.value()) // do we want eval as X coordinate
else if (tCounter) // or time? gnuMonitor->add(_eval);
gnuMonitor->add(*tCounter); else if (tCounter) // or time?
else // default: generation gnuMonitor->add(*tCounter);
gnuMonitor->add(*generationCounter); else // default: generation
gnuMonitor->add(*bestStat); gnuMonitor->add(*generationCounter);
gnuMonitor->add(*averageStat); gnuMonitor->add(*bestStat);
} gnuMonitor->add(*averageStat);
}
// historgram?
if (plotHistogramParam.value()) // want to see how the fitness is spread? // historgram?
{ if (plotHistogramParam.value()) // want to see how the fitness is spread?
eoScalarFitnessStat<EOT> *fitStat = new eoScalarFitnessStat<EOT>; {
_state.storeFunctor(fitStat); eoScalarFitnessStat<EOT> *fitStat = new eoScalarFitnessStat<EOT>;
checkpoint->add(*fitStat); _state.storeFunctor(fitStat);
// a gnuplot-based monitor for snapshots: needs a dir name checkpoint->add(*fitStat);
eoGnuplot1DSnapshot *fitSnapshot = new eoGnuplot1DSnapshot(dirNameParam.value()); // a gnuplot-based monitor for snapshots: needs a dir name
_state.storeFunctor(fitSnapshot); eoGnuplot1DSnapshot *fitSnapshot = new eoGnuplot1DSnapshot(dirNameParam.value());
// add any stat that is a std::vector<double> to it _state.storeFunctor(fitSnapshot);
fitSnapshot->add(*fitStat); // add any stat that is a std::vector<double> to it
// and of course add it to the checkpoint fitSnapshot->add(*fitStat);
checkpoint->add(*fitSnapshot); // and of course add it to the checkpoint
} checkpoint->add(*fitSnapshot);
}
////////////////////////////////// #endif
// State savers //////////////////////////////////
////////////////////////////// // State savers
//////////////////////////////
// feed the state to state savers
// save state every N generation // feed the state to state savers
eoValueParam<unsigned>& saveFrequencyParam = _parser.createParam(unsigned(0), "saveFrequency", "Save every F generation (0 = only final state, absent = never)", '\0', "Persistence" ); // save state every N generation
eoValueParam<unsigned>& saveFrequencyParam = _parser.createParam(unsigned(0), "saveFrequency", "Save every F generation (0 = only final state, absent = never)", '\0', "Persistence" );
if (_parser.isItThere(saveFrequencyParam))
{ if (_parser.isItThere(saveFrequencyParam))
// first make sure dirName is OK {
if (! dirOK ) // first make sure dirName is OK
dirOK = testDirRes(dirNameParam.value(), eraseParam.value()); // TRUE if (! dirOK )
dirOK = testDirRes(dirNameParam.value(), eraseParam.value()); // TRUE
unsigned freq = (saveFrequencyParam.value()>0 ? saveFrequencyParam.value() : UINT_MAX );
#ifdef _MSVC unsigned freq = (saveFrequencyParam.value()>0 ? saveFrequencyParam.value() : UINT_MAX );
std::string stmp = dirNameParam.value() + "\generations"; #ifdef _MSVC
#else std::string stmp = dirNameParam.value() + "\generations";
std::string stmp = dirNameParam.value() + "/generations"; #else
#endif std::string stmp = dirNameParam.value() + "/generations";
eoCountedStateSaver *stateSaver1 = new eoCountedStateSaver(freq, _state, stmp); #endif
_state.storeFunctor(stateSaver1); eoCountedStateSaver *stateSaver1 = new eoCountedStateSaver(freq, _state, stmp);
checkpoint->add(*stateSaver1); _state.storeFunctor(stateSaver1);
} checkpoint->add(*stateSaver1);
}
// save state every T seconds
eoValueParam<unsigned>& saveTimeIntervalParam = _parser.createParam(unsigned(0), "saveTimeInterval", "Save every T seconds (0 or absent = never)", '\0',"Persistence" ); // save state every T seconds
if (_parser.isItThere(saveTimeIntervalParam) && saveTimeIntervalParam.value()>0) eoValueParam<unsigned>& saveTimeIntervalParam = _parser.createParam(unsigned(0), "saveTimeInterval", "Save every T seconds (0 or absent = never)", '\0',"Persistence" );
{ if (_parser.isItThere(saveTimeIntervalParam) && saveTimeIntervalParam.value()>0)
// first make sure dirName is OK {
if (! dirOK ) // first make sure dirName is OK
dirOK = testDirRes(dirNameParam.value(), eraseParam.value()); // TRUE if (! dirOK )
dirOK = testDirRes(dirNameParam.value(), eraseParam.value()); // TRUE
#ifdef _MSVC
std::string stmp = dirNameParam.value() + "\time"; #ifdef _MSVC
#else std::string stmp = dirNameParam.value() + "\time";
std::string stmp = dirNameParam.value() + "/time"; #else
#endif std::string stmp = dirNameParam.value() + "/time";
eoTimedStateSaver *stateSaver2 = new eoTimedStateSaver(saveTimeIntervalParam.value(), _state, stmp); #endif
_state.storeFunctor(stateSaver2); eoTimedStateSaver *stateSaver2 = new eoTimedStateSaver(saveTimeIntervalParam.value(), _state, stmp);
checkpoint->add(*stateSaver2); _state.storeFunctor(stateSaver2);
} checkpoint->add(*stateSaver2);
}
// and that's it for the (control and) output
return *checkpoint; // and that's it for the (control and) output
} return *checkpoint;
}
#endif
#endif

View file

@ -1,99 +1,104 @@
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- /* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
----------------------------------------------------------------------------- -----------------------------------------------------------------------------
eoScalarFitness.h eoScalarFitness.h
(c) Maarten Keijzer (mkeijzer@mad.scientist.com) and GeNeura Team, 1999, 2000 (c) Maarten Keijzer (mkeijzer@mad.scientist.com) and GeNeura Team, 1999, 2000
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version. version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/ */
#ifndef eoScalarFitness_h #ifndef eoScalarFitness_h
#define eoScalarFitness_h #define eoScalarFitness_h
#include <functional> #include <functional>
#include <iostream> #include <iostream>
/** /**
* eoScalarFitness<ScalarType, Compare = less<ScalarType> >: * eoScalarFitness<ScalarType, Compare = less<ScalarType> >:
* Wraps a scalar fitness values such as a double or int, with the option of * Wraps a scalar fitness values such as a double or int, with the option of
* maximizing (using less<ScalarType>) or minimizing (using greater<ScalarType>) * maximizing (using less<ScalarType>) or minimizing (using greater<ScalarType>)
* It overrides operator<() to use the Compare template argument * 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. * with this quantity as if it were a ScalarType.
*/ */
template <class ScalarType, class Compare > template <class ScalarType, class Compare >
class eoScalarFitness class eoScalarFitness
{ {
public : public :
eoScalarFitness() : value() {} eoScalarFitness() : value() {}
eoScalarFitness(const eoScalarFitness& other) : value(other.value) {} eoScalarFitness(const eoScalarFitness& other) : value(other.value) {}
eoScalarFitness(const ScalarType& v) : value(v) {} eoScalarFitness(const ScalarType& v) : value(v) {}
eoScalarFitness& operator=(const eoScalarFitness& other) eoScalarFitness& operator=(const eoScalarFitness& other)
{ value = other.value; return *this; } { value = other.value; return *this; }
eoScalarFitness& operator=(const ScalarType& v) eoScalarFitness& operator=(const ScalarType& v)
{ value = v; return *this; } { value = v; return *this; }
operator ScalarType(void) const { return value; } operator ScalarType(void) const { return value; }
/// Comparison, using less by default /// Comparison, using less by default
bool operator<(const eoScalarFitness& other) const bool operator<(const eoScalarFitness& other) const
{ return Compare()(value, other.value); } { return Compare()(value, other.value); }
// implementation of the other operators /// Comparison, using less by default
bool operator>( const eoScalarFitness<ScalarType, Compare>& y ) const { return y < *this; } // needed for MSVC 8 (MSVC 2005) added by J.Eggermont 20-11-2006
// implementation of the other operators bool operator<(const ScalarType& other) const
bool operator<=( const eoScalarFitness<ScalarType, Compare>& y ) const { return !(*this > y); } { return Compare()(value, other); }
// implementation of the other operators
bool operator>=(const eoScalarFitness<ScalarType, Compare>& y ) const { return !(*this < y); } // implementation of the other operators
bool operator>( const eoScalarFitness<ScalarType, Compare>& y ) const { return y < *this; }
// implementation of the other operators
private : bool operator<=( const eoScalarFitness<ScalarType, Compare>& y ) const { return !(*this > y); }
ScalarType value; // implementation of the other operators
}; bool operator>=(const eoScalarFitness<ScalarType, Compare>& y ) const { return !(*this < y); }
/**
Typedefs for fitness comparison, Maximizing Fitness compares with less, private :
and minimizing fitness compares with greater. This because we want ordinary ScalarType value;
fitness values (doubles) to be equivalent with Maximizing Fitness, and };
comparing with less is the default behaviour.
*/ /**
typedef eoScalarFitness<double, std::less<double> > eoMaximizingFitness; Typedefs for fitness comparison, Maximizing Fitness compares with less,
typedef eoScalarFitness<double, std::greater<double> > eoMinimizingFitness; and minimizing fitness compares with greater. This because we want ordinary
fitness values (doubles) to be equivalent with Maximizing Fitness, and
template <class F, class Cmp> comparing with less is the default behaviour.
std::ostream& operator<<(std::ostream& os, const eoScalarFitness<F, Cmp>& f) */
{ typedef eoScalarFitness<double, std::less<double> > eoMaximizingFitness;
os << (F) f; typedef eoScalarFitness<double, std::greater<double> > eoMinimizingFitness;
return os;
} template <class F, class Cmp>
std::ostream& operator<<(std::ostream& os, const eoScalarFitness<F, Cmp>& f)
template <class F, class Cmp> {
std::istream& operator>>(std::istream& is, eoScalarFitness<F, Cmp>& f) os << (F) f;
{ return os;
F value; }
is >> value;
f = value; template <class F, class Cmp>
return is; std::istream& operator>>(std::istream& is, eoScalarFitness<F, Cmp>& f)
} {
F value;
#endif is >> value;
f = value;
return is;
}
#endif

View file

@ -1,54 +1,54 @@
/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- /** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
----------------------------------------------------------------------------- -----------------------------------------------------------------------------
eoSelectOne.h eoSelectOne.h
(c) Maarten Keijzer, GeNeura Team, 2000 (c) Maarten Keijzer, GeNeura Team, 2000
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version. version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/ */
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#ifndef _eoSelectOne_h #ifndef _eoSelectOne_h
#define _eoSelectOne_h #define _eoSelectOne_h
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#include <eoPop.h> #include <eoPop.h>
#include <eoFunctor.h> #include <eoFunctor.h>
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
/** eoSelectOne selects only one element from a whole population. /** eoSelectOne selects only one element from a whole population.
Most selection techniques are simply repeated applications Most selection techniques are simply repeated applications
of eoSelectOne. of eoSelectOne.
@see eoSelectMany, eoSelectRandom, eoDetTournament, eoStochTournament, eoProportional @see eoSelectMany, eoSelectRandom, eoDetTournament, eoStochTournament, eoProportional
*/ */
#ifdef _MSC_VER #if defined(_MSC_VER) && (_MSC_VER < 1300)
template<class EOT, class WorthT = EOT::Fitness> template<class EOT, class WorthT = EOT::Fitness>
#else #else
template<class EOT, class WorthT = typename EOT::Fitness> template<class EOT, class WorthT = typename EOT::Fitness>
#endif #endif
class eoSelectOne : public eoUF<const eoPop<EOT>&, const EOT&> class eoSelectOne : public eoUF<const eoPop<EOT>&, const EOT&>
{ {
public : public :
/// virtual function to setup some population stats (for instance eoProportional can benefit greatly from this) /// virtual function to setup some population stats (for instance eoProportional can benefit greatly from this)
virtual void setup(const eoPop<EOT>& _pop) virtual void setup(const eoPop<EOT>& _pop)
{} {}
}; };
#endif #endif

View file

@ -1,91 +1,91 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoFitnessStat.h // eoFitnessStat.h
// (c) Marc Schoenauer, Maarten Keijzer and GeNeura Team, 2000, 2001 // (c) Marc Schoenauer, Maarten Keijzer and GeNeura Team, 2000, 2001
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version. version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es Contact: todos@geneura.ugr.es, http://geneura.ugr.es
Marc.Schoenauer@polytechnique.fr Marc.Schoenauer@polytechnique.fr
mkeijzer@dhi.dk mkeijzer@dhi.dk
*/ */
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#ifndef _eoFitnessStat_h #ifndef _eoFitnessStat_h
#define _eoFitnessStat_h #define _eoFitnessStat_h
#include <utils/eoStat.h> #include <utils/eoStat.h>
/** /**
The fitnesses of a whole population, as a vector The fitnesses of a whole population, as a vector
*/ */
template <class EOT, class FitT = typename EOT::Fitness> template <class EOT, class FitT = typename EOT::Fitness>
class eoFitnessStat : public eoSortedStat<EOT, std::vector<FitT> > class eoFitnessStat : public eoSortedStat<EOT, std::vector<FitT> >
{ {
public : public :
using eoSortedStat<EOT, std::vector<FitT> >::value; using eoSortedStat<EOT, std::vector<FitT> >::value;
eoFitnessStat(std::string _description = "AllFitnesses") : eoFitnessStat(std::string _description = "AllFitnesses") :
eoSortedStat<EOT,std::vector<FitT> >(std::vector<FitT>(0), _description) {} eoSortedStat<EOT,std::vector<FitT> >(std::vector<FitT>(0), _description) {}
virtual void operator()(const std::vector<const EOT*>& _popPters) virtual void operator()(const std::vector<const EOT*>& _popPters)
{ {
value().resize(_popPters.size()); value().resize(_popPters.size());
for (unsigned i=0; i<_popPters.size(); i++) for (unsigned i=0; i<_popPters.size(); i++)
value()[i] = _popPters[i]->fitness(); value()[i] = _popPters[i]->fitness();
} }
}; };
/** For multi-objective fitness, we need to translate a stat<vector<double> > /** For multi-objective fitness, we need to translate a stat<vector<double> >
into a vector<stat>, so each objective gets a seperate stat into a vector<stat>, so each objective gets a seperate stat
*/ */
#ifdef _MSC_VER #ifdef _MSC_VER
// The follownig is needed to avoid some bug in Visual Studio 6.0 // The follownig is needed to avoid some bug in Visual Studio 6.0
typedef double PartFitDefault; typedef double PartFitDefault;
template <class EOT, class PartFitT = PartFitDefault> template <class EOT, class PartFitT = PartFitDefault>
class eoMOFitnessStat : public eoSortedStat<EOT, std::vector<PartFitT> > class eoMOFitnessStat : public eoSortedStat<EOT, std::vector<PartFitT> >
#else #else
template <class EOT, class PartFitT = double> template <class EOT, class PartFitT = double>
class eoMOFitnessStat : public eoSortedStat<EOT, std::vector<PartFitT> > class eoMOFitnessStat : public eoSortedStat<EOT, std::vector<PartFitT> >
#endif #endif
{ {
public: public:
using eoSortedStat<EOT, std::vector<PartFitT> >::value; using eoSortedStat<EOT, std::vector<PartFitT> >::value;
/** Ctor: say what component you want /** Ctor: say what component you want
*/ */
eoMOFitnessStat(unsigned _objective, std::string _description = "MO-Fitness") : eoMOFitnessStat(unsigned _objective, std::string _description = "MO-Fitness") :
eoSortedStat<EOT, std::vector<PartFitT> >(std::vector<PartFitT>(0), _description), eoSortedStat<EOT, std::vector<PartFitT> >(std::vector<PartFitT>(0), _description),
objective(_objective) {} objective(_objective) {}
virtual void operator()(const std::vector<const EOT*>& _popPters) virtual void operator()(const std::vector<const EOT*>& _popPters)
{ {
value().resize(_popPters.size()); value().resize(_popPters.size());
for (unsigned i=0; i<_popPters.size(); i++) for (unsigned i=0; i<_popPters.size(); i++)
{ {
value()[i] = _popPters[i]->fitness()[objective]; value()[i] = _popPters[i]->fitness()[objective];
} }
} }
private: private:
unsigned int objective; // The objective we're storing unsigned int objective; // The objective we're storing
}; };
#endif #endif

View file

@ -32,11 +32,19 @@ Contact: todos@geneura.ugr.es, http://geneura.ugr.es
// //
// The C99-standard defines uint32_t to be declared in stdint.h, but some // The C99-standard defines uint32_t to be declared in stdint.h, but some
// systmes don't have that and implement it in inttypes.h. // systmes don't have that and implement it in inttypes.h.
// first if check added for MSVC by Jeroen Eggermont 20-11-2006, needed for MSVC 2003 (and 2005)
# if (defined _MSC_VER)
typedef unsigned long uint32_t;
#include <cmath>
#else
#if (! defined __sun) #if (! defined __sun)
#include <stdint.h> #include <stdint.h>
#else #else
#include <inttypes.h> #include <inttypes.h>
#endif #endif
#endif
#include <vector> #include <vector>
#include "eoPersistent.h" #include "eoPersistent.h"

View file

@ -102,7 +102,7 @@ public :
( For eoScalarFitnessAssembled user eoAssembledFitnessStat classes.) ( For eoScalarFitnessAssembled user eoAssembledFitnessStat classes.)
*/ */
#ifdef _MSC_VER #if defined(_MSC_VER) && (_MSC_VER < 1300)
template <class EOT> class eoAverageStat : public eoStat<EOT, EOT::Fitness> template <class EOT> class eoAverageStat : public eoStat<EOT, EOT::Fitness>
#else #else
template <class EOT> class eoAverageStat : public eoStat<EOT, typename EOT::Fitness> template <class EOT> class eoAverageStat : public eoStat<EOT, typename EOT::Fitness>
@ -203,7 +203,7 @@ public :
/** /**
The n_th element fitness in the population (see eoBestFitnessStat) The n_th element fitness in the population (see eoBestFitnessStat)
*/ */
#ifdef _MSC_VER #if defined(_MSC_VER) && (_MSC_VER < 1300)
template <class EOT> template <class EOT>
class eoNthElementFitnessStat : public eoSortedStat<EOT, EOT::Fitness > class eoNthElementFitnessStat : public eoSortedStat<EOT, EOT::Fitness >
#else #else
@ -308,7 +308,7 @@ public :
( For eoScalarFitnessAssembled look at eoAssembledFitnessStat ) ( For eoScalarFitnessAssembled look at eoAssembledFitnessStat )
*/ */
#ifdef _MSC_VER #if defined(_MSC_VER) && (_MSC_VER < 1300)
template <class EOT> template <class EOT>
class eoBestFitnessStat : public eoStat<EOT, EOT::Fitness> class eoBestFitnessStat : public eoStat<EOT, EOT::Fitness>
#else #else

View file

@ -1,338 +1,338 @@
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- /* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
----------------------------------------------------------------------------- -----------------------------------------------------------------------------
selectors.h selectors.h
A bunch of useful selector functions. They generally have three forms: A bunch of useful selector functions. They generally have three forms:
template <class It> template <class It>
It select(It begin, It end, params, eoRng& gen = rng); It select(It begin, It end, params, eoRng& gen = rng);
template <class EOT> template <class EOT>
const EOT& select(const eoPop<EOT>& pop, params, eoRng& gen = rng); const EOT& select(const eoPop<EOT>& pop, params, eoRng& gen = rng);
template <class EOT> template <class EOT>
EOT& select(eoPop<EOT>& pop, params, eoRng& gen = rng); EOT& select(eoPop<EOT>& pop, params, eoRng& gen = rng);
where select is one of: roulette_wheel, deterministic_tournament where select is one of: roulette_wheel, deterministic_tournament
and stochastic_tournament (at the moment). and stochastic_tournament (at the moment).
(c) Maarten Keijzer (mak@dhi.dk) and GeNeura Team, 1999, 2000 (c) Maarten Keijzer (mak@dhi.dk) and GeNeura Team, 1999, 2000
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version. version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/ */
#ifndef SELECT__H #ifndef SELECT__H
#define SELECT__H #define SELECT__H
#include <stdexcept> #include <stdexcept>
#include "eoRNG.h" #include "eoRNG.h"
#include <eoPop.h> #include <eoPop.h>
/** /**
\defgroup selectors \defgroup selectors
*/ */
template <class EOT> template <class EOT>
bool minimizing_fitness() bool minimizing_fitness()
{ {
EOT eo1; // Assuming people don't do anything fancy in the default constructor! 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 likely not working with scalar fitness values. In that case we're sorry
but you cannot use lottery or roulette_wheel selection... but you cannot use lottery or roulette_wheel selection...
*/ */
#ifdef _MSC_VER #ifdef _MSC_VER
eo1.fitness( EOT::Fitness(0.0) ); eo1.fitness( EOT::Fitness(0.0) );
eo2.fitness( EOT::Fitness(1.0) ); eo2.fitness( EOT::Fitness(1.0) );
#else #else
eo1.fitness( typename EOT::Fitness(0.0) ); // tried to cast it to an EOT::Fitness, but for some reason GNU barfs on this 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) ); eo2.fitness( typename EOT::Fitness(1.0) );
#endif #endif
return eo2 < eo1; // check whether we have a minimizing fitness return eo2 < eo1; // check whether we have a minimizing fitness
} }
inline double scale_fitness(const std::pair<double, double>& _minmax, double _value) inline double scale_fitness(const std::pair<double, double>& _minmax, double _value)
{ {
if (_minmax.first == _minmax.second) if (_minmax.first == _minmax.second)
{ {
return 0.0; // no differences in fitness, population converged! return 0.0; // no differences in fitness, population converged!
} }
// else // else
return (_value - _minmax.first) / (_minmax.second - _minmax.first); return (_value - _minmax.first) / (_minmax.second - _minmax.first);
} }
template <class It> template <class It>
double sum_fitness(It begin, It end) double sum_fitness(It begin, It end)
{ {
double sum = 0.0; double sum = 0.0;
for (; begin != end; ++begin) for (; begin != end; ++begin)
{ {
double v = static_cast<double>(begin->fitness()); double v = static_cast<double>(begin->fitness());
if (v < 0.0) if (v < 0.0)
throw std::logic_error("sum_fitness: negative fitness value encountered"); throw std::logic_error("sum_fitness: negative fitness value encountered");
sum += v; sum += v;
} }
return sum; return sum;
} }
template <class EOT> template <class EOT>
double sum_fitness(const eoPop<EOT>& _pop) double sum_fitness(const eoPop<EOT>& _pop)
{ {
return sum_fitness(_pop.begin(), _pop.end()); return sum_fitness(_pop.begin(), _pop.end());
} }
template <class EOT> template <class EOT>
double sum_fitness(const eoPop<EOT>& _pop, std::pair<double, double>& _minmax) double sum_fitness(const eoPop<EOT>& _pop, std::pair<double, double>& _minmax)
{ {
double rawTotal, scaledTotal; double rawTotal, scaledTotal;
typename eoPop<EOT>::const_iterator it = _pop.begin(); typename eoPop<EOT>::const_iterator it = _pop.begin();
_minmax.first = it->fitness(); _minmax.first = it->fitness();
_minmax.second = it++->fitness(); _minmax.second = it++->fitness();
for(; it != _pop.end(); ++it) for(; it != _pop.end(); ++it)
{ {
double v = static_cast<double>(it->fitness()); double v = static_cast<double>(it->fitness());
_minmax.first = std::min(_minmax.first, v); _minmax.first = std::min(_minmax.first, v);
_minmax.second = std::max(_minmax.second, v); _minmax.second = std::max(_minmax.second, v);
rawTotal += v; rawTotal += v;
} }
if (minimizing_fitness<EOT>()) if (minimizing_fitness<EOT>())
{ {
std::swap(_minmax.first, _minmax.second); std::swap(_minmax.first, _minmax.second);
} }
scaledTotal = 0.0; scaledTotal = 0.0;
// unfortunately a second loop is neccessary to scale the fitness // unfortunately a second loop is neccessary to scale the fitness
for (it = _pop.begin(); it != _pop.end(); ++it) for (it = _pop.begin(); it != _pop.end(); ++it)
{ {
double v = scale_fitness(_minmax, static_cast<double>(it->fitness())); double v = scale_fitness(_minmax, static_cast<double>(it->fitness()));
scaledTotal += v; scaledTotal += v;
} }
return scaledTotal; return scaledTotal;
} }
template <class It> template <class It>
It roulette_wheel(It _begin, It _end, double total, eoRng& _gen = rng) It roulette_wheel(It _begin, It _end, double total, eoRng& _gen = rng)
{ {
float roulette = _gen.uniform(total); float roulette = _gen.uniform(total);
if (roulette == 0.0) // covers the case where total==0.0 if (roulette == 0.0) // covers the case where total==0.0
return _begin + _gen.random(_end - _begin); // uniform choice return _begin + _gen.random(_end - _begin); // uniform choice
It i = _begin; It i = _begin;
while (roulette > 0.0) while (roulette > 0.0)
{ {
roulette -= static_cast<double>(*(i++)); roulette -= static_cast<double>(*(i++));
} }
return --i; return --i;
} }
template <class EOT> template <class EOT>
const EOT& roulette_wheel(const eoPop<EOT>& _pop, double total, eoRng& _gen = rng) const EOT& roulette_wheel(const eoPop<EOT>& _pop, double total, eoRng& _gen = rng)
{ {
float roulette = _gen.uniform(total); float roulette = _gen.uniform(total);
if (roulette == 0.0) // covers the case where total==0.0 if (roulette == 0.0) // covers the case where total==0.0
return _pop[_gen.random(_pop.size())]; // uniform choice return _pop[_gen.random(_pop.size())]; // uniform choice
typename eoPop<EOT>::const_iterator i = _pop.begin(); typename eoPop<EOT>::const_iterator i = _pop.begin();
while (roulette > 0.0) while (roulette > 0.0)
{ {
roulette -= static_cast<double>((i++)->fitness()); roulette -= static_cast<double>((i++)->fitness());
} }
return *--i; return *--i;
} }
template <class EOT> template <class EOT>
EOT& roulette_wheel(eoPop<EOT>& _pop, double total, eoRng& _gen = rng) EOT& roulette_wheel(eoPop<EOT>& _pop, double total, eoRng& _gen = rng)
{ {
float roulette = _gen.uniform(total); float roulette = _gen.uniform(total);
if (roulette == 0.0) // covers the case where total==0.0 if (roulette == 0.0) // covers the case where total==0.0
return _pop[_gen.random(_pop.size())]; // uniform choice return _pop[_gen.random(_pop.size())]; // uniform choice
typename eoPop<EOT>::iterator i = _pop.begin(); typename eoPop<EOT>::iterator i = _pop.begin();
while (roulette > 0.0) while (roulette > 0.0)
{ {
roulette -= static_cast<double>((i++)->fitness()); roulette -= static_cast<double>((i++)->fitness());
} }
return *--i; return *--i;
} }
template <class It> template <class It>
It deterministic_tournament(It _begin, It _end, unsigned _t_size, eoRng& _gen = rng) 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) for (unsigned i = 0; i < _t_size - 1; ++i)
{ {
It competitor = _begin + _gen.random(_end - _begin); It competitor = _begin + _gen.random(_end - _begin);
if (*best < *competitor) if (*best < *competitor)
{ {
best = competitor; best = competitor;
} }
} }
return best; return best;
} }
template <class EOT> template <class EOT>
const EOT& deterministic_tournament(const eoPop<EOT>& _pop, unsigned _t_size, eoRng& _gen = rng) const EOT& deterministic_tournament(const eoPop<EOT>& _pop, unsigned _t_size, eoRng& _gen = rng)
{ {
return *deterministic_tournament(_pop.begin(), _pop.end(), _t_size, _gen); return *deterministic_tournament(_pop.begin(), _pop.end(), _t_size, _gen);
} }
template <class EOT> template <class EOT>
EOT& deterministic_tournament(eoPop<EOT>& _pop, unsigned _t_size, eoRng& _gen = rng) EOT& deterministic_tournament(eoPop<EOT>& _pop, unsigned _t_size, eoRng& _gen = rng)
{ {
return *deterministic_tournament(_pop.begin(), _pop.end(), _t_size, _gen); return *deterministic_tournament(_pop.begin(), _pop.end(), _t_size, _gen);
} }
template <class It> template <class It>
It inverse_deterministic_tournament(It _begin, It _end, unsigned _t_size, eoRng& _gen = rng) 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) for (unsigned i = 1; i < _t_size; ++i)
{ {
It competitor = _begin + _gen.random(_end - _begin); It competitor = _begin + _gen.random(_end - _begin);
if (competitor == worst) if (competitor == worst)
{ {
--i; --i;
continue; // try again continue; // try again
} }
if (*competitor < *worst) if (*competitor < *worst)
{ {
worst = competitor; worst = competitor;
} }
} }
return worst; return worst;
} }
template <class EOT> template <class EOT>
const EOT& inverse_deterministic_tournament(const eoPop<EOT>& _pop, unsigned _t_size, eoRng& _gen = rng) const EOT& inverse_deterministic_tournament(const eoPop<EOT>& _pop, unsigned _t_size, eoRng& _gen = rng)
{ {
return *inverse_deterministic_tournament<EOT>(_pop.begin(), _pop.end(), _t_size, _gen); return *inverse_deterministic_tournament<EOT>(_pop.begin(), _pop.end(), _t_size, _gen);
} }
template <class EOT> template <class EOT>
EOT& inverse_deterministic_tournament(eoPop<EOT>& _pop, unsigned _t_size, eoRng& _gen = rng) EOT& inverse_deterministic_tournament(eoPop<EOT>& _pop, unsigned _t_size, eoRng& _gen = rng)
{ {
return *inverse_deterministic_tournament(_pop.begin(), _pop.end(), _t_size, _gen); return *inverse_deterministic_tournament(_pop.begin(), _pop.end(), _t_size, _gen);
} }
template <class It> template <class It>
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 i1 = _begin + _gen.random(_end - _begin);
It i2 = _begin + _gen.random(_end - _begin); It i2 = _begin + _gen.random(_end - _begin);
bool return_better = _gen.flip(_t_rate); bool return_better = _gen.flip(_t_rate);
if (*i1 < *i2) if (*i1 < *i2)
{ {
if (return_better) return i2; if (return_better) return i2;
// else // else
return i1; return i1;
} }
else else
{ {
if (return_better) return i1; if (return_better) return i1;
// else // else
} }
// else // else
return i2; return i2;
} }
template <class EOT> template <class EOT>
const EOT& stochastic_tournament(const eoPop<EOT>& _pop, double _t_rate, eoRng& _gen = rng) const EOT& stochastic_tournament(const eoPop<EOT>& _pop, double _t_rate, eoRng& _gen = rng)
{ {
return *stochastic_tournament(_pop.begin(), _pop.end(), _t_rate, _gen); return *stochastic_tournament(_pop.begin(), _pop.end(), _t_rate, _gen);
} }
template <class EOT> template <class EOT>
EOT& stochastic_tournament(eoPop<EOT>& _pop, double _t_rate, eoRng& _gen = rng) EOT& stochastic_tournament(eoPop<EOT>& _pop, double _t_rate, eoRng& _gen = rng)
{ {
return *stochastic_tournament(_pop.begin(), _pop.end(), _t_rate, _gen); return *stochastic_tournament(_pop.begin(), _pop.end(), _t_rate, _gen);
} }
template <class It> template <class It>
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 i1 = _begin + _gen.random(_end - _begin);
It i2 = _begin + _gen.random(_end - _begin); It i2 = _begin + _gen.random(_end - _begin);
bool return_worse = _gen.flip(_t_rate); bool return_worse = _gen.flip(_t_rate);
if (*i1 < *i2) if (*i1 < *i2)
{ {
if (return_worse) return i1; if (return_worse) return i1;
// else // else
return i2; return i2;
} }
else else
{ {
if (return_worse) return i2; if (return_worse) return i2;
// else // else
} }
// else // else
return i1; return i1;
} }
template <class EOT> template <class EOT>
const EOT& inverse_stochastic_tournament(const eoPop<EOT>& _pop, double _t_rate, eoRng& _gen = rng) const EOT& inverse_stochastic_tournament(const eoPop<EOT>& _pop, double _t_rate, eoRng& _gen = rng)
{ {
return *inverse_stochastic_tournament(_pop.begin(), _pop.end(), _t_rate, _gen); return *inverse_stochastic_tournament(_pop.begin(), _pop.end(), _t_rate, _gen);
} }
template <class EOT> template <class EOT>
EOT& inverse_stochastic_tournament(eoPop<EOT>& _pop, double _t_rate, eoRng& _gen = rng) EOT& inverse_stochastic_tournament(eoPop<EOT>& _pop, double _t_rate, eoRng& _gen = rng)
{ {
return *inverse_stochastic_tournament(_pop.begin(), _pop.end(), _t_rate, _gen); return *inverse_stochastic_tournament(_pop.begin(), _pop.end(), _t_rate, _gen);
} }
#endif #endif