optimized eoProportional and added universalselect

This commit is contained in:
maartenkeijzer 2003-06-04 09:33:27 +00:00
commit a7b5d90f1b
2 changed files with 125 additions and 8 deletions

View file

@ -32,11 +32,13 @@
#include <utils/eoRNG.h>
#include <utils/selectors.h>
#include <eoSelectOne.h>
#include <eoPop.h>
//-----------------------------------------------------------------------------
/** eoProportionalSelect: select an individual proportional to her stored fitness
value
Changed the algorithm to make use of a cumulative array of fitness scores,
This changes the algorithm from O(n) per call to O(log n) per call. (MK)
*/
//-----------------------------------------------------------------------------
@ -44,8 +46,7 @@ template <class EOT> class eoProportionalSelect: public eoSelectOne<EOT>
{
public:
/// Sanity check
eoProportionalSelect(const eoPop<EOT>& pop = eoPop<EOT>()):
total((pop.size() == 0) ? -1.0 : sum_fitness(pop))
eoProportionalSelect(const eoPop<EOT>& pop = eoPop<EOT>())
{
if (minimizing_fitness<EOT>())
throw std::logic_error("eoProportionalSelect: minimizing fitness");
@ -53,18 +54,32 @@ public:
void setup(const eoPop<EOT>& _pop)
{
total = sum_fitness(_pop);
if (_pop.size() == 0) return;
cumulative.resize(_pop.size());
cumulative[0] = _pop[0].fitness();
for (unsigned i = 1; i < _pop.size(); ++i)
{
cumulative[i] = _pop[i].fitness() + cumulative[i-1];
}
}
/** do the selection, call roulette_wheel.
/** do the selection,
*/
const EOT& operator()(const eoPop<EOT>& _pop)
{
return roulette_wheel(_pop, total) ;
if (cumulative.size() == 0) setup(_pop);
double fortune = rng.uniform() * cumulative.back();
typename FitVec::iterator result = std::upper_bound(cumulative.begin(), cumulative.end(), fortune);
return _pop[result - cumulative.begin()];
}
private :
typename EOT::Fitness total;
typedef std::vector<typename EOT::Fitness> FitVec;
FitVec cumulative;
};
#endif