(re)moving...
This commit is contained in:
parent
2620c402bc
commit
2e6d406d8e
19 changed files with 0 additions and 3516 deletions
109
eo/src/eoAged.h
109
eo/src/eoAged.h
|
|
@ -1,109 +0,0 @@
|
|||
// eoAged.h
|
||||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoAge.h
|
||||
// (c) GeNeura Team, 1998
|
||||
/*
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
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
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef EOAGED_H
|
||||
#define EOAGED_H
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#include <iostream> // istream, ostream
|
||||
#include <string> // para string
|
||||
|
||||
using namespace std;
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoAge
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
/** eoAge is a template class that adds an age to an object.\\
|
||||
Requisites for template instantiation are that the object must admit a default ctor
|
||||
and a copy ctor. The Object must be an eoObject, thus, it must have its methods: className,
|
||||
printOn, readFrom.
|
||||
@see eoObject
|
||||
*/
|
||||
template <class Object>
|
||||
class eoAged: public Object
|
||||
{
|
||||
public:
|
||||
/// Main ctor from an already built Object.
|
||||
eoAged( const Object& _o): Object( _o ), age(0) {};
|
||||
|
||||
/// Copy constructor.
|
||||
eoAged( const eoAged& _a): Object( _a ), age( _a.age ) {};
|
||||
|
||||
/// Virtual dtor. They are needed in virtual class hierarchies
|
||||
virtual ~eoAged() {};
|
||||
|
||||
|
||||
///returns the age of the object
|
||||
unsigned long Age() const {return age;}
|
||||
|
||||
/// Increments age
|
||||
const eoAged& operator ++ () { age++; return *this;}
|
||||
|
||||
/** @name Methods from eoObject
|
||||
readFrom and printOn are directly inherited from eo1d
|
||||
*/
|
||||
//@{
|
||||
/** Return the class id. This should be redefined in each class; but
|
||||
it's got code as an example of implementation. Only "leaf" classes
|
||||
can be non-virtual.
|
||||
*/
|
||||
virtual string className() const { return string("eoAged")+Object::className(); };
|
||||
|
||||
/**
|
||||
* Read object.
|
||||
* @param _is A istream.
|
||||
* @throw runtime_exception If a valid object can't be read.
|
||||
*/
|
||||
virtual void readFrom(istream& _is) {
|
||||
Object::readFrom( _is );
|
||||
_is >> age;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Write object. It's called printOn since it prints the object _on_ a stream.
|
||||
* @param _os A ostream.
|
||||
*/
|
||||
virtual void printOn(ostream& _os) const{
|
||||
Object::printOn( _os );
|
||||
_os << age;
|
||||
}
|
||||
//@}
|
||||
|
||||
private:
|
||||
|
||||
/** Default Constructor. \\
|
||||
It´s private so that it is not used anywhere; the right way of using this object
|
||||
is to create an Object and passing it to an aged by means of the copy ctor; that way
|
||||
it´s turned into an Aged object*/
|
||||
eoAged(): Object(), age(0) {};
|
||||
|
||||
unsigned long age;
|
||||
};
|
||||
|
||||
#endif EOAGE_H
|
||||
|
||||
|
|
@ -1,93 +0,0 @@
|
|||
/*
|
||||
eoBin.h
|
||||
(c) GeNeura Team 1998
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
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
|
||||
*/
|
||||
|
||||
#ifndef eoBin_h
|
||||
#define eoBin_h
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#include <iostream> // ostream, istream
|
||||
#include <functional> // bind2nd
|
||||
#include <string> // string
|
||||
#include <eoVector.h> // EO
|
||||
|
||||
/** eoBin: implementation of binary chromosome.
|
||||
* based on STL's bit_vector (vector<bool>).
|
||||
*/
|
||||
template <class F> class eoBin: public eoVector<bool, F>
|
||||
{
|
||||
public:
|
||||
|
||||
/**
|
||||
* (Default) Constructor.
|
||||
* @param size Size of the binary string.
|
||||
*/
|
||||
eoBin(unsigned size = 0, bool value = false):
|
||||
eoVector<bool,F>(size, value) {}
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
* @param size Size of the binary string.
|
||||
*/
|
||||
eoBin(unsigned size, const eoRnd<bool>& rnd): eoVector<bool,F>(size)
|
||||
{
|
||||
generate(begin(), end(), rnd);
|
||||
}
|
||||
|
||||
/** Constructor from istream.
|
||||
@param is The istream to read from.*/
|
||||
eoBin(istream& _is):eoVector<bool,F>(_is){};
|
||||
|
||||
/// My class name.
|
||||
string className() const
|
||||
{
|
||||
return "eoBin";
|
||||
}
|
||||
|
||||
/**
|
||||
* To print me on a stream.
|
||||
* @param os The ostream.
|
||||
*/
|
||||
void printOn(ostream& os) const
|
||||
{
|
||||
copy(begin(), end(), ostream_iterator<bool>(os));
|
||||
}
|
||||
|
||||
/**
|
||||
* To read me from a stream.
|
||||
* @param is The istream.
|
||||
*/
|
||||
void readFrom(istream& is)
|
||||
{
|
||||
string bits;
|
||||
is >> bits;
|
||||
if (is)
|
||||
{
|
||||
resize(bits.size());
|
||||
transform(bits.begin(), bits.end(), begin(),
|
||||
bind2nd(equal_to<char>(), '1'));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#endif eoBin_h
|
||||
325
eo/src/eoBitOp.h
325
eo/src/eoBitOp.h
|
|
@ -1,325 +0,0 @@
|
|||
//-----------------------------------------------------------------------------
|
||||
// eoBitOp.h
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef eoBitOp_h
|
||||
#define eoBitOp_h
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#include <algorithm> // swap_ranges
|
||||
#include <eoUniform.h> // eoUniform
|
||||
#include <eoBin.h> // eoBin
|
||||
#include <eoOp.h> // eoMonOp
|
||||
|
||||
|
||||
/** @name BitWise Genetic operators
|
||||
|
||||
Even as these operators might seem general, they are particular versions of genetic
|
||||
operators useful only for binary operators. As any set of genetic operators, it must
|
||||
have a factory that knows how to build them from a description
|
||||
@author GeNeura Team
|
||||
@version 0.1
|
||||
@see eoBin
|
||||
@see eoBitOpFactory
|
||||
*/
|
||||
|
||||
//@{
|
||||
|
||||
/** eoBinRandom --> mofify a chromosome in a random way */
|
||||
|
||||
template<class Chrom> class eoBinRandom: public eoMonOp<Chrom>
|
||||
{
|
||||
public:
|
||||
/// The class name.
|
||||
string className() const { return "eoBinRandom"; }
|
||||
|
||||
/**
|
||||
* Randomizes a cromosome.
|
||||
* @param chrom The cromosome to be randomize.
|
||||
*/
|
||||
void operator()(Chrom& chrom) const
|
||||
{
|
||||
eoUniform<float> uniform(0.0, 1.0);
|
||||
for (unsigned i = 0; i < chrom.size(); i++)
|
||||
chrom[i] = (uniform() < 0.5) ? false : true;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/** eoBinBitFlip --> chages a bit */
|
||||
|
||||
template<class Chrom> class eoBinBitFlip: public eoMonOp<Chrom>
|
||||
{
|
||||
public:
|
||||
/// The class name.
|
||||
string className() const { return "eoBinBitFlip"; }
|
||||
|
||||
/**
|
||||
* Change one bit.
|
||||
* @param chrom The cromosome which one bit is going to be changed.
|
||||
*/
|
||||
void operator()(Chrom& chrom) const
|
||||
{
|
||||
eoUniform<int> uniform(0, chrom.size());
|
||||
unsigned i = uniform();
|
||||
chrom[i] = (chrom[i]) ? false : true;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/** eoBinMutation --> classical mutation */
|
||||
|
||||
template<class Chrom> class eoBinMutation: public eoMonOp<Chrom>
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* (Default) Constructor.
|
||||
* @param _rate Rate of mutation.
|
||||
*/
|
||||
eoBinMutation(const double& _rate = 0.01): rate(_rate), uniform(0.0, 1.0) {}
|
||||
|
||||
/// The class name.
|
||||
string className() const { return "eoBinMutation"; }
|
||||
|
||||
/**
|
||||
* Mutate a chromosome.
|
||||
* @param chrom The chromosome to be mutated.
|
||||
*/
|
||||
void operator()(Chrom& chrom) const
|
||||
{
|
||||
for (unsigned i = 0; i < chrom.size(); i++)
|
||||
if (uniform() < rate)
|
||||
chrom[i] = !chrom[i];
|
||||
}
|
||||
|
||||
private:
|
||||
double rate;
|
||||
mutable eoUniform<float> uniform;
|
||||
};
|
||||
|
||||
|
||||
/** eoBinInversion: inverts the bits of the chromosome between an interval */
|
||||
|
||||
template<class Chrom> class eoBinInversion: public eoMonOp<Chrom>
|
||||
{
|
||||
public:
|
||||
/// The class name.
|
||||
string className() const { return "eoBinInversion"; }
|
||||
|
||||
/**
|
||||
* Inverts a range of bits in a binary chromosome.
|
||||
* @param chrom The chromosome whos bits are going to be inverted (a range).
|
||||
*/
|
||||
void operator()(Chrom& chrom) const
|
||||
{
|
||||
eoUniform<unsigned> uniform(0, chrom.size() + 1);
|
||||
|
||||
unsigned u1 = uniform(), u2;
|
||||
do u2 = uniform(); while (u1 == u2);
|
||||
unsigned r1 = min(u1, u2), r2 = max(u1, u2);
|
||||
|
||||
reverse(chrom.begin() + r1, chrom.begin() + r2);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/** eoBinNext --> next binary value */
|
||||
|
||||
template<class Chrom> class eoBinNext: public eoMonOp<Chrom>
|
||||
{
|
||||
public:
|
||||
/// The class name.
|
||||
string className() const { return "eoBinNext"; }
|
||||
|
||||
/**
|
||||
* Change the bit string x to be x+1.
|
||||
* @param chrom The chromosome to be added one.
|
||||
*/
|
||||
void operator()(Chrom& chrom) const
|
||||
{
|
||||
for (int i = chrom.size() - 1; i >= 0; i--)
|
||||
if (chrom[i])
|
||||
{
|
||||
chrom[i] = 0;
|
||||
continue;
|
||||
}
|
||||
else
|
||||
{
|
||||
chrom[i] = 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/** eoBinPrev --> previos binary value */
|
||||
|
||||
template<class Chrom> class eoBinPrev: public eoMonOp<Chrom>
|
||||
{
|
||||
public:
|
||||
/// The class name.
|
||||
string className() const { return "eoBinPrev"; }
|
||||
|
||||
/**
|
||||
* Change the bit string x to be x-1.
|
||||
* @param chrom The chromosome to be substracted one.
|
||||
*/
|
||||
void operator()(Chrom& chrom) const
|
||||
{
|
||||
for (int i = chrom.size() - 1; i >= 0; i--)
|
||||
if (chrom[i])
|
||||
{
|
||||
chrom[i] = 0;
|
||||
break;
|
||||
}
|
||||
else
|
||||
{
|
||||
chrom[i] = 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/** eoBinCrossover --> classic crossover */
|
||||
|
||||
template<class Chrom> class eoBinCrossover: public eoQuadraticOp<Chrom>
|
||||
{
|
||||
public:
|
||||
/// The class name.
|
||||
string className() const { return "eoBinCrossover"; }
|
||||
|
||||
/**
|
||||
* 2-point crossover for binary chromosomes.
|
||||
* @param chrom1 The first chromosome.
|
||||
* @param chrom2 The first chromosome.
|
||||
*/
|
||||
void operator()(Chrom& chrom1, Chrom& chrom2) const
|
||||
{
|
||||
eoUniform<unsigned> uniform(1, min(chrom1.size(), chrom2.size()));
|
||||
swap_ranges(chrom1.begin(), chrom1.begin() + uniform(), chrom2.begin());
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/** eoBinNxOver --> n-point crossover */
|
||||
|
||||
template<class Chrom> class eoBinNxOver: public eoQuadraticOp<Chrom>
|
||||
{
|
||||
public:
|
||||
/// (Defualt) Constructor.
|
||||
eoBinNxOver(const unsigned& _num_points = 2): num_points(_num_points)
|
||||
{
|
||||
if (num_points < 1)
|
||||
runtime_error("NxOver --> invalid number of points");
|
||||
}
|
||||
|
||||
/// The class name.
|
||||
string className() const { return "eoBinNxOver"; }
|
||||
|
||||
/**
|
||||
* n-point crossover for binary chromosomes.
|
||||
* @param chrom1 The first chromosome.
|
||||
* @param chrom2 The first chromosome.
|
||||
*/
|
||||
void operator()(Chrom& chrom1, Chrom& chrom2) const
|
||||
{
|
||||
unsigned max_size = min(chrom1.size(), chrom2.size());
|
||||
unsigned max_points = min(max_size - 1, num_points);
|
||||
|
||||
vector<bool> points(max_size, false);
|
||||
eoUniform<unsigned> uniform(1, max_size);
|
||||
|
||||
// select ranges of bits to swap
|
||||
do {
|
||||
unsigned bit = uniform();
|
||||
if (points[bit])
|
||||
continue;
|
||||
else
|
||||
{
|
||||
points[bit] = true;
|
||||
max_points--;
|
||||
}
|
||||
} while (max_points);
|
||||
|
||||
|
||||
// swap bits between chromosomes
|
||||
bool change = false;
|
||||
for (unsigned bit = 1; bit < points.size(); bit++)
|
||||
{
|
||||
if (points[bit])
|
||||
change = !change;
|
||||
|
||||
if (change)
|
||||
swap(chrom1[bit], chrom2[bit]);
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
unsigned num_points;
|
||||
};
|
||||
|
||||
|
||||
/** eoBinGxOver --> gene crossover */
|
||||
|
||||
template<class Chrom> class eoBinGxOver: public eoQuadraticOp<Chrom>
|
||||
{
|
||||
public:
|
||||
/// Constructor.
|
||||
eoBinGxOver(const unsigned _gene_size, const unsigned _num_points = 2):
|
||||
gene_size(_gene_size), num_points(_num_points)
|
||||
{
|
||||
if (gene_size < 1)
|
||||
runtime_error("GxOver --> invalid gene size");
|
||||
if (num_points < 1)
|
||||
runtime_error("GxOver --> invalid number of points");
|
||||
}
|
||||
|
||||
/// The class name
|
||||
string className() const { return "eoBinGxOver"; }
|
||||
|
||||
/**
|
||||
* Gene crossover for binary chromosomes.
|
||||
* @param chrom1 The first chromosome.
|
||||
* @param chrom2 The first chromosome.
|
||||
*/
|
||||
void operator()(Chrom& chrom1, Chrom& chrom2) const
|
||||
{
|
||||
unsigned max_genes = min(chrom1.size(), chrom2.size()) / gene_size;
|
||||
unsigned cut_genes = min(max_genes, num_points);
|
||||
|
||||
vector<bool> points(max_genes, false);
|
||||
eoUniform<unsigned> uniform(0, max_genes);
|
||||
|
||||
// selects genes to swap
|
||||
do {
|
||||
unsigned bit = uniform();
|
||||
if (points[bit])
|
||||
continue;
|
||||
else
|
||||
{
|
||||
points[bit] = true;
|
||||
cut_genes--;
|
||||
}
|
||||
} while (cut_genes);
|
||||
|
||||
// swaps genes
|
||||
for (unsigned i = 0; i < points.size(); i++)
|
||||
if (points[i])
|
||||
swap_ranges(chrom1.begin() + i * gene_size,
|
||||
chrom1.begin() + i * gene_size + gene_size,
|
||||
chrom2.begin() + i * gene_size);
|
||||
}
|
||||
|
||||
private:
|
||||
unsigned gene_size;
|
||||
unsigned num_points;
|
||||
};
|
||||
|
||||
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
//@}
|
||||
#endif eoBitOp_h
|
||||
|
||||
|
|
@ -1,120 +0,0 @@
|
|||
// eoBitOpFactory.h
|
||||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoOpFactory.h
|
||||
// (c) GeNeura Team, 1998
|
||||
/*
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
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
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _EOBITOPFACTORY_H
|
||||
#define _EOBITOPFACTORY_H
|
||||
|
||||
#include <eoOpFactory.h>
|
||||
#include <eoBitOp.h>
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
/** EO Factory. An instance of the factory class to create operators that act
|
||||
on bitstring chromosomes. Only those chromosomes can instantiate the operators
|
||||
that are created here
|
||||
@see eoSelect*/
|
||||
template< class EOT>
|
||||
class eoBitOpFactory: public eoOpFactory<EOT> {
|
||||
|
||||
public:
|
||||
|
||||
/// @name ctors and dtors
|
||||
//{@
|
||||
/// constructor
|
||||
eoBitOpFactory( ) {};
|
||||
|
||||
/// destructor
|
||||
virtual ~eoBitOpFactory() {};
|
||||
//@}
|
||||
|
||||
/** Another factory method: creates an object from an istream, reading from
|
||||
it whatever is needed to create the object. Usually, the format for the istream will be\\
|
||||
objectType parameter1 parameter2 ... parametern\\
|
||||
If there are problems, an exception is raised; it should be caught at the
|
||||
upper level, because it might be something for that level\\
|
||||
At the same time, it catches exceptions thrown at a lower level, which will
|
||||
indicate that whatever is in the stream is for this method to process
|
||||
@param _is an stream from where a single line will be read
|
||||
@throw runtime_exception if the object type is not known
|
||||
*/
|
||||
virtual eoOp<EOT>* make(istream& _is) {
|
||||
eoOp<EOT> * opPtr = NULL;
|
||||
try {
|
||||
opPtr = eoOpFactory<EOT>::make( _is );
|
||||
} catch ( const string& objectTypeStr ) {
|
||||
if ( objectTypeStr == "eoBinRandom") {
|
||||
opPtr = new eoBinRandom<EOT>();
|
||||
}
|
||||
if ( objectTypeStr == "eoBinBitFlip" ) {
|
||||
opPtr = new eoBinBitFlip<EOT>( );
|
||||
}
|
||||
if ( objectTypeStr == "eoBinMutation" ) {
|
||||
float rate;
|
||||
_is >> rate;
|
||||
opPtr = new eoBinMutation<EOT>( rate );
|
||||
}
|
||||
if ( objectTypeStr == "eoBinInversion" ) {
|
||||
opPtr = new eoBinInversion<EOT>( );
|
||||
}
|
||||
if ( objectTypeStr == "eoBinNext" ) {
|
||||
opPtr = new eoBinNext<EOT>( );
|
||||
}
|
||||
if ( objectTypeStr == "eoBinPrev" ) {
|
||||
opPtr = new eoBinPrev<EOT>( );
|
||||
}
|
||||
if ( objectTypeStr == "eoBinNext" ) {
|
||||
opPtr = new eoBinNext<EOT>( );
|
||||
}
|
||||
if ( objectTypeStr == "eoBinCrossover" ) {
|
||||
opPtr = new eoBinCrossover<EOT>( );
|
||||
}
|
||||
if ( objectTypeStr == "eoBinNxOver" ) {
|
||||
unsigned nPoints;
|
||||
_is >> nPoints;
|
||||
opPtr = new eoBinNxOver<EOT>( nPoints );
|
||||
}
|
||||
if ( objectTypeStr == "eoBinGxOver" ) {
|
||||
unsigned geneSize, nPoints;
|
||||
_is >> geneSize >> nPoints;
|
||||
opPtr = new eoBinGxOver<EOT>( geneSize, nPoints );
|
||||
}
|
||||
if ( objectTypeStr == "eoBinUxOver" ) {
|
||||
float rate;
|
||||
_is >> rate;
|
||||
opPtr = new eoBinUxOver<EOT>( rate );
|
||||
}
|
||||
if ( !opPtr ) { // to be caught by the upper level
|
||||
throw objectTypeStr;
|
||||
}
|
||||
}
|
||||
return opPtr;
|
||||
};
|
||||
|
||||
|
||||
};
|
||||
|
||||
|
||||
#endif _EOBITOPFACTORY_H
|
||||
|
||||
|
|
@ -1,64 +0,0 @@
|
|||
/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
-----------------------------------------------------------------------------
|
||||
eoData.h
|
||||
Some numeric limits and types and things like that; with #ifdefs to keep
|
||||
compatibility
|
||||
(c) GeNeura Team & Maarten Keijzer, 1998, 1999, 2000
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
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
|
||||
*/
|
||||
|
||||
#ifndef EODATA_H
|
||||
#define EODATA_H
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#include <vector> // vector
|
||||
#include <set> // set
|
||||
#include <string> // string
|
||||
|
||||
using namespace std;
|
||||
|
||||
|
||||
#ifdef _MSC_VER
|
||||
#include <limits> // MAXDOUBLE
|
||||
#define MAXFLOAT numeric_limits<float>::max()
|
||||
#define MINFLOAT numeric_limits<float>::min()
|
||||
#define MAXDOUBLE numeric_limits<double>::max()
|
||||
#define MAXINT numeric_limits<int>::max()
|
||||
#else
|
||||
#include <float.h>
|
||||
#include <limits.h>
|
||||
#ifndef _WIN32 // should be the define for UN*X flavours: _POSIX??
|
||||
#include <values.h>
|
||||
#endif
|
||||
#ifndef MAXFLOAT
|
||||
#define MAXFLOAT (float)1e127
|
||||
#define MAXDOUBLE (double)1.79769313486231570e+308
|
||||
#define MAXINT 2147483647
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#ifndef _MSC_VER
|
||||
#include <math.h>
|
||||
#define _isnan isnan
|
||||
#endif
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#endif EODATA_H
|
||||
|
||||
|
|
@ -1,64 +0,0 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoDrawable.h
|
||||
// (c) GeNeura Team, 1999
|
||||
/*
|
||||
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
|
||||
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
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef EODRAWABLE_H
|
||||
#define EODRAWABLE_H
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
using namespace std;
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoDrawable
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
/** eoDrawable is a template class that adds a drawing interface to an object.\\
|
||||
Requisites for template instantiation are that the object must admit a default ctor
|
||||
and a copy ctor. The Object must be an eoObject, thus, it must have its methods: className,
|
||||
eoDrawables can be drawn on any two-dimensional surface; it can be added to any
|
||||
object with above characteristics.
|
||||
@see eoObject
|
||||
*/
|
||||
template <class Object>
|
||||
class eoDrawable
|
||||
{
|
||||
public:
|
||||
/// Main ctor from an already built Object.
|
||||
eoDrawable( const Object& _o): Object( _o ){};
|
||||
|
||||
/// Copy constructor.
|
||||
eoDrawable( const eoDrawable& _d): Object( _d ){};
|
||||
|
||||
/// Virtual dtor. They are needed in virtual class hierarchies
|
||||
virtual ~eoDrawable() {};
|
||||
|
||||
|
||||
/**Draws the object. It must be redefined in any subclass, it´s impossible
|
||||
to have a general drawing method
|
||||
@param _x, _y coorinates */
|
||||
virtual void draw( unsigned _x, unsigned _y) = 0;
|
||||
|
||||
};
|
||||
|
||||
#endif EODRAWABLE_H
|
||||
|
|
@ -1,126 +0,0 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoESChrom.h
|
||||
// (c) GeNeura Team, 1998
|
||||
/*
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
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
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
|
||||
#ifndef _eoESCHROM_H
|
||||
#define _eoESCHROM_H
|
||||
|
||||
// STL libraries
|
||||
#include <vector> // For vector<>
|
||||
#include <stdexcept>
|
||||
#include <strstream>
|
||||
#include <iostream> // for ostream
|
||||
|
||||
// EO includes
|
||||
#include <eoVector.h>
|
||||
|
||||
/**@name Chromosomes for evolution strategies
|
||||
Each chromosome in an evolution strategies is composed of a vector of floating point
|
||||
values plus a vector of sigmas, that are added to them during mutation
|
||||
*/
|
||||
//@{
|
||||
|
||||
/** Each gene in an Evolution Strategies is composed of a value plus an standard
|
||||
deviation, sigma, used for mutation*/
|
||||
struct eoESGene {
|
||||
double val, sigma;
|
||||
eoESGene( double _val = 0, double _sigma = 0 ): val( _val ), sigma( _sigma ) {};
|
||||
};
|
||||
|
||||
/// Tricky operator to avoid errors in some VC++ systems, namely VC 5.0 SP3
|
||||
bool operator < ( eoESGene _e1, eoESGene _e2 ) {
|
||||
return _e1.val < _e2.val;
|
||||
}
|
||||
|
||||
/// Tricky operator to avoid errors in some VC++ systems
|
||||
bool operator == ( eoESGene _e1, eoESGene _e2 ) {
|
||||
return ( _e1.val == _e2.val ) && ( _e1.sigma == _e2.sigma ) ;
|
||||
}
|
||||
|
||||
///
|
||||
ostream & operator << ( ostream& _s, const eoESGene& _e ) {
|
||||
_s << _e.val << ", " << _e.sigma << " | ";
|
||||
return _s;
|
||||
}
|
||||
|
||||
/// Dummy >>
|
||||
istream & operator >> ( istream& _s, const eoESGene& _e ) {
|
||||
_s >> _e.val;
|
||||
_s >> _e.sigma;
|
||||
return _s;
|
||||
}
|
||||
|
||||
|
||||
/** Basic chromosome for evolution strategies (ES), as defined by Rechenberg and
|
||||
Schwefel. Each chromosomes is composed of "genes"; each one of then is an eoESGene
|
||||
@see eoESGene
|
||||
*/
|
||||
template <typename fitT = float >
|
||||
class eoESChrom: public eoVector<eoESGene, fitT> {
|
||||
public:
|
||||
/// Basic ctor
|
||||
eoESChrom( ):eoVector<eoESGene, fitT>() {};
|
||||
|
||||
/** Ctor using a couple of random number generators
|
||||
@param _size Lineal length of the object
|
||||
@param _rnd a random number generator, which returns a random value each time it´s called.
|
||||
@param _rndS another one, for the sigma
|
||||
*/
|
||||
eoESChrom( unsigned _size, eoRnd<double>& _rnd, eoRnd<double>& _rndS )
|
||||
: eoVector<eoESGene, fitT>( _size ){
|
||||
for ( iterator i = begin(); i != end(); i ++ ) {
|
||||
i->val = _rnd();
|
||||
i->sigma = _rndS();
|
||||
}
|
||||
};
|
||||
|
||||
/// Copy ctor
|
||||
eoESChrom( const eoESChrom& _eoes): eoVector<eoESGene, fitT>( _eoes ) {};
|
||||
|
||||
/// Assignment operator
|
||||
const eoESChrom& operator =( const eoESChrom & _eoes ) {
|
||||
if ( this != &_eoes ){
|
||||
eoVector<eoESGene, fitT>::operator=( _eoes );
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
///
|
||||
~eoESChrom() {};
|
||||
|
||||
/** @name Methods from eoObject
|
||||
readFrom and printOn are directly inherited from eo1d
|
||||
*/
|
||||
//@{
|
||||
/** Inherited from eoObject
|
||||
@see eoObject
|
||||
*/
|
||||
string className() const {return "eoESChrom";};
|
||||
//@}
|
||||
|
||||
};
|
||||
|
||||
//@}
|
||||
#endif
|
||||
|
||||
|
|
@ -1,271 +0,0 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoESInd.h
|
||||
// (c) GeNeura Team, 1998 - EEAAX 1999
|
||||
/*
|
||||
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
|
||||
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@polytechnique.fr
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _EOESFULLCHROM_H
|
||||
#define _EOESFULLCHROM_H
|
||||
|
||||
// STL libraries
|
||||
#include <vector> // For vector<>
|
||||
#include <stdexcept>
|
||||
#include <strstream>
|
||||
#include <iostream> // for ostream
|
||||
|
||||
// EO includes
|
||||
#include <eoVector.h>
|
||||
#include <eoRNG.h>
|
||||
/**@name Chromosomes for evolution strategies
|
||||
Each chromosome in an evolution strategies is composed of a vector of floating point
|
||||
values plus a vector of sigmas, that are added to them during mutation and a vector of correlations
|
||||
*/
|
||||
//@{
|
||||
|
||||
|
||||
/**@name individuals for evolution strategies -MS- 22/10/99
|
||||
Each individual in an evolution strategy is composed of
|
||||
a vector of floating point values
|
||||
a vector of std deviations
|
||||
a vector of rotation angles (for correlated mutations)
|
||||
|
||||
THese individuals CANNOT BE IMPLEMENTED as vectors of anything
|
||||
at least in the case of correlated mutations
|
||||
*/
|
||||
//@{
|
||||
|
||||
template <typename fitT = float >
|
||||
class eoESFullChrom : public eoVector<double, fitT> {
|
||||
public:
|
||||
/// constructor
|
||||
eoESFullChrom( unsigned _num_genes = 1,
|
||||
unsigned _num_sigma = 1, unsigned _num_correl = 0,
|
||||
bool _verbose = false,
|
||||
double _ObjMin = 0, double _ObjMax = 1,
|
||||
double _StdDevInit = 0.3 ):
|
||||
eoVector<double, fitT>(_num_genes),
|
||||
// ObjVar( _num_genes ), now an eoVector<double>
|
||||
StdDev( _num_sigma ),
|
||||
CorCff( _num_correl ),
|
||||
verbose( _verbose ),
|
||||
ObjMin( _ObjMin ),
|
||||
ObjMax(_ObjMax ),
|
||||
StdDevInit( _StdDevInit ) {}
|
||||
|
||||
/// copy constructor
|
||||
eoESFullChrom( const eoESFullChrom& _eo ):
|
||||
eoVector<double, fitT> ( _eo ), // ObjVar ( _eo.ObjVar ),
|
||||
StdDev ( _eo.StdDev ), CorCff( _eo.CorCff ), verbose( _eo.verbose ),
|
||||
ObjMin( _eo.ObjMin ), ObjMax(_eo.ObjMax ), StdDevInit( _eo.StdDevInit ) {}
|
||||
|
||||
|
||||
/* another constructor, for compatibility reasons */
|
||||
eoESFullChrom(istream& _s) { cout << "Not Yet implemented\n";exit(1);};
|
||||
|
||||
/* And now the useful constructor: from a parser (should be in the
|
||||
factory, if such a thing exists one day for eoESFullChrom
|
||||
*/
|
||||
eoESFullChrom(Parser & parser) : StdDev(0), CorCff(0) {
|
||||
parser.AddTitle("Description of ES individuals");
|
||||
int num_genes, num_sigma;
|
||||
bool correlated_mutations;
|
||||
try {
|
||||
num_genes = parser.getInt("-Io", "--NbObjVar", "2",
|
||||
"Number of Object Variables" );
|
||||
num_sigma = parser.getInt("-Is", "--NbSigma", "1",
|
||||
"Number of Standard Deviations" );
|
||||
correlated_mutations = parser.getBool("-Ic", "--Correlated",
|
||||
"Correlated mutation?" );
|
||||
ObjMin = parser.getFloat("-Im", "--min", "0",
|
||||
"Minimum value for object variables" );
|
||||
ObjMax = parser.getFloat("-IM", "--max", "1",
|
||||
"Maximum value for object variables" );
|
||||
StdDevInit = parser.getFloat("-II", "--SigmaInit", "0.3",
|
||||
"Initial value for std. dev. (scaled by range)" );
|
||||
verbose = parser.getBool("-Iv", "--verbose",
|
||||
"Verbose listing of ES individuals (mutation parameters");
|
||||
}
|
||||
catch (exception & e)
|
||||
{
|
||||
cout << e.what() << endl;
|
||||
parser.printHelp();
|
||||
exit(1);
|
||||
}
|
||||
|
||||
// consistency tests
|
||||
if (! num_sigma) { // no std dev??? EXCEPTION
|
||||
throw invalid_argument( "No standard deviation: choose another representation please" );
|
||||
}
|
||||
if (num_sigma > num_genes) {
|
||||
cout << "WARNING, Number of Standard Deviations > Number of Object Variables\nAdjusted!\n";
|
||||
num_sigma = num_genes;
|
||||
// modify the Param value - so .status is OK
|
||||
ostrstream sloc;
|
||||
sloc << num_genes;
|
||||
parser.setParamValue("--NbSigma", sloc.str());
|
||||
}
|
||||
// adjust the sizes!!!
|
||||
resize(num_genes);
|
||||
if (num_sigma)
|
||||
StdDev.resize(num_sigma);
|
||||
if (correlated_mutations) {
|
||||
if (num_sigma < num_genes) {
|
||||
cout << "WARNING less Std Dev. than number of variables + Correlated mutations\n";
|
||||
cout << "Though possible, this is a strange setting" << endl;
|
||||
}
|
||||
// nb of rotation angles: N*(N-1)/2 (in general!)
|
||||
CorCff.resize ( (2*num_genes - num_sigma)*(num_sigma - 1) / 2 );
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/// Operator =
|
||||
const eoESFullChrom& operator = ( const eoESFullChrom& _eo ) {
|
||||
if ( this != &_eo ) {
|
||||
// Change EO part
|
||||
eoVector<double, fitT>::operator = (_eo);
|
||||
|
||||
// Change this part
|
||||
// ObjVar = _eo.ObjVar;
|
||||
StdDev = _eo.StdDev;
|
||||
CorCff = _eo.CorCff;
|
||||
verbose = _eo.verbose;
|
||||
ObjMin = _eo.ObjMin;
|
||||
ObjMax = _eo.ObjMax;
|
||||
StdDevInit = _eo.StdDevInit;
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
/// destructor
|
||||
virtual ~eoESFullChrom() {}
|
||||
|
||||
///
|
||||
double getStdDev( unsigned _i ) const {
|
||||
if ( _i >= length() )
|
||||
throw out_of_range( "out_of_range when reading StdDev");
|
||||
return StdDev[ _i ];
|
||||
}
|
||||
|
||||
///
|
||||
void setStdDev( unsigned _i, double _val ) {
|
||||
if ( _i < length() ) {
|
||||
StdDev[_i] = _val;
|
||||
} else
|
||||
throw out_of_range( "out_of_range when writing StdDev");
|
||||
}
|
||||
|
||||
///
|
||||
double getCorCff( unsigned _i ) const {
|
||||
if ( _i >= length() )
|
||||
throw out_of_range( "out_of_range when reading CorCff");
|
||||
return CorCff[ _i ];
|
||||
}
|
||||
|
||||
///
|
||||
void setCorCff( unsigned _i, double _val ) {
|
||||
if ( _i < length() ) {
|
||||
CorCff[_i] = _val;
|
||||
} else
|
||||
throw out_of_range( "out_of_range when writing CorCff");
|
||||
}
|
||||
|
||||
///
|
||||
void insertGene( unsigned _i, double _val ) {
|
||||
throw FixedLengthChromosome();
|
||||
};
|
||||
|
||||
///
|
||||
void deleteGene( unsigned _i ) {
|
||||
throw FixedLengthChromosome();
|
||||
};
|
||||
|
||||
///
|
||||
unsigned length() const { return size();}/* formerly ObjVar.size() */
|
||||
unsigned StdDevLength() const { return StdDev.size();}
|
||||
unsigned CorCffLength() const { return CorCff.size();}
|
||||
|
||||
|
||||
/** Print itself: inherited from eoObject implementation.
|
||||
Instance from base classes are processed in
|
||||
base classes, so you don´t have to worry about, for instance, fitness.
|
||||
@param _s the ostream in which things are written*/
|
||||
virtual void printOn( ostream& _s ) const{
|
||||
copy( begin(), end(), ostream_iterator<double>( _s, " ") );
|
||||
// The formatting instructinos shoudl be left to the caller
|
||||
// _s << "\n";
|
||||
if (verbose) {
|
||||
_s << "\n\tStd Dev. " ;
|
||||
copy( StdDev.begin(), StdDev.end(), ostream_iterator<double>( _s, " ") );
|
||||
if (CorCff.size()) {
|
||||
_s << "\n\t";
|
||||
copy( CorCff.begin(), CorCff.end(), ostream_iterator<double>( _s, " ") );
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/** This exception should be thrown when trying to insert or delete a gene
|
||||
in a fixed length chromosome
|
||||
*/
|
||||
class FixedLengthChromosome : public exception {
|
||||
|
||||
public:
|
||||
/**
|
||||
* Constructor
|
||||
*/
|
||||
FixedLengthChromosome()
|
||||
: exception() { };
|
||||
|
||||
~FixedLengthChromosome() {};
|
||||
};
|
||||
|
||||
// accessors
|
||||
double getObjMin() const {return ObjMin;}
|
||||
double getObjMax() const {return ObjMax;}
|
||||
double getStdDevInit () const {return StdDevInit;}
|
||||
|
||||
/** Inherited from eoObject
|
||||
@see eoObject
|
||||
*/
|
||||
virtual string className() const {return "eoESFullChrom";};
|
||||
|
||||
private:
|
||||
// vector<double> ObjVar; /* object variable vector */
|
||||
// or shoudl the class be subclass of EOVector<double> ???
|
||||
|
||||
vector<double> StdDev; /* standard deviation vector */
|
||||
vector<double> CorCff; /* correlation coefficient vector */
|
||||
|
||||
bool verbose; /* Print std deviations or not */
|
||||
|
||||
/** the range is used for mutation AND random initialization,
|
||||
* while the StdDevInit is used only for random initialization
|
||||
* this in a little inconsistent!
|
||||
*/
|
||||
double ObjMin, ObjMax; /* Range for Object variables */
|
||||
double StdDevInit; /* Initial value of Standard Deviations */
|
||||
|
||||
};
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
|
|
@ -1,253 +0,0 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoESMute.h : ES mutation
|
||||
// (c) GeNeura Team, 1998 for the EO part
|
||||
// Th. Baeck 1994 and EEAAX 1999 for the ES part
|
||||
/*
|
||||
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
|
||||
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@polytechnique.fr
|
||||
http://eeaax.cmap.polytchnique.fr/
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
|
||||
#ifndef _EOESMUT_H
|
||||
#define _EOESMUT_H
|
||||
|
||||
#include <eoParser.h>
|
||||
#include <eoRNG.h>
|
||||
#include <cmath> // for exp
|
||||
|
||||
#include <eoESFullChrom.h>
|
||||
#include <eoOp.h>
|
||||
|
||||
#ifndef M_PI
|
||||
#define M_PI 3.1415926535897932384626433832795
|
||||
#endif
|
||||
|
||||
const double ES_SIGEPS = 1.0e-40; /* ES lower bound for sigma values */
|
||||
// should not be a parameter ...
|
||||
|
||||
/** ES-style mutation in the large: Obviously, valid only for eoESInd
|
||||
*/
|
||||
template <class fitT>
|
||||
class eoESMutate: public eoMonOp< eoESFullChrom<fitT> > {
|
||||
public:
|
||||
eoESMutate(double n)
|
||||
{
|
||||
TauLcl = 1/sqrt(2*sqrt(n));
|
||||
TauGlb= 1 / sqrt(2 * n);
|
||||
TauBeta = 0.0873;
|
||||
}///
|
||||
|
||||
eoESMutate( double _TauLcl, double _TauGlb, double _TauBeta )
|
||||
: eoMonOp< eoESFullChrom<fitT> >( ), TauLcl(_TauLcl), TauGlb(_TauGlb),
|
||||
TauBeta(_TauBeta) {};
|
||||
|
||||
/* The parser constructor
|
||||
*/
|
||||
eoESMutate(Parser & parser, unsigned _stdDevLength, unsigned _size, bool _correlated ):
|
||||
eoMonOp< eoESFullChrom<fitT> >( ) {
|
||||
parser.AddTitle("Parameters of ES mutation (before renormalization)");
|
||||
try { // we know that there is at least 1 std dev.
|
||||
if (_stdDevLength == 1) {
|
||||
TauLcl = parser.getInt("-Ml", "--TauLcl", "1",
|
||||
"TauLcl, Mutation rate for the only Std Dev." );
|
||||
// different normalization in that case -- Thomas Baeck
|
||||
TauLcl /= sqrt((double) _size);
|
||||
}
|
||||
else { /* more than 1 std dev */
|
||||
TauLcl = parser.getFloat("-Ml", "--TauLcl", "1",
|
||||
"Local mutation rate for Std Dev." );
|
||||
TauGlb = parser.getFloat("-Mg", "--TauGlb", "1",
|
||||
"Global mutation rate for Std Dev." );
|
||||
// renormalization
|
||||
TauLcl /= sqrt( 2.0 * sqrt( (double)_size ) );
|
||||
TauGlb /= sqrt( 2.0 * ( (double) _size ) );
|
||||
|
||||
if ( _correlated ) { // Correlated Mutations
|
||||
TauBeta = parser.getFloat("-Mb", "--TauBeta", "0.0873",
|
||||
"Mutation rate for corr. coeff." );
|
||||
// rotation angles: no normalization
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (exception & e)
|
||||
{
|
||||
cout << e.what() << endl;
|
||||
parser.printHelp();
|
||||
exit(1);
|
||||
}
|
||||
};
|
||||
|
||||
/// needed virtual dtor
|
||||
virtual ~eoESMutate() {};
|
||||
|
||||
// virtual separation depending wether correlated mutations are present
|
||||
virtual void operator() ( eoESFullChrom<fitT> & _eo ) const {
|
||||
if (_eo.CorCffLength())
|
||||
CorrelatedMutation(_eo);
|
||||
else
|
||||
StandardMutation(_eo);
|
||||
}
|
||||
|
||||
/** @name Methods from eoObject
|
||||
readFrom and printOn are directly inherited from eoObject
|
||||
*/
|
||||
//@{
|
||||
/** Inherited from eoObject
|
||||
@see eoObject
|
||||
*/
|
||||
virtual string className() const {return "eoESMutate";};
|
||||
|
||||
private:
|
||||
/// mutations - standard et correlated
|
||||
// =========
|
||||
/*
|
||||
* Standard mutation of object variables and standard
|
||||
* deviations in ESs.
|
||||
* If there are fewer different standard deviations available
|
||||
* than the dimension of the objective function requires, the
|
||||
* last standard deviation is responsible for ALL remaining
|
||||
* object variables.
|
||||
* Schwefel 1977: Numerische Optimierung von Computer-Modellen
|
||||
* mittels der Evolutionsstrategie, pp. 165 ff.
|
||||
*/
|
||||
|
||||
virtual void StandardMutation( eoESFullChrom<fitT> & _eo ) const {
|
||||
unsigned i,k;
|
||||
double Glb, StdLoc;
|
||||
|
||||
if (_eo.StdDevLength() == 1) { /* single StdDev -> No global factor */
|
||||
StdLoc = _eo.getStdDev(0);
|
||||
StdLoc *= exp(TauLcl*rng.normal());
|
||||
if (StdLoc < ES_SIGEPS)
|
||||
StdLoc = ES_SIGEPS;
|
||||
_eo.setStdDev(0, StdLoc);
|
||||
_eo.setGene( 0, _eo.getGene(0) + StdLoc*rng.normal());
|
||||
i = 1;
|
||||
}
|
||||
else { /* more than one std dev. */
|
||||
Glb = exp(TauGlb*rng.normal());
|
||||
for (i = 0; i < _eo.length() && i < _eo.StdDevLength(); i++) {
|
||||
StdLoc = _eo.getStdDev(i);
|
||||
StdLoc *= Glb * exp(TauLcl*rng.normal());
|
||||
if (StdLoc < ES_SIGEPS)
|
||||
StdLoc = ES_SIGEPS;
|
||||
_eo.setStdDev(i, StdLoc);
|
||||
_eo.setGene( i, _eo.getGene(i) + StdLoc*rng.normal());
|
||||
}
|
||||
}
|
||||
// last object variables: same STdDev than the preceding one
|
||||
for (k = i; k < _eo.length(); k++) {
|
||||
_eo.setGene( k, _eo.getGene(k) + StdLoc*rng.normal() );
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Correlated mutations in ESs, according to the following
|
||||
* sources:
|
||||
* H.-P. Schwefel: Internal Report of KFA Juelich, KFA-STE-IB-3/80
|
||||
* p. 43, 1980
|
||||
* G. Rudolph: Globale Optimierung mit parallelen Evolutions-
|
||||
* strategien, Diploma Thesis, University of Dortmund, 1990
|
||||
*/
|
||||
|
||||
// Code from Thomas Baeck
|
||||
|
||||
virtual void CorrelatedMutation( eoESFullChrom<fitT> & _eo ) const {
|
||||
|
||||
|
||||
int i, k, n1, n2, nq;
|
||||
|
||||
double d1, d2, S, C, Glb;
|
||||
double tmp;
|
||||
/*
|
||||
* First: mutate standard deviations (as above).
|
||||
*/
|
||||
|
||||
Glb = exp(TauGlb*rng.normal());
|
||||
for (i = 0; i < _eo.StdDevLength(); i++) {
|
||||
tmp = _eo.getStdDev(i);
|
||||
_eo.setStdDev( i, tmp*Glb*exp(TauLcl*rng.normal()) );
|
||||
}
|
||||
|
||||
/*
|
||||
* Mutate rotation angles.
|
||||
*/
|
||||
|
||||
for (i = 0; i < _eo.CorCffLength(); i++) {
|
||||
tmp = _eo.getCorCff(i);
|
||||
tmp += TauBeta*rng.normal();
|
||||
// danger of VERY long loops --MS--
|
||||
// while (CorCff[i] > M_PI)
|
||||
// CorCff[i] -= 2.0 * M_PI;
|
||||
// while (CorCff[i] < - M_PI)
|
||||
// CorCff[i] += 2.0 * M_PI;
|
||||
if ( fabs(tmp) > M_PI ) {
|
||||
tmp -= M_PI * (int) (tmp/M_PI) ;
|
||||
}
|
||||
_eo.setCorCff(i, tmp);
|
||||
}
|
||||
|
||||
/*
|
||||
* Perform correlated mutations.
|
||||
*/
|
||||
vector<double> VarStp(_eo.size());
|
||||
for (i = 0; i < _eo.size() && i < _eo.StdDevLength(); i++)
|
||||
VarStp[i] = _eo.getStdDev(i)*rng.normal();
|
||||
for (k = i; k < _eo.size(); k++)
|
||||
VarStp[k] = _eo.getStdDev(i-1)*rng.normal();
|
||||
nq = _eo.CorCffLength() - 1;
|
||||
for (k = _eo.size()-_eo.StdDevLength(); k < _eo.size()-1; k++) {
|
||||
n1 = _eo.size() - k - 1;
|
||||
n2 = _eo.size() - 1;
|
||||
for (i = 0; i < k; i++) {
|
||||
d1 = VarStp[n1];
|
||||
d2 = VarStp[n2];
|
||||
S = sin( _eo.getCorCff(nq) );
|
||||
C = cos( _eo.getCorCff(nq) );
|
||||
VarStp[n2] = d1 * S + d2 * C;
|
||||
VarStp[n1] = d1 * C - d2 * S;
|
||||
n2--;
|
||||
nq--;
|
||||
}
|
||||
}
|
||||
for (i = 0; i < _eo.size(); i++)
|
||||
_eo[i] += VarStp[i];
|
||||
|
||||
}
|
||||
// the data
|
||||
//=========
|
||||
double TauLcl; /* Local factor for mutation of std deviations */
|
||||
double TauGlb; /* Global factor for mutation of std deviations */
|
||||
double TauBeta; /* Factor for mutation of correlation parameters */
|
||||
};
|
||||
|
||||
/*
|
||||
* Correlated mutations in ESs, according to the following
|
||||
* sources:
|
||||
* H.-P. Schwefel: Internal Report of KFA Juelich, KFA-STE-IB-3/80
|
||||
* p. 43, 1980
|
||||
* G. Rudolph: Globale Optimierung mit parallelen Evolutions-
|
||||
* strategien, Diploma Thesis, University of Dortmund, 1990
|
||||
*/
|
||||
// Not yet implemented!
|
||||
|
||||
#endif
|
||||
|
||||
|
|
@ -1,72 +0,0 @@
|
|||
/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
-----------------------------------------------------------------------------
|
||||
eoException.h
|
||||
Exceptions that are possibly thrown at initialization and such should be
|
||||
defined here.
|
||||
|
||||
(c) 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
|
||||
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
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef eoException_h
|
||||
#define eoException_h
|
||||
|
||||
#include <exception>
|
||||
|
||||
#include "eoObject.h"
|
||||
|
||||
struct eoException
|
||||
{
|
||||
eoException() {}
|
||||
eoException(const eoObject& caller) : who_caught_it(caller.className()) {}
|
||||
virtual ~eoException(){} // otherwise compiler complains
|
||||
std::string who(void) const { return who_caught_it; }
|
||||
virtual std::string what(void) const{ return "";}
|
||||
|
||||
private :
|
||||
std::string who_caught_it;
|
||||
};
|
||||
|
||||
struct eoFitnessException : public eoException
|
||||
{
|
||||
eoFitnessException() : eoException() {}
|
||||
eoFitnessException(const eoObject& caller) : eoException(caller) {}
|
||||
virtual ~eoFitnessException(){} // otherwise compiler complains
|
||||
};
|
||||
|
||||
struct eoNegativeFitnessException : public eoFitnessException
|
||||
{
|
||||
eoNegativeFitnessException() : eoFitnessException() {}
|
||||
eoNegativeFitnessException(const eoObject& caller) : eoFitnessException(caller) {}
|
||||
|
||||
virtual ~eoNegativeFitnessException(){} // otherwise compiler complains
|
||||
std::string what(void) const { return "negative fitness encountered"; }
|
||||
};
|
||||
|
||||
struct eoMinimizingFitnessException : public eoFitnessException
|
||||
{
|
||||
eoMinimizingFitnessException() : eoFitnessException() {}
|
||||
eoMinimizingFitnessException(const eoObject& caller) : eoFitnessException(caller) {}
|
||||
virtual ~eoMinimizingFitnessException(){} // otherwise compiler complains
|
||||
|
||||
std::string what(void) const { return "smaller fitness is better fitness, which is quite inappropriate here"; }
|
||||
};
|
||||
|
||||
#endif
|
||||
|
|
@ -1,838 +0,0 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
/* eoParser.h
|
||||
some classes to parser either the command line or a parameter file
|
||||
|
||||
(c) Marc Schoenauer and Geneura team, 1999
|
||||
|
||||
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
|
||||
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
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _PARSER_H
|
||||
#define _PARSER_H
|
||||
|
||||
#include <string.h> // for strcasecmp ... maybe there's a c++ way of doing it?
|
||||
// Yep there is, but needs either a simple functor for the equal function
|
||||
// or a hand-rolled string template class (this isn't that horrible as
|
||||
// it sounds, it just means a new string_traits class with two changed
|
||||
// function definitions. (Maarten)
|
||||
#ifdef _MSC_VER
|
||||
#define strcasecmp(a,b) _strnicmp(a,b,strlen(a))
|
||||
#endif
|
||||
|
||||
// STL includes
|
||||
#include <iostream>
|
||||
#include <fstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <strstream>
|
||||
#include <ctime>
|
||||
|
||||
// include for exceptions
|
||||
#include <stdexcept> // logic_error
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// Class Param
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* A param repesents an argument that can be passed to a program in the command line
|
||||
*/
|
||||
class Param {
|
||||
public:
|
||||
|
||||
/**
|
||||
* Type of params
|
||||
*/
|
||||
enum valueType { INT, UL, FLOAT, STRING, BOOL, ARRAY, TITLE };
|
||||
|
||||
/**
|
||||
* Construct an Param.
|
||||
* @param _shortName Short name of the argument
|
||||
* @param _longName Long name of the argument
|
||||
* @param _default The default value
|
||||
* @param _valueType Type of the parameter ("integer","unsigned long", "float","char", "bool" and so on)
|
||||
* @param _description Description of the parameter. What is useful for.
|
||||
* @param _required If it is a necessary parameter or not
|
||||
*/
|
||||
Param (string _shortName="-h", string _longName="--help",
|
||||
string _default = "", valueType _valType= STRING,
|
||||
string _description="Shows this help",
|
||||
bool _required=false )
|
||||
: repShortName(_shortName), repLongName(_longName),
|
||||
repDescription(_description ), repEnv(""), repDefault(_default),
|
||||
repValue(_default), repValType( _valType),
|
||||
repRequired( _required), repChanged(false) {
|
||||
|
||||
const char *c = repLongName.c_str();
|
||||
for(unsigned i=0; i<repLongName.length() ; i++,c++) {
|
||||
if( *c != '-' ) break;
|
||||
}
|
||||
//initialize "repEnv" depending on the long name of the parameter.
|
||||
//previously the "-" (if exist) are skiped.
|
||||
repEnv = c ;
|
||||
};
|
||||
|
||||
/**
|
||||
* Copy constructor
|
||||
* @param _param The source param.
|
||||
*/
|
||||
Param (const Param& _param) :
|
||||
repShortName(_param.repShortName), repLongName(_param.repLongName),
|
||||
repDescription(_param.repDescription ), repEnv(_param.repEnv),
|
||||
repDefault(_param.repDefault),
|
||||
repValue(_param.repValue), repValType(_param.repValType),
|
||||
repRequired(_param.repRequired), repChanged(_param.repChanged) {};
|
||||
|
||||
/**
|
||||
* Virtual destructor is needed.
|
||||
*/
|
||||
virtual ~Param () {};
|
||||
|
||||
/**
|
||||
* Returns the short name.
|
||||
*/
|
||||
const string& shortName ( void ) const { return repShortName; };
|
||||
|
||||
/**
|
||||
* Returns the long name.
|
||||
*/
|
||||
const string& longName ( void ) const { return repLongName; };
|
||||
|
||||
/**
|
||||
* Returns the description of the argument
|
||||
*/
|
||||
const string& description ( void ) const { return repDescription; };
|
||||
|
||||
/**
|
||||
* Returns the environment variable of the argument
|
||||
*/
|
||||
const string& environment ( void ) const { return repEnv; };
|
||||
|
||||
/**
|
||||
* Returns the default value of the argument
|
||||
*/
|
||||
const string& defValue ( void ) const { return repDefault; };
|
||||
|
||||
/**
|
||||
* Sets a value for the param.
|
||||
* @param _value The new value.
|
||||
*/
|
||||
void value ( const string& _value ) { repValue = _value; repChanged = true; };
|
||||
|
||||
/**
|
||||
* Returns the value of the param.
|
||||
*/
|
||||
const string& value ( void ) const { return repValue; };
|
||||
|
||||
/**
|
||||
* Returns if required or not.
|
||||
*/
|
||||
bool required ( void ) const { return repRequired; };
|
||||
|
||||
/**
|
||||
* Returns the type of the param's value.
|
||||
*/
|
||||
Param::valueType valType( void ) const { return repValType; };
|
||||
|
||||
/**
|
||||
* Returns true if the default value of the param has changed.
|
||||
*/
|
||||
bool changed( void ) const { return repChanged; };
|
||||
|
||||
private:
|
||||
string repShortName;
|
||||
string repLongName;
|
||||
string repDescription;
|
||||
string repEnv;
|
||||
string repDefault;
|
||||
|
||||
string repValue;
|
||||
Param::valueType repValType;
|
||||
bool repRequired;
|
||||
bool repChanged;
|
||||
};
|
||||
|
||||
/// This operator is defined to avoid errors in some systems
|
||||
inline bool operator < ( const Param& _p1, const Param& _p2 ) {
|
||||
return ( _p1.shortName() < _p2.shortName() );
|
||||
}
|
||||
|
||||
/// This operator is defined to avoid errors in some systems
|
||||
inline bool operator == ( const Param& _p1, const Param& _p2 ) {
|
||||
return ( _p1.shortName() == _p2.shortName() );
|
||||
}
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// Class Parser
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Parses the command line / input parameter file / environment variables.
|
||||
*/
|
||||
class Parser {
|
||||
public:
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
* @param _argc, _ argv command line arguments
|
||||
* @param _programDescription Description of the work the program does
|
||||
*/
|
||||
Parser ( int _argc, char **_argv , string _programDescription,
|
||||
string _sFileParamName = "-P",
|
||||
string _lFileParamName = "--Param") :
|
||||
params(),
|
||||
programName( _argv[0]), programDescription( _programDescription),
|
||||
parse_argc(_argc), parse_argv(_argv), InputFileName("") {
|
||||
|
||||
// the input file name has to be read immediately - from command-line or environement (not input0file :-)
|
||||
string _default = _argv[0];
|
||||
_default += ".param";
|
||||
Param param (_sFileParamName, _lFileParamName, _default, Param::STRING, "Name of the input file", 0);
|
||||
|
||||
// FIRST: look for the corresponding environment variable
|
||||
if( getenv( param.environment().c_str() ) )
|
||||
param.value(getenv(param.environment().c_str()) );
|
||||
|
||||
// LAST (highest priority) parse the command line arguments
|
||||
for (int i=1 ; i<parse_argc ; i++)
|
||||
if( ( ! strcasecmp(param.longName().c_str(), parse_argv[i]) ) ||
|
||||
( ! strcmp(param.shortName().c_str(), parse_argv[i]) )
|
||||
) { // found the parameter name
|
||||
param.value(parse_argv[i+1]);
|
||||
break;
|
||||
}
|
||||
// Now try to open the file
|
||||
ifstream is(param.value().c_str());
|
||||
if (is) // file exists ???
|
||||
InputFileName = param.value().c_str();
|
||||
|
||||
params.push_back( param );
|
||||
};
|
||||
|
||||
/**
|
||||
* Copy constructor
|
||||
* @param _parser The source parser
|
||||
*/
|
||||
Parser ( const Parser& _parser ) :
|
||||
params(_parser.params),
|
||||
programName( _parser.programName),
|
||||
programDescription(_parser.programDescription),
|
||||
parse_argc(_parser.parse_argc),
|
||||
parse_argv(_parser.parse_argv),
|
||||
InputFileName(_parser.InputFileName)
|
||||
{};
|
||||
|
||||
/**
|
||||
* Virtual destructor is needed.
|
||||
*/
|
||||
virtual ~Parser () {};
|
||||
|
||||
|
||||
/**
|
||||
* Adds a fake parameter == title in the output file
|
||||
* @param the title
|
||||
*/
|
||||
void AddTitle (const string& _title)
|
||||
{
|
||||
Param param ( "", "", "", Param::TITLE, _title, false );
|
||||
params.push_back( param );
|
||||
}
|
||||
|
||||
/**
|
||||
* Description of all parameter readings:
|
||||
* @param _shortName Short name of the param.
|
||||
* @param _longName Long name of the param.
|
||||
* @param _default Default value.
|
||||
* @param _valType Type of the parameter
|
||||
* @param _description Parameter utility
|
||||
* @param _required If the parameter is necessary or not
|
||||
*/
|
||||
|
||||
/**
|
||||
* Gets the string value of a param from the full parameter description
|
||||
* @param see above
|
||||
*/
|
||||
string getString (const string& _shortName, const string& _longName,
|
||||
const string& _default = "",
|
||||
const string& _description="", bool _required=false) {
|
||||
Param param ( _shortName, _longName, _default, Param::STRING, _description, _required );
|
||||
parse( param );
|
||||
params.push_back( param );
|
||||
|
||||
return param.value();
|
||||
};
|
||||
|
||||
/**
|
||||
* Gets the bool value of a param-flag from the full parameter description
|
||||
* @param see above
|
||||
*/
|
||||
|
||||
bool getBool (const string& _shortName, const string& _longName,
|
||||
const string& _description="") {
|
||||
Param param ( _shortName, _longName, "false", Param::BOOL, _description, false );
|
||||
parse( param );
|
||||
params.push_back( param );
|
||||
|
||||
if (param.value() == "true") {
|
||||
return true;
|
||||
}
|
||||
else {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Gets the "array" (vector of strings) value of a param from the full parameter description
|
||||
* @param see above
|
||||
*/
|
||||
vector<string> getArray (const string& _shortName, const string& _longName,
|
||||
const string& _default = "",
|
||||
const string& _description="", bool _required=false) {
|
||||
Param param ( _shortName, _longName, _default, Param::ARRAY, _description, _required );
|
||||
parse( param );
|
||||
params.push_back( param );
|
||||
|
||||
istrstream is(param.value().c_str());
|
||||
vector<string> retValue;
|
||||
string tmpStr;
|
||||
|
||||
is >> tmpStr;
|
||||
while(is){
|
||||
retValue.push_back(tmpStr);
|
||||
is >> tmpStr;
|
||||
}
|
||||
return retValue;
|
||||
};
|
||||
|
||||
/**
|
||||
* Gets the int value of a param given the full description of the parameter
|
||||
* @param see above
|
||||
* @exception BadType if the param's value isn't a correct int
|
||||
*/
|
||||
|
||||
int getInt (const string& _shortName, const string& _longName,
|
||||
const string& _default = "",
|
||||
const string& _description="", bool _required=false) {
|
||||
Param param ( _shortName, _longName, _default, Param::INT, _description, _required );
|
||||
parse( param );
|
||||
params.push_back( param );
|
||||
|
||||
// now gets the value
|
||||
istrstream is( param.value().c_str());
|
||||
int retValue;
|
||||
is >> retValue;
|
||||
|
||||
if (!is) {
|
||||
throw Parser::BadType(param.longName().c_str(), param.value().c_str(), "float");
|
||||
return 0;
|
||||
} else {
|
||||
return retValue;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Gets the unsigned lon value of a param given ...
|
||||
* @param see above
|
||||
* @exception BadType if the param's value isn't a correct unsigned long
|
||||
*/
|
||||
|
||||
int getUnsignedLong (const string& _shortName, const string& _longName,
|
||||
const string& _default = "",
|
||||
const string& _description="", bool _required=false) {
|
||||
Param param ( _shortName, _longName, _default, Param::UL, _description, _required );
|
||||
parse( param );
|
||||
params.push_back( param );
|
||||
|
||||
// now gets the value
|
||||
istrstream is( param.value().c_str());
|
||||
unsigned long retValue;
|
||||
is >> retValue;
|
||||
|
||||
if (!is) {
|
||||
throw Parser::BadType(param.longName().c_str(), param.value().c_str(), "float");
|
||||
return 0;
|
||||
} else {
|
||||
return retValue;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Gets the float value of a param given the description of the parameter
|
||||
* @param see above
|
||||
* @exception BadType if the param's value isn't a correct int
|
||||
*/
|
||||
|
||||
float getFloat (const string& _shortName, const string& _longName,
|
||||
const string& _default = "",
|
||||
const string& _description="", bool _required=false) {
|
||||
Param param ( _shortName, _longName, _default, Param::FLOAT, _description, _required );
|
||||
parse( param );
|
||||
params.push_back( param );
|
||||
|
||||
// now gets the value
|
||||
istrstream is( param.value().c_str());
|
||||
float retValue;
|
||||
is >> retValue;
|
||||
|
||||
if (!is) {
|
||||
throw Parser::BadType(param.longName().c_str(), param.value().c_str(), "float");
|
||||
return 0;
|
||||
} else {
|
||||
return retValue;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
string parse_string (istream & _is) {
|
||||
string paramValue;
|
||||
_is >> paramValue;
|
||||
//if the first character of the string or array is not a " => just one word or array-element.
|
||||
if( paramValue[0] != '\"' )
|
||||
return paramValue;
|
||||
|
||||
if( paramValue[1] == '\"' ) // the empty string
|
||||
return "" ;
|
||||
|
||||
//else => read until the next " (the end of the string).
|
||||
const char *c = paramValue.c_str();
|
||||
string tmpStr = c+1;// skip the "
|
||||
if (tmpStr[tmpStr.length()-1] == '\"') { // one word only
|
||||
//tmpStr[tmpStr.length()-1] = '\0';
|
||||
tmpStr.erase( &tmpStr[tmpStr.length()-1] );
|
||||
return tmpStr;
|
||||
}
|
||||
|
||||
bool stop = false;
|
||||
while (_is && !stop) {
|
||||
_is >> paramValue;
|
||||
// test last character of paramValue for "
|
||||
if (paramValue[paramValue.length()-1] == '\"') {
|
||||
paramValue.erase( ¶mValue[paramValue.length()-1] );
|
||||
//paramValue[paramValue.length()-1] = '\0';
|
||||
stop = true;
|
||||
}
|
||||
tmpStr = tmpStr + " " + paramValue ;
|
||||
}
|
||||
return tmpStr;
|
||||
};
|
||||
|
||||
|
||||
void parse (Param & param) {
|
||||
int i;
|
||||
string tmpStr, ReadStr, FirstWord;
|
||||
|
||||
// FIRST: look if the associated environment variables have any value, to use them.
|
||||
if( getenv( param.environment().c_str() ) ) {
|
||||
//cout <<"\t\t ENV param: ,"<<p->shortName()<<", ,"<<getenv(p->environment().c_str())<<endl;
|
||||
param.value(getenv(param.environment().c_str()) );
|
||||
}
|
||||
|
||||
|
||||
// SECOND: search the file parameter, if present
|
||||
if ( InputFileName != "" ) {
|
||||
ifstream is(InputFileName.c_str());
|
||||
while (is) {
|
||||
is >> tmpStr;
|
||||
if ( ( !strcmp(tmpStr.c_str(), param.shortName().c_str()) ) ||
|
||||
( !strcasecmp(tmpStr.c_str(), param.longName().c_str()) )
|
||||
) { // found the keyword
|
||||
|
||||
Param::valueType tmp = param.valType();
|
||||
switch ( tmp ) {
|
||||
case Param::TITLE:
|
||||
cerr << "Error, we should not be there" << endl;
|
||||
exit(1);
|
||||
break;
|
||||
case Param::BOOL :
|
||||
param.value("true" );
|
||||
break;
|
||||
|
||||
case Param::INT:
|
||||
case Param::UL:
|
||||
case Param::FLOAT:
|
||||
is >> tmpStr;
|
||||
param.value(tmpStr);
|
||||
break;
|
||||
|
||||
case Param::STRING:
|
||||
tmpStr = parse_string(is);
|
||||
param.value(tmpStr);
|
||||
break;
|
||||
|
||||
case Param::ARRAY:
|
||||
ReadStr = parse_string(is);
|
||||
if ( ReadStr != "<" ) { // no "<" ">" --> a single string in the array
|
||||
param.value(ReadStr);
|
||||
break;
|
||||
}
|
||||
// read next word - and keep it in case of <> mismatch
|
||||
FirstWord = parse_string(is);
|
||||
// test for empty array
|
||||
if (FirstWord == ">") {
|
||||
param.value("");
|
||||
break;
|
||||
}
|
||||
// else, read all words until ">"
|
||||
tmpStr = FirstWord;
|
||||
ReadStr = parse_string(is);
|
||||
while ( is && (ReadStr != ">") ) {
|
||||
tmpStr = tmpStr + " " + ReadStr;
|
||||
ReadStr = parse_string(is);
|
||||
}
|
||||
|
||||
if (!is) { // there was a "<" without the corresponding ">"
|
||||
throw Parser::BadArrayParam( param.longName(), FirstWord );
|
||||
param.value(FirstWord); // assume unique string
|
||||
}
|
||||
else
|
||||
param.value(tmpStr);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// LAST (highest priority) parse the command line arguments
|
||||
for (i=1 ; i<parse_argc ; i++)
|
||||
if( ( ! strcasecmp(param.longName().c_str(), parse_argv[i]) ) ||
|
||||
( ! strcmp(param.shortName().c_str(), parse_argv[i]) )
|
||||
) { // found the parameter name
|
||||
if (param.valType() == Param::BOOL) {
|
||||
//cout <<"BOOL: "<<parse_argv[i]<<" <-- true"<<endl;
|
||||
param.value("true");
|
||||
}else{
|
||||
if (param.valType() != Param::ARRAY) { //only if it is not an array
|
||||
//cout <<"TYPE: "<<parse_argv[i]<<" <-- "<<parse_argv[i+1]<<endl;
|
||||
param.value(parse_argv[i+1]);
|
||||
}else{ //if it is an ARRAY
|
||||
i++;
|
||||
ReadStr = parse_argv[i++];
|
||||
//cout <<"ARRAY: <-- ";
|
||||
|
||||
if ( ReadStr != "<" ) { // no "<" ">" --> a single string in the array
|
||||
param.value(ReadStr);
|
||||
}else{
|
||||
// read next word - and keep it in case of <> mismatch
|
||||
FirstWord = parse_argv[i++];
|
||||
|
||||
// test for empty array
|
||||
if (FirstWord == ">") {
|
||||
param.value("");
|
||||
}else{
|
||||
// else, read all words until ">"
|
||||
tmpStr = FirstWord;
|
||||
ReadStr = parse_argv[i++];
|
||||
while ( (i<parse_argc) && (ReadStr != ">") ) {
|
||||
tmpStr = tmpStr + " " + ReadStr;
|
||||
ReadStr = parse_argv[i++];
|
||||
}
|
||||
//cout <<"tmpStr ;"<<tmpStr<<"; ("<<i<<","<<parse_argc<<") "<<endl;
|
||||
|
||||
if ( (i>=parse_argc) && (ReadStr != ">") ) { // there was a "<" without the corresponding ">"
|
||||
throw Parser::BadArrayParam( param.longName(), FirstWord );
|
||||
param.value(FirstWord); // assume unique string
|
||||
}else{
|
||||
param.value(tmpStr);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
//MS after trying all possibilities, and if the value has not changed
|
||||
// though the parameter was required, protest!
|
||||
if (param.required() && !param.changed())
|
||||
throw Parser::MissingReqParam(param.shortName());
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Sets a new value for a param given its short name or its long name.
|
||||
* @param _name One of the names of the param.
|
||||
* @param _value Value to be assigned.
|
||||
* @exception UnknownArg if the param doesn't exist
|
||||
* @exception MissingVal if the param hasn't got a value
|
||||
*/
|
||||
Param::valueType setParamValue (const string& _name, const char* _value){
|
||||
vector<Param>::iterator pos;
|
||||
|
||||
for (pos=params.begin() ; pos!=params.end() ; pos++)
|
||||
if (pos->shortName()==_name || pos->longName()==_name)
|
||||
break;
|
||||
|
||||
// if found ...
|
||||
if (pos!=params.end()) {
|
||||
switch ( pos->valType() ) {
|
||||
case Param::TITLE:
|
||||
cerr << "Error, we should not be there" << endl;
|
||||
exit(1);
|
||||
break;
|
||||
case Param::BOOL :
|
||||
pos->value("true");
|
||||
break;
|
||||
case Param::ARRAY :
|
||||
case Param::INT:
|
||||
case Param::UL:
|
||||
case Param::FLOAT:
|
||||
case Param::STRING:
|
||||
if (_value != NULL){
|
||||
pos->value(_value);
|
||||
}else{
|
||||
throw Parser::MissingVal(_name);
|
||||
return Param::BOOL;
|
||||
}
|
||||
break;
|
||||
} // switch
|
||||
|
||||
return pos->valType();
|
||||
|
||||
}else{
|
||||
throw Parser::UnknownArg(_name);
|
||||
return Param::BOOL;
|
||||
}
|
||||
};
|
||||
|
||||
/// the output method - generate the .status file (unless other name is given)
|
||||
friend ostream & operator<< ( ostream & os, Parser & _parser )
|
||||
{
|
||||
vector<Param>::iterator p;
|
||||
//print every param with its value
|
||||
for ( p=_parser.params.begin(); p!=_parser.params.end(); p++ ) {
|
||||
switch ( p->valType() ) {
|
||||
case Param::BOOL :
|
||||
if( p->value() == (string) "true")
|
||||
os << p->longName();
|
||||
else
|
||||
os << "#" << p->longName() ; // so the name of the bool is commented out
|
||||
break;
|
||||
|
||||
case Param::INT:
|
||||
case Param::UL:
|
||||
case Param::FLOAT:
|
||||
os << p->longName()<<" "<<p->value();
|
||||
break;
|
||||
|
||||
case Param::ARRAY :
|
||||
os << p->longName() << " < " << p->value().c_str() << " >" ;
|
||||
break;
|
||||
case Param::STRING:
|
||||
os << p->longName()<<" \""<<p->value().c_str()<<"\" ";
|
||||
break;
|
||||
case Param::TITLE:
|
||||
os << endl; // Title is in the description below
|
||||
break;
|
||||
} // switch
|
||||
os << "\t #" << p->shortName() << " : " << p->description();
|
||||
if (p->valType() != Param::TITLE)
|
||||
os << " [" << p->defValue() << "]" ;
|
||||
os << endl;
|
||||
}
|
||||
return os;
|
||||
};
|
||||
|
||||
/**
|
||||
* Prints out the list of parameters in the output file (if specified)
|
||||
*/
|
||||
void outputParam(string _OutputFile="")
|
||||
{
|
||||
if (_OutputFile == "") {
|
||||
_OutputFile = parse_argv[0];
|
||||
_OutputFile += ".status";
|
||||
}
|
||||
|
||||
ofstream os(_OutputFile.c_str());
|
||||
os << "Parameters used by \"" << programName << "\" ("
|
||||
<< programDescription << ")" << endl << endl;
|
||||
os << *this;
|
||||
};
|
||||
|
||||
/**
|
||||
* Prints an automatic help in the standard output using the information
|
||||
* provided by parameters
|
||||
*/
|
||||
void printHelp() {
|
||||
vector<Param>::iterator p;
|
||||
// unsigned i;
|
||||
|
||||
// print program name and description
|
||||
cout << this->programName <<": "<<programDescription<<endl<<endl;
|
||||
|
||||
// print the usage when calling the program from the command line
|
||||
cout << "Usage: "<< programName<<" [Options]\n";
|
||||
// only short usage!
|
||||
cout << "Options of the form \"-ShortName value\" or \"--LongName value\"" << endl;
|
||||
|
||||
// for ( i=0,p=params.begin(); p!=params.end(); i++,p++ )
|
||||
// if( p->valType() != Param::TITLE ) {
|
||||
// if( p->valType() != Param::BOOL ){
|
||||
// cout << ( (!p->required())?"[":"");
|
||||
// cout <<p->shortName()<<" value"<<i;
|
||||
// cout << ( (!p->required())?"]":"")<<" ";
|
||||
// }else{
|
||||
// cout << "["<<p->shortName()<<"] ";
|
||||
// }
|
||||
// } // for p
|
||||
cout << "Where:"<<endl;
|
||||
|
||||
for ( p=params.begin(); p!=params.end(); p++ ) {
|
||||
if( p->valType() != Param::TITLE ) {
|
||||
// Victor: 04-Jan-2000
|
||||
// Modified because the - and -- prefixes are not needed.
|
||||
/*
|
||||
cout << "-" << p->shortName()
|
||||
<<", --"<<p->longName()<<":\t"
|
||||
<<p->description()<<endl;
|
||||
*/
|
||||
cout << p->shortName()
|
||||
<<", " << p->longName()<<":\t"
|
||||
<<p->description()<<endl;
|
||||
cout << "\t(";
|
||||
switch ( p->valType() ) {
|
||||
case Param::INT: cout <<"Integer"; break;
|
||||
case Param::UL: cout <<"Unsigned Long Integer"; break;
|
||||
case Param::FLOAT: cout <<"Float"; break;
|
||||
case Param::STRING: cout <<"String"; break;
|
||||
case Param::ARRAY: cout <<"An array of strings, enclosed within < >"; break;
|
||||
case Param::BOOL: cout << "Flag"; break;
|
||||
case Param::TITLE: break;
|
||||
} // switch
|
||||
if(p->valType() == Param::BOOL)
|
||||
cout << ") True if present" << endl;
|
||||
else
|
||||
cout<<") "<<( (p->required())?"Required":"Optional" )<<". By default: "<<p->defValue()<<endl;
|
||||
}
|
||||
else {
|
||||
cout << "\n\t # " << p->description() << endl;
|
||||
}
|
||||
} // for p
|
||||
cout << endl;
|
||||
};
|
||||
|
||||
/**
|
||||
* This class managges unknown argument exceptions.
|
||||
*/
|
||||
class UnknownArg : public logic_error {
|
||||
public:
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
* @param _arg string to be shown when the exception occurs
|
||||
*/
|
||||
UnknownArg( const string& _arg): logic_error( "Invalid argument: "+_arg ) { };
|
||||
};
|
||||
|
||||
/**
|
||||
* This class managges bad param types.
|
||||
*/
|
||||
class BadType : public logic_error {
|
||||
public:
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
* @param _param The param
|
||||
* @param _value The value of the param
|
||||
*/
|
||||
BadType(const string& _param, const string& _value, const string& _correctType)
|
||||
: logic_error("The value '" + _value + "' assigned to the argument " + _param + " isn't a correct "+_correctType) { };
|
||||
};
|
||||
|
||||
/**
|
||||
* This class managges exceptions produced when there isn't a value for a parameter.
|
||||
*/
|
||||
class MissingVal : public logic_error {
|
||||
public:
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
* @param _param The param
|
||||
*/
|
||||
MissingVal(const string& _param) : logic_error("Missing value for parameter " + _param) {};
|
||||
};
|
||||
|
||||
/**
|
||||
* This class managges exceptions produced when the user forgot a required parameter.
|
||||
*/
|
||||
class MissingReqParam : public logic_error {
|
||||
public:
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
* @param _shortName The param's short name
|
||||
*/
|
||||
MissingReqParam(const string& _shortName) : logic_error("Missing required parameter " + _shortName) {};
|
||||
};
|
||||
|
||||
/**
|
||||
* This class managges exceptions du to < without a > in array value
|
||||
*/
|
||||
class BadArrayParam : public logic_error {
|
||||
public:
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
* @param _param The param
|
||||
* @param _first_word The first word read after the "<"
|
||||
*/
|
||||
BadArrayParam(const string& _param, const string &_first_word) :
|
||||
logic_error("Array parameter " + _param + ": No matching > (" + _first_word
|
||||
+ "... )") {};
|
||||
};
|
||||
|
||||
void createParamFile( ostream& _os ) {
|
||||
vector<Param>::iterator p;
|
||||
for ( p=params.begin(); p!=params.end(); p++ ) {
|
||||
switch( p->valType() ) {
|
||||
case Param::TITLE:
|
||||
_os << endl << "# -- ";
|
||||
break;
|
||||
case Param::BOOL:
|
||||
_os << ((p->value()=="true" )?"":"#")
|
||||
<< p->longName();
|
||||
break;
|
||||
case Param::STRING:
|
||||
_os << p->longName()<<"\t\""<<p->value()<<"\"";
|
||||
break;
|
||||
case Param::ARRAY:
|
||||
_os << p->longName()<<"\t< "<<p->value()<<" >";
|
||||
break;
|
||||
default:
|
||||
_os << p->longName()<<"\t"<<p->value();
|
||||
break;
|
||||
} // switch
|
||||
_os << "\t #" << p->description() << endl;
|
||||
}
|
||||
}
|
||||
private:
|
||||
vector<Param> params;
|
||||
string programName;
|
||||
string programDescription;
|
||||
int parse_argc;
|
||||
char **parse_argv;
|
||||
string InputFileName;
|
||||
|
||||
};
|
||||
|
||||
|
||||
|
||||
|
||||
#endif
|
||||
|
|
@ -1,35 +0,0 @@
|
|||
// See eoParserUtils.h
|
||||
|
||||
#include <iostream.h>
|
||||
#include <eoParserUtils.h>
|
||||
/// Reproducible random seed
|
||||
|
||||
// For the Mersenne-Twister used in EO, the entire rng needs to be saved
|
||||
|
||||
//----------------------------------
|
||||
void InitRandom( Parser & parser) {
|
||||
//----------------------------------
|
||||
unsigned long _seed;
|
||||
try {
|
||||
_seed = parser.getUnsignedLong("-S", "--seed", "0",
|
||||
"Seed for Random number generator" );
|
||||
}
|
||||
catch (logic_error & e)
|
||||
{
|
||||
cout << e.what() << endl;
|
||||
parser.printHelp();
|
||||
exit(1);
|
||||
}
|
||||
|
||||
if (_seed == 0) { // use clock to get a "random" seed
|
||||
_seed = (unsigned long)( time( 0 ) );
|
||||
ostrstream s;
|
||||
s << _seed;
|
||||
parser.setParamValue("--seed", s.str()); // so it will be printed out in the status file, and canbe later re-used to re-run EXACTLY the same run
|
||||
}
|
||||
#error This does not work: load and save the entire state of the rng object.
|
||||
rng.reseed(_seed);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -1,24 +0,0 @@
|
|||
/*-------------------------------------------------------
|
||||
File..........: eoParserUtils.h
|
||||
Author........: Geneura Team, Marc Shoenauer
|
||||
(this file: Victor Rivas, vrivas@ujaen.es)
|
||||
Date..........: 17-Dec-1999
|
||||
Description...: Some useful things that use eoParser.
|
||||
Modifications.:
|
||||
------------------- 1 -------------------
|
||||
Author.......:
|
||||
Date.........:
|
||||
Description..:
|
||||
*/
|
||||
|
||||
#ifndef EO_PARSER_UTILS
|
||||
#define EO_PARSER_UTILS
|
||||
|
||||
#include <eoRNG.h>
|
||||
#include <eoParser.h>
|
||||
/// Reproducible random seed
|
||||
|
||||
//----------------------------------
|
||||
void InitRandom( Parser & parser);
|
||||
//----------------------------------
|
||||
#endif
|
||||
|
|
@ -1,45 +0,0 @@
|
|||
//-----------------------------------------------------------------------------
|
||||
|
||||
// eoProblem.h
|
||||
|
||||
// (c) GeNeura Team 1998
|
||||
|
||||
/*
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
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
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef EOPROBLEM_H
|
||||
#define EOPROBLEM_H
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
template<class T> class Problem
|
||||
{
|
||||
public:
|
||||
typedef T Chrom;
|
||||
typedef typename T::Gene Gene;
|
||||
typedef typename T::Fitness Fitness;
|
||||
|
||||
virtual Fitness operator()(const Chrom& chrom) = 0;
|
||||
};
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#endif EOPROBLEM_H
|
||||
|
||||
453
eo/src/eoRNG.h
453
eo/src/eoRNG.h
|
|
@ -1,453 +0,0 @@
|
|||
/*
|
||||
* Random number generator adapted from (see comments below)
|
||||
*
|
||||
* The random number generator is modified into a class
|
||||
* by Maarten Keijzer (mak@dhi.dk). Also added the Box-Muller
|
||||
* transformation to generate normal deviates.
|
||||
*
|
||||
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
|
||||
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
|
||||
*/
|
||||
|
||||
/* ************ DOCUMENTATION IN ORIGINAL FILE *********************/
|
||||
|
||||
// This is the ``Mersenne Twister'' random number generator MT19937, which
|
||||
// generates pseudorandom integers uniformly distributed in 0..(2^32 - 1)
|
||||
// starting from any odd seed in 0..(2^32 - 1). This version is a recode
|
||||
// by Shawn Cokus (Cokus@math.washington.edu) on March 8, 1998 of a version by
|
||||
// Takuji Nishimura (who had suggestions from Topher Cooper and Marc Rieffel in
|
||||
// July-August 1997).
|
||||
//
|
||||
// Effectiveness of the recoding (on Goedel2.math.washington.edu, a DEC Alpha
|
||||
// running OSF/1) using GCC -O3 as a compiler: before recoding: 51.6 sec. to
|
||||
// generate 300 million random numbers; after recoding: 24.0 sec. for the same
|
||||
// (i.e., 46.5% of original time), so speed is now about 12.5 million random
|
||||
// number generations per second on this machine.
|
||||
//
|
||||
// According to the URL <http://www.math.keio.ac.jp/~matumoto/emt.html>
|
||||
// (and paraphrasing a bit in places), the Mersenne Twister is ``designed
|
||||
// with consideration of the flaws of various existing generators,'' has
|
||||
// a period of 2^19937 - 1, gives a sequence that is 623-dimensionally
|
||||
// equidistributed, and ``has passed many stringent tests, including the
|
||||
// die-hard test of G. Marsaglia and the load test of P. Hellekalek and
|
||||
// S. Wegenkittl.'' It is efficient in memory usage (typically using 2506
|
||||
// to 5012 bytes of static data, depending on data type sizes, and the code
|
||||
// is quite short as well). It generates random numbers in batches of 624
|
||||
// at a time, so the caching and pipelining of modern systems is exploited.
|
||||
// It is also divide- and mod-free.
|
||||
//
|
||||
// This library is free software; you can redistribute it and/or modify it
|
||||
// under the terms of the GNU Library 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 Library General Public License for more details. You should have
|
||||
// received a copy of the GNU Library 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.
|
||||
//
|
||||
// The code as Shawn received it included the following notice:
|
||||
//
|
||||
// Copyright (C) 1997 Makoto Matsumoto and Takuji Nishimura. When
|
||||
// you use this, send an e-mail to <matumoto@math.keio.ac.jp> with
|
||||
// an appropriate reference to your work.
|
||||
//
|
||||
// It would be nice to CC: <Cokus@math.washington.edu> when you write.
|
||||
//
|
||||
|
||||
//
|
||||
// uint32 must be an unsigned integer type capable of holding at least 32
|
||||
// bits; exactly 32 should be fastest, but 64 is better on an Alpha with
|
||||
// GCC at -O3 optimization so try your options and see what's best for you
|
||||
//
|
||||
|
||||
/* ************ END DOCUMENTATION IN ORIGINAL FILE *********************/
|
||||
|
||||
|
||||
#ifndef EO_RANDOM_NUMBER_GENERATOR
|
||||
#define EO_RANDOM_NUMBER_GENERATOR
|
||||
|
||||
#include <ctime>
|
||||
|
||||
#include <eoPersistent.h>
|
||||
#include <eoObject.h>
|
||||
|
||||
// TODO: check for various compilers if this is exactly 32 bits
|
||||
// Unfortunately MSVC's preprocessor does not comprehends sizeof()
|
||||
// so neat preprocessing tricks will not work
|
||||
|
||||
typedef unsigned long uint32; // Compiler and platform dependent!
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoRng
|
||||
//-----------------------------------------------------------------------------
|
||||
/**
|
||||
eoRng is a persitent class that uses the ``Mersenne Twister'' random number generator MT19937
|
||||
for generating random numbers. The various member functions implement useful functions
|
||||
for evolutionary algorithms. Included are: rand(), random(), flip() and normal().
|
||||
|
||||
Note for people porting EO to other platforms: please make sure that the typedef
|
||||
uint32 in the file eoRng.h is exactly 32 bits long. It may be longer, but not
|
||||
shorter. If it is longer, file compatibility between EO on different platforms
|
||||
may be broken.
|
||||
*/
|
||||
class eoRng : public eoObject, public eoPersistent
|
||||
{
|
||||
public :
|
||||
/**
|
||||
ctor takes a random seed; if you want another seed, use reseed
|
||||
@see reseed
|
||||
*/
|
||||
|
||||
eoRng(uint32 s = (uint32) time(0) ) : state(0), next(0), left(-1), cached(false), N(624), M(397), K(0x9908B0DFU) {
|
||||
state = new uint32[N+1];
|
||||
initialize(s);
|
||||
}
|
||||
|
||||
~eoRng(void)
|
||||
{
|
||||
delete [] state;
|
||||
}
|
||||
|
||||
/**
|
||||
Re-initializes the Random Number Generator.
|
||||
*/
|
||||
void reseed(uint32 s)
|
||||
{
|
||||
initialize(s);
|
||||
}
|
||||
|
||||
/**
|
||||
uniform(m = 1.0) returns a random double in the range [0, m)
|
||||
*/
|
||||
double uniform(double m = 1.0)
|
||||
{ // random number between [0, m]
|
||||
return m * double(rand()) / double(rand_max());
|
||||
}
|
||||
|
||||
/**
|
||||
random() returns a random integer in the range [0, m)
|
||||
*/
|
||||
uint32 random(uint32 m)
|
||||
{
|
||||
return uint32(uniform() * double(m));
|
||||
}
|
||||
|
||||
/**
|
||||
flip() tosses a biased coin such that flip(x/100.0) will
|
||||
returns true x% of the time
|
||||
*/
|
||||
bool flip(float bias)
|
||||
{
|
||||
return uniform() < bias;
|
||||
}
|
||||
|
||||
/**
|
||||
normal() zero mean gaussian deviate with standard deviation of 1
|
||||
*/
|
||||
double normal(void); // gaussian mutation, stdev 1
|
||||
|
||||
/**
|
||||
normal(stdev) zero mean gaussian deviate with user defined standard deviation
|
||||
*/
|
||||
double normal(double stdev)
|
||||
{
|
||||
return stdev * normal();
|
||||
}
|
||||
|
||||
/**
|
||||
normal(mean, stdev) user defined mean gaussian deviate with user defined standard deviation
|
||||
*/
|
||||
double normal(double mean, double stdev)
|
||||
{
|
||||
return mean + normal(stdev);
|
||||
}
|
||||
|
||||
/**
|
||||
rand() returns a random number in the range [0, rand_max)
|
||||
*/
|
||||
uint32 rand();
|
||||
|
||||
/**
|
||||
rand_max() the maximum returned by rand()
|
||||
*/
|
||||
uint32 rand_max(void) const { return (uint32) 0xffffffff; }
|
||||
|
||||
/**
|
||||
roulette_wheel(vec, total = 0) does a roulette wheel selection
|
||||
on the input vector vec. If the total is not supplied, it is
|
||||
calculated. It returns an integer denoting the selected argument.
|
||||
*/
|
||||
template <class T>
|
||||
int roulette_wheel(const std::vector<T>& vec, T total = 0)
|
||||
{
|
||||
if (total == 0)
|
||||
{ // count
|
||||
for (unsigned i = 0; i < vec.size(); ++i)
|
||||
total += vec[i];
|
||||
}
|
||||
|
||||
float change = uniform() * total;
|
||||
|
||||
int i = 0;
|
||||
|
||||
while (change > 0)
|
||||
{
|
||||
change -= vec[i++];
|
||||
}
|
||||
|
||||
return --i;
|
||||
}
|
||||
|
||||
///
|
||||
void printOn(ostream& _os) const
|
||||
{
|
||||
for (int i = 0; i < N; ++i)
|
||||
{
|
||||
_os << state[i] << ' ';
|
||||
}
|
||||
_os << int(next - state) << ' ';
|
||||
_os << left << ' ' << cached << ' ' << cacheValue;
|
||||
}
|
||||
|
||||
///
|
||||
void readFrom(istream& _is)
|
||||
{
|
||||
for (int i = 0; i < N; ++i)
|
||||
{
|
||||
_is >> state[i];
|
||||
}
|
||||
|
||||
int n;
|
||||
_is >> n;
|
||||
next = state + n;
|
||||
|
||||
_is >> left;
|
||||
_is >> cached;
|
||||
_is >> cacheValue;
|
||||
}
|
||||
|
||||
|
||||
private :
|
||||
uint32 restart(void);
|
||||
void initialize(uint32 seed);
|
||||
|
||||
uint32* state; // the array for the state
|
||||
uint32* next;
|
||||
int left;
|
||||
|
||||
bool cached;
|
||||
float cacheValue;
|
||||
|
||||
const int N;
|
||||
const int M;
|
||||
const uint32 K; // a magic constant
|
||||
|
||||
/**
|
||||
Private copy ctor and assignment operator to make sure that
|
||||
nobody accidentally copies the random number generator.
|
||||
If you want similar RNG's, make two RNG's and initialize
|
||||
them with the same seed.
|
||||
*/
|
||||
eoRng (const eoRng&); // no implementation
|
||||
eoRng& operator=(const eoRng&); // dito
|
||||
};
|
||||
|
||||
/**
|
||||
The one and only global eoRng object
|
||||
*/
|
||||
extern eoRng rng;
|
||||
|
||||
/**
|
||||
The class uniform_generator can be used in the STL generate function
|
||||
to easily generate random floats and doubles between [0, _max). _max
|
||||
defaults to 1.0
|
||||
*/
|
||||
template <class T = double> class uniform_generator
|
||||
{
|
||||
public :
|
||||
uniform_generator(T _max = T(1.0), eoRng& _rng = rng) : maxim(_max), uniform(_rng) {}
|
||||
|
||||
virtual T operator()(void) { return (T) uniform.uniform(maxim); }
|
||||
private :
|
||||
T maxim;
|
||||
eoRng& uniform;
|
||||
};
|
||||
|
||||
/**
|
||||
The class random_generator can be used in the STL generate function
|
||||
to easily generate random ints between [0, _max).
|
||||
*/
|
||||
template <class T = uint32> class random_generator
|
||||
{
|
||||
public :
|
||||
random_generator(int _max, eoRng& _rng = rng) : maxim(_max), random(_rng) {}
|
||||
|
||||
virtual T operator()(void) { return (T) random.random(max); }
|
||||
|
||||
private :
|
||||
T maxim;
|
||||
eoRng& random;
|
||||
};
|
||||
|
||||
/**
|
||||
The class normal_generator can be used in the STL generate function
|
||||
to easily generate gaussian distributed floats and doubles. The user
|
||||
can supply a standard deviation which defaults to 1.
|
||||
*/
|
||||
template <class T = double> class normal_generator
|
||||
{
|
||||
public :
|
||||
normal_generator(T _stdev = T(1.0), eoRng& _rng = rng) : stdev(_stdev), normal(_rng) {}
|
||||
|
||||
virtual T operator()(void) { return (T) normal.normal(stdev); }
|
||||
|
||||
private :
|
||||
T stdev;
|
||||
eoRng& normal;
|
||||
};
|
||||
|
||||
// Implementation of some eoRng members.... Don't mind the mess, it does work.
|
||||
|
||||
|
||||
#define hiBit(u) ((u) & 0x80000000U) // mask all but highest bit of u
|
||||
#define loBit(u) ((u) & 0x00000001U) // mask all but lowest bit of u
|
||||
#define loBits(u) ((u) & 0x7FFFFFFFU) // mask the highest bit of u
|
||||
#define mixBits(u, v) (hiBit(u)|loBits(v)) // move hi bit of u to hi bit of v
|
||||
|
||||
inline void eoRng::initialize(uint32 seed)
|
||||
{
|
||||
//
|
||||
// We initialize state[0..(N-1)] via the generator
|
||||
//
|
||||
// x_new = (69069 * x_old) mod 2^32
|
||||
//
|
||||
// from Line 15 of Table 1, p. 106, Sec. 3.3.4 of Knuth's
|
||||
// _The Art of Computer Programming_, Volume 2, 3rd ed.
|
||||
//
|
||||
// Notes (SJC): I do not know what the initial state requirements
|
||||
// of the Mersenne Twister are, but it seems this seeding generator
|
||||
// could be better. It achieves the maximum period for its modulus
|
||||
// (2^30) iff x_initial is odd (p. 20-21, Sec. 3.2.1.2, Knuth); if
|
||||
// x_initial can be even, you have sequences like 0, 0, 0, ...;
|
||||
// 2^31, 2^31, 2^31, ...; 2^30, 2^30, 2^30, ...; 2^29, 2^29 + 2^31,
|
||||
// 2^29, 2^29 + 2^31, ..., etc. so I force seed to be odd below.
|
||||
//
|
||||
// Even if x_initial is odd, if x_initial is 1 mod 4 then
|
||||
//
|
||||
// the lowest bit of x is always 1,
|
||||
// the next-to-lowest bit of x is always 0,
|
||||
// the 2nd-from-lowest bit of x alternates ... 0 1 0 1 0 1 0 1 ... ,
|
||||
// the 3rd-from-lowest bit of x 4-cycles ... 0 1 1 0 0 1 1 0 ... ,
|
||||
// the 4th-from-lowest bit of x has the 8-cycle ... 0 0 0 1 1 1 1 0 ... ,
|
||||
// ...
|
||||
//
|
||||
// and if x_initial is 3 mod 4 then
|
||||
//
|
||||
// the lowest bit of x is always 1,
|
||||
// the next-to-lowest bit of x is always 1,
|
||||
// the 2nd-from-lowest bit of x alternates ... 0 1 0 1 0 1 0 1 ... ,
|
||||
// the 3rd-from-lowest bit of x 4-cycles ... 0 0 1 1 0 0 1 1 ... ,
|
||||
// the 4th-from-lowest bit of x has the 8-cycle ... 0 0 1 1 1 1 0 0 ... ,
|
||||
// ...
|
||||
//
|
||||
// The generator's potency (min. s>=0 with (69069-1)^s = 0 mod 2^32) is
|
||||
// 16, which seems to be alright by p. 25, Sec. 3.2.1.3 of Knuth. It
|
||||
// also does well in the dimension 2..5 spectral tests, but it could be
|
||||
// better in dimension 6 (Line 15, Table 1, p. 106, Sec. 3.3.4, Knuth).
|
||||
//
|
||||
// Note that the random number user does not see the values generated
|
||||
// here directly since restart() will always munge them first, so maybe
|
||||
// none of all of this matters. In fact, the seed values made here could
|
||||
// even be extra-special desirable if the Mersenne Twister theory says
|
||||
// so-- that's why the only change I made is to restrict to odd seeds.
|
||||
//
|
||||
|
||||
left = -1;
|
||||
|
||||
register uint32 x = (seed | 1U) & 0xFFFFFFFFU, *s = state;
|
||||
register int j;
|
||||
|
||||
for(left=0, *s++=x, j=N; --j;
|
||||
*s++ = (x*=69069U) & 0xFFFFFFFFU);
|
||||
}
|
||||
|
||||
|
||||
inline uint32 eoRng::restart(void)
|
||||
{
|
||||
register uint32 *p0=state, *p2=state+2, *pM=state+M, s0, s1;
|
||||
register int j;
|
||||
|
||||
left=N-1, next=state+1;
|
||||
|
||||
for(s0=state[0], s1=state[1], j=N-M+1; --j; s0=s1, s1=*p2++)
|
||||
*p0++ = *pM++ ^ (mixBits(s0, s1) >> 1) ^ (loBit(s1) ? K : 0U);
|
||||
|
||||
for(pM=state, j=M; --j; s0=s1, s1=*p2++)
|
||||
*p0++ = *pM++ ^ (mixBits(s0, s1) >> 1) ^ (loBit(s1) ? K : 0U);
|
||||
|
||||
s1=state[0], *p0 = *pM ^ (mixBits(s0, s1) >> 1) ^ (loBit(s1) ? K : 0U);
|
||||
s1 ^= (s1 >> 11);
|
||||
s1 ^= (s1 << 7) & 0x9D2C5680U;
|
||||
s1 ^= (s1 << 15) & 0xEFC60000U;
|
||||
return(s1 ^ (s1 >> 18));
|
||||
}
|
||||
|
||||
|
||||
inline uint32 eoRng::rand(void)
|
||||
{
|
||||
uint32 y;
|
||||
|
||||
if(--left < 0)
|
||||
return(restart());
|
||||
|
||||
y = *next++;
|
||||
y ^= (y >> 11);
|
||||
y ^= (y << 7) & 0x9D2C5680U;
|
||||
y ^= (y << 15) & 0xEFC60000U;
|
||||
return(y ^ (y >> 18));
|
||||
}
|
||||
|
||||
inline double eoRng::normal(void)
|
||||
{
|
||||
if (cached)
|
||||
{
|
||||
cached = false;
|
||||
return cacheValue;
|
||||
}
|
||||
|
||||
float rSquare, factor, var1, var2;
|
||||
|
||||
do
|
||||
{
|
||||
var1 = 2.0 * uniform() - 1.0;
|
||||
var2 = 2.0 * uniform() - 1.0;
|
||||
|
||||
rSquare = var1 * var1 + var2 * var2;
|
||||
}
|
||||
while (rSquare >= 1.0 || rSquare == 0.0);
|
||||
|
||||
factor = sqrt(-2.0 * log(rSquare) / rSquare);
|
||||
|
||||
cacheValue = var1 * factor;
|
||||
cached = true;
|
||||
|
||||
return (var2 * factor);
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
|
|
@ -1,148 +0,0 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoString.h
|
||||
// (c) GeNeura Team, 1998
|
||||
/*
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
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
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _eoString_H
|
||||
#define _eoString_H
|
||||
|
||||
// STL libraries
|
||||
#include <string>
|
||||
#include <stdexcept>
|
||||
|
||||
using namespace std;
|
||||
|
||||
// EO headers
|
||||
#include <eo1d.h>
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoString
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
/** Adaptor that turns an STL string into an EO */
|
||||
template <class fitnessT >
|
||||
class eoString: public eo1d<char, fitnessT>, public string {
|
||||
public:
|
||||
|
||||
/// Canonical part of the objects: several ctors, copy ctor, dtor and assignment operator
|
||||
//@{
|
||||
/// ctor
|
||||
eoString( const string& _str ="" )
|
||||
: eo1d<char, fitnessT>(), string( _str ) {};
|
||||
|
||||
|
||||
/** Ctor using a random number generator
|
||||
@param _size Lineal length of the object
|
||||
@param _rnd a random number generator, which returns a random value each time it´s called
|
||||
*/
|
||||
eoString( unsigned _size, eoRnd<char>& _rnd )
|
||||
: eo1d<char, fitnessT>(), string(){
|
||||
for ( unsigned i = 0; i < _size; i ++ ) {
|
||||
*this += _rnd();
|
||||
}
|
||||
};
|
||||
|
||||
/** Ctor from a stream
|
||||
@param _s input stream
|
||||
*/
|
||||
eoString( istream & _s )
|
||||
: eo1d<char, fitnessT>(){
|
||||
_s >> *this;
|
||||
};
|
||||
|
||||
/// copy ctor
|
||||
eoString( const eoString<fitnessT>& _eoStr )
|
||||
:eo1d<char, fitnessT>( static_cast<const eo1d<char, fitnessT> & > ( _eoStr ) ),
|
||||
string( _eoStr ){};
|
||||
|
||||
/// Assignment operator
|
||||
const eoString& operator =( const eoString& _eoStr ) {
|
||||
if ( this != & _eoStr ) {
|
||||
eo1d<char, fitnessT>::operator = ( _eoStr );
|
||||
string::operator = ( _eoStr );
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
/// dtor
|
||||
virtual ~eoString() {};
|
||||
//@}
|
||||
|
||||
|
||||
/** methods that implement the eo1d <em>protocol</em>
|
||||
@exception out_of_range if _i is larger than EO´s size
|
||||
*/
|
||||
virtual char getGene( unsigned _i ) const {
|
||||
if ( _i >= length() )
|
||||
throw out_of_range( "out_of_range when reading gene");
|
||||
return (*this)[_i];
|
||||
};
|
||||
|
||||
/** methods that implement the eo1d <em>protocol</em>
|
||||
@exception out_of_range if _i is larger than EO´s size
|
||||
*/
|
||||
virtual void setGene( unsigned _i, const char& _value ) {
|
||||
if ( _i >= size() )
|
||||
throw out_of_range( "out_of_range when writing a gene");
|
||||
(*this)[_i] = _value;
|
||||
};
|
||||
|
||||
/** Inserts a value after _i, displacing anything to the right
|
||||
@exception out_of_range if _i is larger than EO´s size
|
||||
*/
|
||||
virtual void insertGene( unsigned _i, char _val ) {
|
||||
if (_i <= this->size() ) {
|
||||
string::iterator i = this->begin()+_i;
|
||||
this->insert( i, _val );
|
||||
} else
|
||||
throw out_of_range( "out_of_range when inserting gene");
|
||||
};
|
||||
|
||||
/** Eliminates the gene at position _i
|
||||
@exception out_of_range if _i is larger than EO´s size
|
||||
*/
|
||||
virtual void deleteGene( unsigned _i ) {
|
||||
if (_i < this->size() ) {
|
||||
string::iterator i = this->begin()+_i;
|
||||
this->erase( i );
|
||||
} else
|
||||
throw out_of_range( "out_of_range when deleting gene");
|
||||
};
|
||||
|
||||
/// methods that implement the EO <em>protocol</em>
|
||||
virtual unsigned length() const { return this->size(); };
|
||||
|
||||
/** @name Methods from eoObject
|
||||
readFrom and printOn are directly inherited from eo1d
|
||||
*/
|
||||
//@{
|
||||
/** Inherited from eoObject
|
||||
@see eoObject
|
||||
*/
|
||||
virtual string className() const {return "eoString";};
|
||||
//@}
|
||||
|
||||
|
||||
};
|
||||
|
||||
#endif
|
||||
|
||||
|
|
@ -1,78 +0,0 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoStringMutation.h
|
||||
// (c) GeNeura Team, 1999
|
||||
/*
|
||||
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
|
||||
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
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _EOSTRINGMUTATION_H
|
||||
#define _EOSRTINGMUTATION_H
|
||||
|
||||
#include <math.h>
|
||||
// EO includes
|
||||
#include <eoOp.h>
|
||||
#include <eoUniform.h>
|
||||
#include <eoMutation.h>
|
||||
|
||||
/** Mutation of an eoString.
|
||||
The eoString's genes are changed by adding or substracting 1 to
|
||||
*/
|
||||
|
||||
template <class EOT>
|
||||
class eoStringMutation: public eoMutation<EOT> {
|
||||
public:
|
||||
|
||||
///
|
||||
eoStringMutation(const double _rate=0.0) : eoMutation< EOT >(_rate) {};
|
||||
|
||||
///
|
||||
virtual ~eoStringMutation() {};
|
||||
|
||||
/** @name Methods from eoObject
|
||||
*/
|
||||
//@{
|
||||
/** Inherited from eoObject
|
||||
@see eoObject
|
||||
*/
|
||||
string className() const {return "eoStringMutation";};
|
||||
//@}
|
||||
|
||||
|
||||
private:
|
||||
|
||||
#ifdef _MSC_VER
|
||||
typedef EOT::Type Type;
|
||||
#else
|
||||
typedef typename EOT::Type Type;
|
||||
#endif
|
||||
|
||||
/// applies operator to one gene in the EO. It increments or decrements the value of that gene by one.
|
||||
virtual void applyAt( EOT& _eo, unsigned _i ) const {
|
||||
eoUniform<double> uniform( 0, 1 );
|
||||
if( rate < uniform() ) {
|
||||
_eo.gene(_i) += ( uniform()>=0.5 )? (1) : (-1) ;
|
||||
}
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#endif
|
||||
|
|
@ -1,85 +0,0 @@
|
|||
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
-----------------------------------------------------------------------------
|
||||
rnd_generators.h
|
||||
Some utility functors for generating random generators:
|
||||
uniform_generator : generates uniform floats or doubles
|
||||
random_generator : generates unsigneds, ints etc.
|
||||
normal_generator : normally distributed floats or doubles
|
||||
|
||||
(c) Maarten Keijzer (mak@dhi.dk) and GeNeura Team, 1999, 2000
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
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
|
||||
*/
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef eoRND_GENERATORS_H
|
||||
#define eoRND_GENERATORS_H
|
||||
|
||||
#include "eoRNG.h"
|
||||
|
||||
/**
|
||||
The class uniform_generator can be used in the STL generate function
|
||||
to easily generate random floats and doubles between [0, _max). _max
|
||||
defaults to 1.0
|
||||
*/
|
||||
template <class T = double> class uniform_generator
|
||||
{
|
||||
public :
|
||||
uniform_generator(T _max = T(1.0), eoRng& _rng = rng) : maxim(_max), uniform(_rng) {}
|
||||
|
||||
virtual T operator()(void) { return (T) uniform.uniform(maxim); }
|
||||
private :
|
||||
T maxim;
|
||||
eoRng& uniform;
|
||||
};
|
||||
|
||||
/**
|
||||
The class random_generator can be used in the STL generate function
|
||||
to easily generate random ints between [0, _max).
|
||||
*/
|
||||
template <class T = uint32> class random_generator
|
||||
{
|
||||
public :
|
||||
random_generator(int _max, eoRng& _rng = rng) : maxim(_max), random(_rng) {}
|
||||
|
||||
virtual T operator()(void) { return (T) random.random(max); }
|
||||
|
||||
private :
|
||||
T maxim;
|
||||
eoRng& random;
|
||||
};
|
||||
|
||||
/**
|
||||
The class normal_generator can be used in the STL generate function
|
||||
to easily generate gaussian distributed floats and doubles. The user
|
||||
can supply a standard deviation which defaults to 1.
|
||||
*/
|
||||
template <class T = double> class normal_generator
|
||||
{
|
||||
public :
|
||||
normal_generator(T _stdev = T(1.0), eoRng& _rng = rng) : stdev(_stdev), normal(_rng) {}
|
||||
|
||||
virtual T operator()(void) { return (T) normal.normal(stdev); }
|
||||
|
||||
private :
|
||||
T stdev;
|
||||
eoRng& normal;
|
||||
};
|
||||
|
||||
#endif
|
||||
|
|
@ -1,313 +0,0 @@
|
|||
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
-----------------------------------------------------------------------------
|
||||
selectors.h
|
||||
A bunch of useful selector functions. They generally have three forms:
|
||||
|
||||
template <class It>
|
||||
It select(It begin, It end, params, eoRng& gen = rng);
|
||||
|
||||
template <class EOT>
|
||||
const EOT& select(const eoPop<EOT>& pop, params, eoRng& gen = rng);
|
||||
|
||||
template <class EOT>
|
||||
EOT& select(eoPop<EOT>& pop, params, eoRng& gen = rng);
|
||||
|
||||
where select is one of: roulette_wheel, deterministic_tournament
|
||||
and stochastic_tournament (at the moment).
|
||||
|
||||
(c) Maarten Keijzer (mak@dhi.dk) and GeNeura Team, 1999, 2000
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
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
|
||||
*/
|
||||
|
||||
#ifndef SELECT__H
|
||||
#define SELECT__H
|
||||
|
||||
#include "eoRNG.h"
|
||||
#include "eoException.h"
|
||||
|
||||
template <class EOT>
|
||||
bool minimizing_fitness()
|
||||
{
|
||||
EOT eo1; // Assuming people don't do anything fancy in the default constructor!
|
||||
EOT eo2;
|
||||
|
||||
/* Dear user, when the two line below do not compile you are most
|
||||
likely not working with scalar fitness values. In that case we're sorry
|
||||
but you cannot use lottery or roulette_wheel selection...
|
||||
*/
|
||||
eo1.fitness(0.0); // tried to cast it to an EOT::Fitness, but for some reason GNU barfs on this
|
||||
eo2.fitness(1.0);
|
||||
|
||||
return eo2 < eo1; // check whether we have a minimizing fitness
|
||||
};
|
||||
|
||||
inline double scale_fitness(const std::pair<double, double>& _minmax, double _value)
|
||||
{
|
||||
if (_minmax.first == _minmax.second)
|
||||
{
|
||||
return 0.0; // no differences in fitness, population converged!
|
||||
}
|
||||
// else
|
||||
|
||||
return (_value - _minmax.first) / (_minmax.second - _minmax.first);
|
||||
}
|
||||
|
||||
template <class It>
|
||||
double sum_fitness(It begin, It end)
|
||||
{
|
||||
double sum = 0.0;
|
||||
|
||||
for (; begin != end; ++begin)
|
||||
{
|
||||
double v = static_cast<double>(begin->fitness());
|
||||
if (v < 0.0)
|
||||
throw eoNegativeFitnessException();
|
||||
sum += v;
|
||||
}
|
||||
|
||||
return sum;
|
||||
}
|
||||
|
||||
template <class EOT>
|
||||
double sum_fitness(const eoPop<EOT>& _pop)
|
||||
{
|
||||
return sum_fitness(_pop.begin(), _pop.end());
|
||||
}
|
||||
|
||||
template <class EOT>
|
||||
double sum_fitness(const eoPop<EOT>& _pop, std::pair<double, double>& _minmax)
|
||||
{
|
||||
eoPop<EOT>::const_iterator it = _pop.begin();
|
||||
|
||||
_minmax.first = it->fitness();
|
||||
_minmax.second = it++->fitness();
|
||||
|
||||
for(; it != _pop.end(); ++it)
|
||||
{
|
||||
double v = static_cast<double>(it->fitness());
|
||||
|
||||
_minmax.first = std::min(_minmax.first, v);
|
||||
_minmax.second = std::max(_minmax.second, v);
|
||||
|
||||
rawTotal += v;
|
||||
}
|
||||
|
||||
if (minimizing_fitness<EOT>())
|
||||
{
|
||||
std::swap(_minmax.first, _minmax.second);
|
||||
}
|
||||
|
||||
scaledTotal = 0.0;
|
||||
|
||||
// unfortunately a second loop is neccessary to scale the fitness
|
||||
for (it = _pop.begin(); it != _pop.end(); ++it)
|
||||
{
|
||||
double v = scale_fitness(static_cast<double>(it->fitness()));
|
||||
|
||||
scaledTotal += v;
|
||||
}
|
||||
}
|
||||
|
||||
template <class It>
|
||||
It roulette_wheel(It _begin, It _end, double total, eoRng& _gen = rng)
|
||||
{
|
||||
float roulette = _gen.uniform(total);
|
||||
|
||||
It i = _begin;
|
||||
|
||||
while (roulette > 0.0)
|
||||
{
|
||||
roulette -= static_cast<double>(*(i++));
|
||||
}
|
||||
|
||||
return --i;
|
||||
}
|
||||
|
||||
template <class EOT>
|
||||
const EOT& roulette_wheel(const eoPop<EOT>& _pop, double total, eoRng& _gen = rng)
|
||||
{
|
||||
float roulette = _gen.uniform(total);
|
||||
|
||||
eoPop<EOT>::const_iterator i = _pop.begin();
|
||||
|
||||
while (roulette > 0.0)
|
||||
{
|
||||
roulette -= static_cast<double>((i++)->fitness());
|
||||
}
|
||||
|
||||
return *--i;
|
||||
}
|
||||
|
||||
template <class EOT>
|
||||
EOT& roulette_wheel(eoPop<EOT>& _pop, double total, eoRng& _gen = rng)
|
||||
{
|
||||
float roulette = _gen.uniform(total);
|
||||
|
||||
eoPop<EOT>::iterator i = _pop.begin();
|
||||
|
||||
while (roulette > 0.0)
|
||||
{
|
||||
roulette -= static_cast<double>((i++)->fitness());
|
||||
}
|
||||
|
||||
return *--i;
|
||||
}
|
||||
|
||||
template <class It>
|
||||
It deterministic_tournament(It _begin, It _end, unsigned _t_size, eoRng& _gen = rng)
|
||||
{
|
||||
It best = _begin + _gen.random(_end - _begin);
|
||||
|
||||
for (unsigned i = 0; i < _t_size - 1; ++i)
|
||||
{
|
||||
It competitor = _begin + _gen.random(_end - _begin);
|
||||
|
||||
if (*best < *competitor)
|
||||
{
|
||||
best = competitor;
|
||||
}
|
||||
}
|
||||
|
||||
return best;
|
||||
}
|
||||
|
||||
template <class EOT>
|
||||
const EOT& deterministic_tournament(const eoPop<EOT>& _pop, unsigned _t_size, eoRng& _gen = rng)
|
||||
{
|
||||
return *deterministic_tournament(_pop.begin(), _pop.end(), _t_size, _gen);
|
||||
}
|
||||
|
||||
template <class EOT>
|
||||
EOT& deterministic_tournament(eoPop<EOT>& _pop, unsigned _t_size, eoRng& _gen = rng)
|
||||
{
|
||||
return *deterministic_tournament(_pop.begin(), _pop.end(), _t_size, _gen);
|
||||
}
|
||||
|
||||
template <class It>
|
||||
It inverse_deterministic_tournament(It _begin, It _end, unsigned _t_size, eoRng& _gen = rng)
|
||||
{
|
||||
It worst = _begin + _gen.random(_end - _begin);
|
||||
|
||||
for (unsigned i = 0; i < _t_size - 1; ++i)
|
||||
{
|
||||
It competitor = _begin + _gen.random(_end - _begin);
|
||||
|
||||
if (competitor == worst)
|
||||
{
|
||||
--i;
|
||||
continue; // try again
|
||||
}
|
||||
|
||||
if (*competitor < *worst)
|
||||
{
|
||||
worst = competitor;
|
||||
}
|
||||
}
|
||||
|
||||
return worst;
|
||||
}
|
||||
|
||||
template <class EOT>
|
||||
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);
|
||||
}
|
||||
|
||||
template <class EOT>
|
||||
EOT& inverse_deterministic_tournament(eoPop<EOT>& _pop, unsigned _t_size, eoRng& _gen = rng)
|
||||
{
|
||||
return *inverse_deterministic_tournament(_pop.begin(), _pop.end(), _t_size, _gen);
|
||||
}
|
||||
|
||||
template <class It>
|
||||
It stochastic_tournament(It _begin, It _end, double _t_rate, eoRng& _gen = rng)
|
||||
{
|
||||
It i1 = _begin + _gen.random(_end - _begin);
|
||||
It i2 = _begin + _gen.random(_end - _begin);
|
||||
|
||||
bool return_better = _gen.flip(_t_rate);
|
||||
|
||||
if (*i1 < *i2)
|
||||
{
|
||||
if (return_better) return i2;
|
||||
// else
|
||||
|
||||
return i1;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (return_better) return i1;
|
||||
// else
|
||||
}
|
||||
// else
|
||||
|
||||
return i2;
|
||||
}
|
||||
|
||||
template <class EOT>
|
||||
const EOT& stochastic_tournament(const eoPop<EOT>& _pop, double _t_rate, eoRng& _gen = rng)
|
||||
{
|
||||
return *stochastic_tournament(_pop.begin(), _pop.end(), _t_rate, _gen);
|
||||
}
|
||||
|
||||
template <class EOT>
|
||||
EOT& stochastic_tournament(eoPop<EOT>& _pop, double _t_rate, eoRng& _gen = rng)
|
||||
{
|
||||
return *stochastic_tournament(_pop.begin(), _pop.end(), _t_rate, _gen);
|
||||
}
|
||||
|
||||
template <class It>
|
||||
It inverse_stochastic_tournament(It _begin, It _end, double _t_rate, eoRng& _gen = rng)
|
||||
{
|
||||
It i1 = _begin + _gen.random(_end - _begin);
|
||||
It i2 = _begin + _gen.random(_end - _begin);
|
||||
|
||||
bool return_worse = _gen.flip(_t_rate);
|
||||
|
||||
if (*i1 < *i2)
|
||||
{
|
||||
if (return_worse) return i1;
|
||||
// else
|
||||
|
||||
return i2;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (return_worse) return i2;
|
||||
// else
|
||||
}
|
||||
// else
|
||||
|
||||
return i1;
|
||||
}
|
||||
|
||||
template <class EOT>
|
||||
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);
|
||||
}
|
||||
|
||||
template <class EOT>
|
||||
EOT& inverse_stochastic_tournament(eoPop<EOT>& _pop, double _t_rate, eoRng& _gen = rng)
|
||||
{
|
||||
return *inverse_stochastic_tournament(_pop.begin(), _pop.end(), _t_rate, _gen);
|
||||
}
|
||||
|
||||
|
||||
#endif
|
||||
Loading…
Add table
Add a link
Reference in a new issue