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.
This commit is contained in:
kuepper 2004-12-23 15:29:07 +00:00
commit 85a326c5e4
35 changed files with 1057 additions and 864 deletions

View file

@ -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<real> 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<neuron>
{
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<neuron>(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<unsigned>& hidden = std::vector<unsigned>())
{
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<unsigned>& 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<sample>
{
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<sample>(num_samples, sample(input_size, output_size)) {}
set(istream& is) : std::vector<sample>(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:

View file

@ -3,7 +3,7 @@
//-----------------------------------------------------------------------------
#include <stdlib.h> // EXIT_SUCCESS EXIT_FAILURE
#include <stdexcept> // exception
#include <stdexcept> // exception
#include <iostream> // cerr cout
#include <fstream> // ifstream
#include <string> // 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<Chrom> pop(pop_size.value(), init);
// evaluate population
eoEvalFuncPtr<Chrom> evaluator(eoChromEvaluator);
apply<Chrom>(evaluator, pop);
// selector
eoProportionalSelect<Chrom> select(pop);
// genetic operators
eoChromMutation mutation;
eoChromXover xover;
// stop condition
eoGenContinue<Chrom> continuator1(generations.value());
eoFitContinue<Chrom> continuator2(solution.fitness());
eoFitContinue<Chrom> continuator2(solution.fitness());
eoCombinedContinue<Chrom> continuator(continuator1, continuator2);
// checkpoint
eoCheckPoint<Chrom> checkpoint(continuator);
// monitor
eoStdoutMonitor monitor;
checkpoint.add(monitor);
// statistics
eoBestFitnessStat<Chrom> stats;
checkpoint.add(stats);
monitor.add(stats);
// genetic algorithm
eoSGA<Chrom> 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:

View file

@ -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<bool> specialization.
*/
template <class FitT> class eoVirus: public eoBit<FitT>
template <class FitT>
class eoVirus: public eoBit<FitT>
{
public:
public:
using eoBit<FitT>::begin;
using eoBit<FitT>::end;
using eoBit<FitT>::size;
/**
* (Default) Constructor.
@ -110,3 +116,9 @@ template <class FitT> class eoVirus: public eoBit<FitT>
//-----------------------------------------------------------------------------
#endif //eoBit_h
// Local Variables:
// mode: C++
// c-file-style: "Stroustrup"
// End:

View file

@ -46,16 +46,14 @@
template <class EoType>
class eoDominanceMap : public eoUF<const eoPop<EoType>&, void>, public std::vector<std::vector<bool> >
{
public :
public:
/**
Clears the map
*/
void clear()
{
std::vector<std::vector<bool> >::clear();
fitnesses.clear();
}
/** Clears the map */
void clear() {
std::vector<std::vector<bool> >::clear();
#warning Is this correct? Was: "fitnesses.clear()"
fitness.clear();
}
/**
Update or create the dominance map

View file

@ -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 EOT>
class eoLinearFitScaling : public eoPerf2Worth<EOT> // 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<EOT>& _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<double> (_pop.best_element().fitness());
// double worstFitness = static_cast<double> (_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<pSize; i++)
sum += static_cast<double>(_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<EOT>& _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<double> (_pop.best_element().fitness());
// double worstFitness = static_cast<double> (_pop.worse_element().fitness());
for (i=0; i<pSize; i++) // truncate to 0
{
value()[i] = std::max(alpha*_pop[i].fitness()+beta, 0.0);
}
// average fitness
double sum=0.0;
unsigned i;
for (i=0; i<pSize; i++)
sum += static_cast<double>(_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<pSize; i++) { // truncate to 0
value()[i] = std::max(alpha*_pop[i].fitness()+beta, 0.0);
}
}
private:
double pressure; // selective pressure
private:
double pressure; // selective pressure
};

View file

@ -41,11 +41,14 @@
template <class EOT>
class eoNDSorting : public eoPerf2WorthCached<EOT, double>
{
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<EOT, double>
{
// 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<EOT, double>
}
}
}
private :
/** used in fast nondominated sorting
@ -90,7 +93,7 @@ private :
};
void one_objective(const eoPop<EOT>& _pop)
{
{
unsigned i;
std::vector<DummyEO> 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<DummyEO>());
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<EOT>& _pop)
{
{
unsigned i;
typedef typename EOT::Fitness::fitness_traits traits;
assert(traits::nObjectives() == 2);
std::vector<unsigned> 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<double> d;
d.resize(_pop.size(), max1); // initialize with the value max1 everywhere
std::vector<std::vector<unsigned> > 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<double>::iterator it =
std::vector<double>::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<double> 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<EOT>& _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<EOT>& pop;
};
void m_objectives(const eoPop<EOT>& _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 EOT>
class eoNDSorting_II : public eoNDSorting<EOT>
{
public:
public:
typedef std::pair<double, unsigned> double_index_pair;
typedef std::pair<double, unsigned> double_index_pair;
class compare_nodes
{
@ -441,7 +449,7 @@ class eoNDSorting_II : public eoNDSorting<EOT>
unsigned i;
std::vector<double> niche_count(_cf.size(), 0.);
unsigned nObjectives = traits::nObjectives(); //_pop[_cf[0]].fitness().size();
for (unsigned o = 0; o < nObjectives; ++o)

View file

@ -87,55 +87,57 @@ class eoOpContainer : public eoGenOp<EOT>
template <class EOT>
class eoSequentialOp : public eoOpContainer<EOT>
{
public :
typedef unsigned position_type;
public:
using eoOpContainer< EOT >::ops;
using eoOpContainer< EOT >::rates;
typedef unsigned position_type;
void apply(eoPopulator<EOT>& _pop)
{
position_type pos = _pop.tellp();
void apply(eoPopulator<EOT>& _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<EOT>::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<EOT>::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<size_t> to_apply;
std::vector<size_t> production;
std::vector<size_t> to_apply;
std::vector<size_t> production;
};
/** The proportional versions: easy! */
template <class EOT>
class eoProportionalOp : public eoOpContainer<EOT>
{
public :
public:
using eoOpContainer< EOT >::ops;
using eoOpContainer< EOT >::rates;
void apply(eoPopulator<EOT>& _pop)
{

View file

@ -39,10 +39,13 @@
template <class EOT>
class eoParetoRanking : public eoPerf2WorthCached<EOT, double>
{
public :
public:
eoParetoRanking(eoDominanceMap<EOT>& _dominanceMap) :
eoPerf2WorthCached<EOT, double>(), dominanceMap(_dominanceMap) {}
using eoParetoRanking< EOT>::value;
eoParetoRanking(eoDominanceMap<EOT>& _dominanceMap)
: eoPerf2WorthCached<EOT, double>(), dominanceMap(_dominanceMap)
{}
void calculate_worths(const eoPop<EOT>& _pop)
{

View file

@ -35,20 +35,24 @@
#include <vector>
#include <string>
/** 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 EOT, class WorthT = double>
class eoPerf2Worth : public eoUF<const eoPop<EOT>&, void>, public eoValueParam<std::vector<WorthT> >
{
public:
eoPerf2Worth(std::string _description = "Worths"):eoValueParam<std::vector<WorthT> >(std::vector<WorthT>(0),
_description) {}
public:
/**
Sort population according to worth, will keep the worths and fitness_cache in sync with the population.
*/
using eoPerf2Worth<EOT, WorthT>::value;
/** @brief default constructor */
eoPerf2Worth(std::string _description = "Worths")
: eoValueParam<std::vector<WorthT> >(std::vector<WorthT>(0), _description)
{}
/** Sort population according to worth, will keep the worths and
fitness_cache in sync with the population. */
virtual void sort_pop(eoPop<EOT>& _pop)
{ // start with a std::vector of indices
std::vector<unsigned> indices(_pop.size());
@ -75,28 +79,28 @@ class eoPerf2Worth : public eoUF<const eoPop<EOT>&, void>, public eoValueParam<s
std::swap(value(), tmp_worths);
}
/** helper class used to sort indices into populations/worths
*/
class compare_worth
{
public :
compare_worth(const std::vector<WorthT>& _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<WorthT>& _worths) : worths(_worths) {}
const std::vector<WorthT>& worths;
};
bool operator()(unsigned a, unsigned b) const {
return worths[b] < worths[a]; // sort in descending (!) order
}
virtual void resize(eoPop<EOT>& _pop, unsigned sz)
{
_pop.resize(sz);
value().resize(sz);
}
private:
const std::vector<WorthT>& worths;
};
virtual void resize(eoPop<EOT>& _pop, unsigned sz) {
_pop.resize(sz);
value().resize(sz);
};
};
@ -106,8 +110,11 @@ Perf2Worth with fitness cache
template <class EOT, class WorthT = typename EOT::Fitness>
class eoPerf2WorthCached : public eoPerf2Worth<EOT, WorthT>
{
public:
eoPerf2WorthCached(std::string _description = "Worths") : eoPerf2Worth<EOT, WorthT>(_description) {}
public:
using eoPerf2Worth<EOT, WorthT>::value;
eoPerf2WorthCached(std::string _description = "Worths") : eoPerf2Worth<EOT, WorthT>(_description) {}
/**
@ -164,7 +171,7 @@ class eoPerf2WorthCached : public eoPerf2Worth<EOT, WorthT>
indices[i] = i;
}
std::sort(indices.begin(), indices.end(), eoPerf2Worth<EOT,WorthT>::compare_worth(value()));
std::sort(indices.begin(), indices.end(), compare_worth(value()));
eoPop<EOT> tmp_pop;
tmp_pop.resize(_pop.size());
@ -216,22 +223,25 @@ class eoPerf2WorthCached : public eoPerf2Worth<EOT, WorthT>
std::vector <typename EOT::Fitness> fitness_cache;
};
/**
A dummy perf2worth, just in case you need it
*/
/** A dummy perf2worth, just in case you need it */
template <class EOT>
class eoNoPerf2Worth : public eoPerf2Worth<EOT, typename EOT::Fitness>
{
public:
public:
using eoValueParam< EOT >::value;
// default behaviour, just copy fitnesses
void operator()(const eoPop<EOT>& _pop)
{
unsigned i;
value.resize(_pop.size());
for (i = 0; i < _pop.size(); ++i)
value()[i]=_pop[i];
void operator()(const eoPop<EOT>& _pop) {
unsigned i;
value().resize(_pop.size());
for (i = 0; i < _pop.size(); ++i)
value()[i]=_pop[i];
}
};
#endif

View file

@ -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<EOT>& dest;
typename eoPop<EOT>::iterator current;
const eoPop<EOT>& src;
protected:
eoPop<EOT>& dest;
typename eoPop<EOT>::iterator current;
const eoPop<EOT>& 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 EOT>
class eoSeqPopulator : public eoPopulator<EOT>
{
public :
public:
eoSeqPopulator(const eoPop<EOT>& _pop, eoPop<EOT>& _dest) :
eoPopulator<EOT>(_pop, _dest), current(0) {}
eoSeqPopulator(const eoPop<EOT>& _pop, eoPop<EOT>& _dest) :
eoPopulator<EOT>(_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 EOT>
class eoSelectivePopulator : public eoPopulator<EOT>
{
public :
eoSelectivePopulator(const eoPop<EOT>& _pop, eoPop<EOT>& _dest, eoSelectOne<EOT>& _sel)
: eoPopulator<EOT>(_pop, _dest), sel(_sel)
{
sel.setup(_pop);
using eoPopulator< EOT >::src;
eoSelectivePopulator(const eoPop<EOT>& _pop, eoPop<EOT>& _dest, eoSelectOne<EOT>& _sel)
: eoPopulator<EOT>(_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<EOT>& sel;
private:
eoSelectOne<EOT>& sel;
};
#endif

View file

@ -38,6 +38,9 @@ template <class EOT>
class eoRanking : public eoPerf2Worth<EOT> // 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;
}

View file

@ -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<std::string>::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<std::string> getDescriptionVector() { return TermDescriptions; }
private:
static std::vector<std::string> TermDescriptions;
};
@ -80,7 +80,7 @@ private:
maximizing (using less<ScalarType>) or minimizing (using greater<ScalarType>).
- 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 ScalarType, class Compare, class FitnessTraits >
class eoScalarFitnessAssembled : public std::vector<ScalarType> {
public:
using std::vector< ScalarType >::empty;
using std::vector< ScalarType >::front;
using std::vector< ScalarType >::size;
typedef typename std::vector<ScalarType> 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<std::string> 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<F, Cmp
{
for (unsigned i=0; i < f.size(); ++i)
os << f[i] << " ";
os << f.feasible << " ";
os << f.failed << " ";
return os;
}
@ -252,10 +257,10 @@ std::istream& operator>>(std::istream& is, eoScalarFitnessAssembled<F, Cmp, Fitn
is >> value;
f[i] = value;
}
is >> f.feasible;
is >> f.failed;
return is;
}

View file

@ -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 <utils/selectors.h>
//-----------------------------------------------------------------------------
/** 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 EOT, class WorthType = double>
class eoSelectFromWorth : public eoSelectOne<EOT>
{
public:
/* Default ctor from an eoPerf2Worth object
*/
eoSelectFromWorth(eoPerf2Worth<EOT, WorthType> & _perf2Worth) :
perf2Worth(_perf2Worth) {}
/* setup the worthes */
virtual void setup(const eoPop<EOT>& _pop)
{
perf2Worth(_pop);
/* Default ctor from an eoPerf2Worth object */
eoSelectFromWorth(eoPerf2Worth<EOT, WorthType>& _perf2Worth)
: perf2Worth(_perf2Worth)
{}
/* setup the worthes */
virtual void setup(const eoPop<EOT>& 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<EOT, WorthType> & perf2Worth;
eoPerf2Worth<EOT, WorthType>& perf2Worth;
#ifndef NDEBUG
std::vector<typename EOT::Fitness> 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<typename EOT::Fitness> 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 EOT, class WorthT = double>
class eoDetTournamentWorthSelect : public eoSelectFromWorth<EOT, WorthT>
{
public:
typedef typename std::vector<WorthT>::iterator worthIterator;
/* Default ctor from an eoPerf2Worth object + tournament size
*/
eoDetTournamentWorthSelect(eoPerf2Worth<EOT, WorthT> &_perf2Worth,
unsigned _tSize) :
eoSelectFromWorth<EOT, WorthT>(_perf2Worth), tSize(_tSize) {}
using eoSelectFromWorth<EOT, WorthT>::perf2Worth;
/* Perform deterministic tournament on worthes
by calling the appropriate fn
see selectors.h
*/
virtual const EOT& operator()(const eoPop<EOT>& _pop)
{
worthIterator it = deterministic_tournament(
perf2Worth.value().begin(),
perf2Worth.value().end(), tSize);
typedef typename std::vector<WorthT>::iterator worthIterator;
unsigned index = it - perf2Worth.value().begin();
/* Default ctor from an eoPerf2Worth object + tournament size */
eoDetTournamentWorthSelect(eoPerf2Worth<EOT, WorthT>& perf2Worth,
unsigned _tSize)
: eoSelectFromWorth<EOT, WorthT>(perf2Worth), tSize(_tSize) {}
/* Perform deterministic tournament on worthes by calling the
appropriate fn see selectors.h */
virtual const EOT& operator()(const eoPop<EOT>& 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 EOT, class WorthT = double>
class eoStochTournamentWorthSelect : public eoSelectFromWorth<EOT, WorthT>
{
public:
typedef typename std::vector<WorthT>::iterator worthIterator;
/* Default ctor from an eoPerf2Worth object + tournament rate
*/
eoStochTournamentWorthSelect(eoPerf2Worth<EOT, WorthT> &_perf2Worth,
double _tRate) :
eoSelectFromWorth<EOT, WorthT>(_perf2Worth), tRate(_tRate) {}
using eoSelectFromWorth<EOT, WorthT>::perf2Worth;
typedef typename std::vector<WorthT>::iterator worthIterator;
/* Default ctor from an eoPerf2Worth object + tournament rate */
eoStochTournamentWorthSelect(eoPerf2Worth<EOT, WorthT> &_perf2Worth, double _tRate)
: eoSelectFromWorth<EOT, WorthT>(_perf2Worth), tRate(_tRate)
{}
/* Perform stochastic tournament on worthes
by calling the appropriate fn in selectors.h
*/
virtual const EOT& operator()(const eoPop<EOT>& _pop)
{
worthIterator it = stochastic_tournament(
perf2Worth.value().begin(),
perf2Worth.value().end(), tRate);
virtual const EOT& operator()(const eoPop<EOT>& _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 EOT, class WorthT = double>
class eoRouletteWorthSelect : public eoSelectFromWorth<EOT, WorthT>
{
public:
typedef typename std::vector<WorthT>::iterator worthIterator;
/* Default ctor from an eoPerf2Worth object
*/
eoRouletteWorthSelect(eoPerf2Worth<EOT, WorthT> &_perf2Worth) :
eoSelectFromWorth<EOT, WorthT>(_perf2Worth) {}
using eoSelectFromWorth<EOT, WorthT>::perf2Worth;
typedef typename std::vector<WorthT>::iterator worthIterator;
/* Default ctor from an eoPerf2Worth object */
eoRouletteWorthSelect(eoPerf2Worth<EOT, WorthT> &_perf2Worth)
: eoSelectFromWorth<EOT, WorthT>(_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<EOT>& _pop)
{
// cout << "On affiche les worths\n";
// for (unsigned i=0;
// i<perf2Worth.value().size();
// i++)
// cout << perf2Worth.value().operator[](i) << "\n";
// cout << endl;
worthIterator it = roulette_wheel(
perf2Worth.value().begin(),
perf2Worth.value().end(),
total);
virtual const EOT& operator()(const eoPop<EOT>& _pop) {
// cout << "On affiche les worths\n";
// for (unsigned i=0;
// i<perf2Worth.value().size();
// i++)
// cout << perf2Worth.value().operator[](i) << "\n";
// cout << endl;
worthIterator it = roulette_wheel(perf2Worth.value().begin(),
perf2Worth.value().end(),
total);
unsigned index = it - perf2Worth.value().begin();
@ -216,7 +213,7 @@ public:
#endif
return _pop[index];
return _pop[it-perf2Worth.value().begin()];
return _pop[it - perf2Worth.value().begin()];
}
private:

View file

@ -29,7 +29,7 @@
#include <eoPerf2Worth.h>
#include <utils/eoDistance.h>
/** 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 EOT>
class eoSharing : public eoPerf2Worth<EOT>
{
public:
public:
using eoSharing< EOT >::value;
/* Ctor requires a distance - cannot have a default distance! */
eoSharing(double _nicheSize, eoDistance<EOT> & _dist) : eoPerf2Worth<EOT>("Sharing"),
nicheSize(_nicheSize),
eoSharing(double _nicheSize, eoDistance<EOT> & _dist) : eoPerf2Worth<EOT>("Sharing"),
nicheSize(_nicheSize),
dist(_dist)
{}
@ -89,7 +93,7 @@ class eoSharing : public eoPerf2Worth<EOT>
*/
void operator()(const eoPop<EOT>& _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<EOT>
for (j=0; j<i; j++)
{
double d = dist(_pop[i], _pop[j]);
distMatrix(i,j) =
distMatrix(i,j) =
distMatrix(j,i) = ( d>nicheSize ? 0 : 1-(d/nicheSize) );
}
}
@ -123,7 +127,7 @@ class eoSharing : public eoPerf2Worth<EOT>
value()[i]=_pop[i].fitness()/sim[i];
}
// private data of class eoSharing
private:
private:
double nicheSize;
eoDistance<EOT> & dist; // specific distance
};

View file

@ -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<EOT> &, eoPop<EOT> &, 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 EOT>
class eoDeterministicSurviveAndDie : public eoSurviveAndDie<EOT>
{
public:
eoDeterministicSurviveAndDie(double _survive, double _die,
bool _interpret_as_rate = true):
eoSurviveAndDie<EOT>(_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<EOT> & _pop, eoPop<EOT> & _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 EOT>
class eoDeterministicSaDReplacement : public eoReplacement<EOT>
{
public:
/** Constructor with reduce */
eoDeterministicSaDReplacement(eoReduce<EOT>& _reduceGlobal,
double _surviveParents, double _dieParents=0,
/** Constructor with reduce */
eoDeterministicSaDReplacement(eoReduce<EOT>& _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)
{}

View file

@ -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 FitT, class GeneType>
class eoVector : public EO<FitT>, public std::vector<GeneType>
{
public :
public:
using EO<FitT>::invalidate;
using std::vector<GeneType>::operator[];
using std::vector<GeneType>::begin;
using std::vector<GeneType>::end;
using std::vector<GeneType>::resize;
using std::vector<GeneType>::size;
typedef GeneType AtomType;
typedef std::vector<GeneType> ContainerType;
/** default constructor
eoVector(unsigned size = 0, GeneType value = GeneType()) : EO<FitT>(), std::vector<GeneType>(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<FitT>(), std::vector<GeneType>(size, value)
{}
/// copy ctor abstracting from the FitT
template <class OtherFitnessType>

View file

@ -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 Fit>
class eoEsFull : public eoVector<Fit, double>
{
public :
public:
using eoEsFull< Fit >::size;
typedef double Type;
eoEsFull(void) : eoVector<Fit, double>() {}

View file

@ -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 Fit>
class eoEsStdev : public eoVector<Fit, double>
{
public :
public:
using eoEsStdev< Fit >::size;
typedef double Type;

View file

@ -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 EOT> class eoNormalVecMutation: public eoMonOp<EOT>
*/
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<bounds.size(); i++)
@ -105,7 +105,7 @@ private:
};
/** 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.
@ -113,9 +113,10 @@ private:
* but this sometimes takes a long time!!!
*/
template<class EOT> class eoNormalMutation: public eoMonOp<EOT>
template<class EOT> class eoNormalMutation
: public eoMonOp<EOT>
{
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 EOT> class eoOneFifthMutation :
template<class EOT> class eoOneFifthMutation :
public eoNormalMutation<EOT>, 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<EOT> & _eval, double & _sigmaInit,
eoOneFifthMutation(eoEvalFunc<EOT> & _eval, double & _sigmaInit,
unsigned _windowSize = 10, double _updateFactor=0.83,
double _threshold=0.2):
eoNormalMutation<EOT>(_sigmaInit), eval(_eval),
threshold(_threshold), updateFactor(_updateFactor),
nbMut(_windowSize, 0), nbSuccess(_windowSize, 0), genIndex(0)
double _threshold=0.2):
eoNormalMutation<EOT>(_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<EOT> & eval;
double threshold; // 1/5 !
double updateFactor ; // the multiplicative factor
std::vector<unsigned> nbMut; // total number of mutations per gen
std::vector<unsigned> nbMut; // total number of mutations per gen
std::vector<unsigned> nbSuccess; // number of successful mutations per gen
unsigned genIndex ; // current index in std::vectors (circular)
};

View file

@ -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 FitT> class eoBit: public eoVector<FitT, bool>
{
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 FitT> class eoBit: public eoVector<FitT, bool>
//-----------------------------------------------------------------------------
#endif //eoBit_h
// Local Variables:
// mode: C++
// c-file-style: "Stroustrup"
// End:

Some files were not shown because too many files have changed in this diff Show more