diff --git a/eo/Makefile.am b/eo/Makefile.am index cb4127aa7..ba1a0dcc5 100644 --- a/eo/Makefile.am +++ b/eo/Makefile.am @@ -5,3 +5,8 @@ ############################################################################### SUBDIRS = src test +DOCDIR = ~/public_html/eodocs + +docs: + doc++ -d $(DOCDIR) -B foot.html -f src/*.h src/*.cpp + /home/jmerelo/bin/index -e html -i /home/jmerelo/index/neweo.idx /home/jmerelo/public_html/eodocs/ -v 3 \ No newline at end of file diff --git a/eo/src/EO.h b/eo/src/EO.h index bc5732008..9e71a4dea 100644 --- a/eo/src/EO.h +++ b/eo/src/EO.h @@ -1,137 +1,137 @@ -// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - -//----------------------------------------------------------------------------- -// EO.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 EO_H -#define EO_H - -//----------------------------------------------------------------------------- - -#include // runtime_error -#include -#include - -//----------------------------------------------------------------------------- -/** EO is a base class for evolvable objects, that is, the subjects of evolution. - EOs have only got a fitness, which at the same time needs to be only an object with the - operation less than (<) defined. Fitness says how good is the object; evolution or change - of these objects is left to the genetic operators. A fitness less than another means a - worse fitness, in whatever the context; thus, fitness is always maximized; although - it can be minimized with a proper definition of the < operator.\\ - The fitness object must have, besides an void ctor, a copy ctor. -*/ -template class EO: public eoObject, public eoPersistent -{ -public: - typedef F Fitness; - - /** Default constructor. - Fitness must have a ctor which takes 0 as a value; we can not use void ctors here - since default types like float have no void initializer. VC++ allows it, but gcc does not - */ - EO(): repFitness(0), invalidFitness(true) {} - - /** Ctor from stream. - Fitness must have defined the lecture from an istream. - */ - EO( istream& _is ) { - _is >> repFitness; - invalidFitness = false; - }; - - /// Copy ctor - EO( const EO& _eo ): repFitness( _eo.repFitness ), invalidFitness( _eo.invalidFitness ) {}; - - /// Virtual dtor - virtual ~EO() {}; - - /// Return fitness value. - Fitness fitness() const - { - if (invalid()) - //throw runtime_error("invalid fitness"); - cout << "invalid fitness" << endl; - return repFitness; - } - - // Set fitness as invalid. - void invalidate() { invalidFitness = true; } - - /** Set fitness. At the same time, validates it. - * @param _fitness New fitness value. - */ - void fitness(const Fitness& _fitness) - { - repFitness = _fitness; - invalidFitness = false; - } - - /** Return true If fitness value is invalid, false otherwise. - * @return true If fitness is invalid. - */ - bool invalid() const { return invalidFitness; } - - /** Returns true if - @return true if the fitness is higher - */ - bool operator<(const EO& _eo2) const { return fitness() < _eo2.fitness();} - - /// Methods inherited from eoObject - //@{ - - /** Return the class id. - * @return the class name as a string - */ - virtual string className() const { return "EO"; }; - - /** - * Read object.\\ - * Calls base class, just in case that one had something to do. The read and print - * methods should be compatible and have the same format. In principle, format is - * "plain": they just print a number - * @param _is a istream. - * @throw runtime_exception If a valid object can't be read. - */ - virtual void readFrom(istream& _is) { - _is >> repFitness; - invalidFitness = false; - } - - /** - * Write object. It's called printOn since it prints the object _on_ a stream. - * @param _os A ostream. - */ - virtual void printOn(ostream& _os) const { - _os << repFitness << endl; - } - - //@} - -private: - Fitness repFitness; // value of fitness for this chromosome - bool invalidFitness; // true if the value of fitness is invalid -}; - -//----------------------------------------------------------------------------- - -#endif EO_H +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// EO.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 EO_H +#define EO_H + +//----------------------------------------------------------------------------- + +#include // runtime_error +#include +#include + +//----------------------------------------------------------------------------- +/** EO is a base class for evolvable objects, that is, the subjects of evolution. + EOs have only got a fitness, which at the same time needs to be only an object with the + operation less than (<) defined. Fitness says how good is the object; evolution or change + of these objects is left to the genetic operators. A fitness less than another means a + worse fitness, in whatever the context; thus, fitness is always maximized; although + it can be minimized with a proper definition of the < operator.\\ + The fitness object must have, besides an void ctor, a copy ctor. +*/ +template class EO: public eoObject, public eoPersistent +{ +public: + typedef F Fitness; + + /** Default constructor. + Fitness must have a ctor which takes 0 as a value; we can not use void ctors here + since default types like float have no void initializer. VC++ allows it, but gcc does not + */ + EO(): repFitness(0), invalidFitness(true) {} + + /** Ctor from stream. + Fitness must have defined the lecture from an istream. + */ + EO( istream& _is ) { + _is >> repFitness; + invalidFitness = false; + }; + + /// Copy ctor + EO( const EO& _eo ): repFitness( _eo.repFitness ), invalidFitness( _eo.invalidFitness ) {}; + + /// Virtual dtor + virtual ~EO() {}; + + /// Return fitness value. + Fitness fitness() const + { + if (invalid()) + //throw runtime_error("invalid fitness"); + cout << "invalid fitness" << endl; + return repFitness; + } + + // Set fitness as invalid. + void invalidate() { invalidFitness = true; } + + /** Set fitness. At the same time, validates it. + * @param _fitness New fitness value. + */ + void fitness(const Fitness& _fitness) + { + repFitness = _fitness; + invalidFitness = false; + } + + /** Return true If fitness value is invalid, false otherwise. + * @return true If fitness is invalid. + */ + bool invalid() const { return invalidFitness; } + + /** Returns true if + @return true if the fitness is higher + */ + bool operator<(const EO& _eo2) const { return fitness() < _eo2.fitness();} + + /// Methods inherited from eoObject + //@{ + + /** Return the class id. + * @return the class name as a string + */ + virtual string className() const { return "EO"; }; + + /** + * Read object.\\ + * Calls base class, just in case that one had something to do. The read and print + * methods should be compatible and have the same format. In principle, format is + * "plain": they just print a number + * @param _is a istream. + * @throw runtime_exception If a valid object can't be read. + */ + virtual void readFrom(istream& _is) { + _is >> repFitness; + invalidFitness = false; + } + + /** + * Write object. It's called printOn since it prints the object _on_ a stream. + * @param _os A ostream. + */ + virtual void printOn(ostream& _os) const { + _os << repFitness << endl; + } + + //@} + +private: + Fitness repFitness; // value of fitness for this chromosome + bool invalidFitness; // true if the value of fitness is invalid +}; + +//----------------------------------------------------------------------------- + +#endif EO_H diff --git a/eo/src/Makefile.am b/eo/src/Makefile.am index 314a1275d..d7b9a9287 100644 --- a/eo/src/Makefile.am +++ b/eo/src/Makefile.am @@ -8,5 +8,16 @@ lib_LIBRARIES = libeo.a libeo_a_SOURCES = eoPrintable.cpp eoPersistent.cpp libeoincdir = $(includedir)/eo -libeoinc_HEADERS = eo EO.h eoDup.h eoMultiMonOp.h eoPop.h eoUniform.h eoESChrom.h eoNegExp.h eoProblem.h eoVector.h eoFitness.h eoNormal.h eoRnd.h eoXOver2.h eo1d.h eoID.h eoObject.h eoString.h eoAged.h eoKill.h eoOp.h eoTranspose.h eoBin.h eoPrintable.h eoPersistent.h eoLottery.h eoMutation.h eoPopOps.h eoUniform.h eoInsertion.h eoInclusion.h eoBitOp.h eoBitOpFactory.h eo2d.h eo2dVector.h eoData.h eoProportionalOpSel.h eoOpSelector.h eoBreeder.h eoEvalFunc.h eoEvalFuncPtr.h eoEvaluator.h eoTerm.h eoGenTerm.h eoFitTerm.h eoGeneration.h eoAlgo.h eoEasyEA.h eoNonUniform.h eoRNG.h eoParser.h +libeoinc_HEADERS = EO.h eo eo1d.h eo2d.h eo2dVector.h eoAged.h eoAlgo.h\ + eoAtomBitFlip.h eoAtomCreep.h eoAtomMutation.h eoAtomMutator.h \ + eoAtomRandom.h eoBin.h eoBitOp.h eoBitOpFactory.h eoBreeder.h\ + eoData.h eoDup.h eoESChrom.h eoESFullChrom.h eoESFullMut.h eoEasyEA.h\ + eoEvalFunc.h eoEvalFuncPtr.h eoEvaluator.h eoFitTerm.h eoFitness.h\ + eoGenTerm.h eoGeneration.h eoID.h eoInclusion.h eoInsertion.h\ + eoKill.h eoLottery.h eoMultiMonOp.h eoMutation.h eoNegExp.h\ + eoNonUniform.h eoNormal.h eoObject.h eoOp.h eoOpSelector.h\ + eoParser.h eoPersistent.h eoPop.h eoPopOps.h eoPrintable.h\ + eoProblem.h eoProportionalOpSel.h eoRNG.h eoRnd.h eoString.h\ + eoTerm.h eoTranspose.h eoUniform.h eoVector.h eoXOver2.h + diff --git a/eo/src/eo2dVector.h b/eo/src/eo2dVector.h index edc82f3a1..13e007a9c 100644 --- a/eo/src/eo2dVector.h +++ b/eo/src/eo2dVector.h @@ -1,333 +1,333 @@ -// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- -/* ------------------------------------------------------------------------------ -File............: eo2dVector.h -Author..........: Geneura Team (this file: Victor Rivas, vrivas@ujaen.es) -Date............: 29-Sep-1999, at Fac. of Sciences, Univ. of Granada (Spain) -Description.....: Implementation of a 2-dimensional chromosome usign STL - vectors. - - ================ Modif. 1 ================ - Author........: - Date..........: - Description...: - -QUEDA: Operador de asignación, lectura desde istream, escritura a ostream ------------------------------------------------------------------------------ -*/ -//----------------------------------------------------------------------------- -// eo2dVector.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 _eo2dVector_H -#define _eo2dVector_H - -// STL libraries -#include // For vector -#include -#include -#include - -#include -#include - -/** Adaptor that turns an STL vector of vectror into an EO - with the same gene type as the type with which - the vector of vector has been instantiated. -*/ -template -class eo2dVector: public eo2d, public vector< vector > { -public: - typedef T Type ; - - /** @name Canonical part of the objects: several ctors, copy ctor, \ - * dtor and assignment operator. - */ - //@{ - - /** Ctor. - @param _rows Number of rows. - @param _cols Number of columns. - @param _val Common initial value - */ - eo2dVector( const unsigned _rows = 0, - const unsigned _cols = 0, - T _val = T() ) - : eo2d(), vector< vector >( _rows, vector( _cols, _val ) ){}; - - /** Ctor using a random number generator. - @param _rows Number of rows. - @param _cols Number of columns. - @param _rnd A random "T-type" generator, which returns a random value each time it´s called. - */ - eo2dVector( const unsigned _rows, - const unsigned _cols, - eoRnd& _rnd ); - - /** Ctor from a istream. The T class should accept reading from a istream. It doesn't read fitness, -which is supposed to be dynamic and dependent on environment. - @param _is the input stream; should have all values in a single line, separated by whitespace - */ - //eo2dVector( istream& _is); - - - /// copy ctor - eo2dVector( const eo2dVector & _eo ) - : eo2d( _eo ), vector< vector >( _eo ){ }; - - /// Assignment operator - /* - const eo2dVector& operator =( const eo2dVector & _eo ) { - if ( this != &_eo ){ - eo2d::operator=( _eo ); - vector< >::operator=( _eo ); - } - return *this; - } - */ - /// dtor - virtual ~eo2dVector() {}; - - //@} - /** Reads and returns a copy of the gene in position _r,_c.\ - This implies that T must have a copy ctor . - @param _r Index for rows. Must be an unsigned less than #numOfRows()# - @param _c Index for columns. Must be an unsigned less than #numOfCols()# +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- +/* +----------------------------------------------------------------------------- +File............: eo2dVector.h +Author..........: Geneura Team (this file: Victor Rivas, vrivas@ujaen.es) +Date............: 29-Sep-1999, at Fac. of Sciences, Univ. of Granada (Spain) +Description.....: Implementation of a 2-dimensional chromosome usign STL + vectors. + + ================ Modif. 1 ================ + Author........: + Date..........: + Description...: + +QUEDA: Operador de asignación, lectura desde istream, escritura a ostream +----------------------------------------------------------------------------- +*/ +//----------------------------------------------------------------------------- +// eo2dVector.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 _eo2dVector_H +#define _eo2dVector_H + +// STL libraries +#include // For vector +#include +#include +#include + +#include +#include + +/** Adaptor that turns an STL vector of vectror into an EO + with the same gene type as the type with which + the vector of vector has been instantiated. +*/ +template +class eo2dVector: public eo2d, public vector< vector > { +public: + typedef T Type ; + + /** @name Canonical part of the objects: several ctors, copy ctor, \ + * dtor and assignment operator. + */ + //@{ + + /** Ctor. + @param _rows Number of rows. + @param _cols Number of columns. + @param _val Common initial value + */ + eo2dVector( const unsigned _rows = 0, + const unsigned _cols = 0, + T _val = T() ) + : eo2d(), vector< vector >( _rows, vector( _cols, _val ) ){}; + + /** Ctor using a random number generator. + @param _rows Number of rows. + @param _cols Number of columns. + @param _rnd A random "T-type" generator, which returns a random value each time it´s called. + */ + eo2dVector( const unsigned _rows, + const unsigned _cols, + eoRnd& _rnd ); + + /** Ctor from a istream. The T class should accept reading from a istream. It doesn't read fitness, +which is supposed to be dynamic and dependent on environment. + @param _is the input stream; should have all values in a single line, separated by whitespace + */ + //eo2dVector( istream& _is); + + + /// copy ctor + eo2dVector( const eo2dVector & _eo ) + : eo2d( _eo ), vector< vector >( _eo ){ }; + + /// Assignment operator + /* + const eo2dVector& operator =( const eo2dVector & _eo ) { + if ( this != &_eo ){ + eo2d::operator=( _eo ); + vector< >::operator=( _eo ); + } + return *this; + } + */ + /// dtor + virtual ~eo2dVector() {}; + + //@} + /** Reads and returns a copy of the gene in position _r,_c.\ + This implies that T must have a copy ctor . + @param _r Index for rows. Must be an unsigned less than #numOfRows()# + @param _c Index for columns. Must be an unsigned less than #numOfCols()# @return what's inside the gene, with the correct type - @exception out_of_range if _r >=numOfRows() - @exception out_of_range if _c >=numOfCols() - */ - virtual T getGene( const unsigned _r, - const unsigned _c ) const { - if ( _r >= numOfRows() ) { - ostrstream msg; - msg << "ERROR in eo2dVector::getGene: row out of range. " - << "It should be <" << numOfRows() << '\0' << endl; - throw out_of_range( msg.str() ); - } - if ( _c >= numOfCols() ) { - ostrstream msg; - msg << "ERROR in eo2dVector::getGene: column out of range. " - << "It should be <" << numOfCols() << '\0' << endl; - throw out_of_range( msg.str() ); - } - return (*this)[_r][_c]; - }; - /** Overwrites the gene placed in position _r,_c with a - * new value. This means that the assignment operator - * for T must be defined . - @param _r Index for rows. Must be an unsigned less than #numOfRows()# - @param _c Index for columns. Must be an unsigned less than #numOfCols()# + @exception out_of_range if _r >=numOfRows() + @exception out_of_range if _c >=numOfCols() + */ + virtual T getGene( const unsigned _r, + const unsigned _c ) const { + if ( _r >= numOfRows() ) { + ostrstream msg; + msg << "ERROR in eo2dVector::getGene: row out of range. " + << "It should be <" << numOfRows() << '\0' << endl; + throw out_of_range( msg.str() ); + } + if ( _c >= numOfCols() ) { + ostrstream msg; + msg << "ERROR in eo2dVector::getGene: column out of range. " + << "It should be <" << numOfCols() << '\0' << endl; + throw out_of_range( msg.str() ); + } + return (*this)[_r][_c]; + }; + /** Overwrites the gene placed in position _r,_c with a + * new value. This means that the assignment operator + * for T must be defined . + @param _r Index for rows. Must be an unsigned less than #numOfRows()# + @param _c Index for columns. Must be an unsigned less than #numOfCols()# @return what's inside the gene, with the correct type - @exception out_of_range if _r >=numOfRows() - @exception out_of_range if _c >=numOfCols() - */ - virtual void setGene( const unsigned _r, - const unsigned _c, - const T& _value ) { - if ( _r >= numOfRows() ) { - ostrstream msg; - msg << "ERROR in eo2dVector::setGene: row out of range. " - << "It should be <" << numOfRows() << '\0' << endl; - throw out_of_range( msg.str() ); - } - if ( _c >= numOfCols() ) { - ostrstream msg; - msg << "ERROR in eo2dVector::setGene: column out of range. " - << "It should be <" << numOfCols() << '\0' << endl; - throw out_of_range( msg.str() ); - } - (*this)[_r][_c]=_value; - }; - - - - /** Inserts a row, moving the rest to the bottom. - * If _r = numOfRows(), it insert it at the end. - * Obviously, changes number of rows. - @param _r Position where the new row will be inserted. - @param _val Vector containing the new values to be inserted. - @exception invalid_argument If _val has not numOfCols() components. - @exception out_of_range If _r is greater than numOfRows() - */ - virtual void insertRow( const unsigned _r, - const vector& _val ) { - // Test errors. - if ( _r > numOfRows() ) { - ostrstream msg; - msg << "ERROR in eo2dVector::insertRow: row out of range. " - << "It should be <=" << numOfRows() << '\0' << endl; - throw out_of_range( msg.str() ); - } - if ( _val.size() != numOfCols() ) { - ostrstream msg; - msg << "ERROR in eo2dVector::insertRow: " - << "Incorrect number of values to be added. " - << "It should be ==" << numOfCols() << '\0' << endl; - throw invalid_argument( msg.str() ); - } - - // Insert the row. - vector< vector >::iterator ite = begin()+_r; - insert( ite, _val ); - }; - - /** Eliminates the row at position _r; all the other genes will - be shifted up. - @param _r Number of he row to be deleted. - @exception out_of_range if _r >=numOfRows() - */ - virtual void deleteRow( const unsigned _r ) { - // Test error. - if ( _r >= numOfRows() ) { - ostrstream msg; - msg << "ERROR in eo2dVector::deleteRow: " - << "Row out of range. " - << "It should be <" << numOfRows() << '\0' << endl; - throw out_of_range( msg.str() ); - } - // Delete row. - vector< vector >::iterator ite = this->begin()+_r; - this->erase( ite ); - }; - - /** Inserts a column, moving the rest to the right. - * If _c = numOfCols(), it insert it at the end. - * Obviously, changes number of cols. - @param _r Position where the new column will be inserted. - @param _val Vector containing the new values to be inserted. - @exception invalid_argument if _val has not numOfRows() components. - */ - virtual void insertCol( const unsigned _c, - const vector& _val ) { - // Test errors. - if ( _c > numOfCols() ) { - ostrstream msg; - msg << "ERROR in eo2dVector::insertCol: " - << "Column out of range. " - << "It should be >=" << numOfCols() << '\0' << endl; - throw out_of_range( msg.str() ); - } - if ( _val.size() != numOfRows() ) { - ostrstream msg; - msg << "ERROR in eo2dVector::insertCol: " - << "Incorrect number of values to be added. " - << "It should be ==" << numOfRows() << '\0' << endl; - throw invalid_argument( msg.str() ); - } - - // Insert column. - for( unsigned r=0; r >::iterator it1 = begin()+r; - vector::iterator it2 = (*it1).begin()+_c; - (*it1).insert( it2, _val[r] ); - }; - } - - /** Eliminates the column at position _c; all the other columns will - be shifted left. - @param _c Number of he column to be deleted. - @exception out_of_range if _c >=numOfCols() - */ - virtual void deleteCol( const unsigned _c ) { - // Test error. - if ( _c >= numOfCols() ) { - ostrstream msg; - msg << "ERROR in eo2dVector::deleteCol: " - << "Column out of range. " - << "It should be <" << numOfCols() << '\0' << endl; - throw out_of_range( msg.str() ); - } - // Delete columns. - for( unsigned r=0; r >::iterator it1 = begin()+r; - vector::iterator it2 = (*it1).begin()+_c; - (*it1).erase( it2 ); - } - }; - - /// Returns the number of rows in the eo2d - virtual unsigned numOfRows() const { - return size(); - }; - - /// Returns the number of columns in the eo2d - virtual unsigned numOfCols() const { - return begin()->size(); - }; - - - /** @name Methods from eoObject - readFrom and printOn are directly inherited from eo1d - */ - //@{ - /** Inherited from eoObject - @see eoObject - */ - string className() const {return "eo2dVector";}; - //@} - -}; - - -//____________________________ Some method implementation ____________________ - -// Ctors_______________________________________________________________________ -//_____________________________________________________________________________ -template -eo2dVector::eo2dVector( const unsigned _rows, - const unsigned _cols, - eoRnd& _rnd ) - : eo2d(), vector< vector >( _rows, vector( _cols, T() ) ){ - for ( vector< vector >::iterator i = begin(); i != end(); ++i ) { - for( vector::iterator j=(*i).begin(); j!= (*i).end(); ++j ) { - *j = _rnd(); - } - } -}; - -//_____________________________________________________________________________ -/*template -eoVector::eoVector( istream& _is) - : eo1d(), vector( ){ - while (_is ) { - T tmp; - _is >> tmp; - push_back( tmp ); - } - -}; -*/ - -//_____________________________________________________________________________ -template -ostream& operator<<( ostream& _os, const eo2dVector& _eo) { - for( unsigned i=0; i<_eo.numOfRows(); ++i ) { - for( unsigned j=0; j<_eo.numOfCols(); ++j ) { - _os << _eo.getGene( i,j ) << " "; - } - _os << endl; - } - return _os; -}; - -#endif + @exception out_of_range if _r >=numOfRows() + @exception out_of_range if _c >=numOfCols() + */ + virtual void setGene( const unsigned _r, + const unsigned _c, + const T& _value ) { + if ( _r >= numOfRows() ) { + ostrstream msg; + msg << "ERROR in eo2dVector::setGene: row out of range. " + << "It should be <" << numOfRows() << '\0' << endl; + throw out_of_range( msg.str() ); + } + if ( _c >= numOfCols() ) { + ostrstream msg; + msg << "ERROR in eo2dVector::setGene: column out of range. " + << "It should be <" << numOfCols() << '\0' << endl; + throw out_of_range( msg.str() ); + } + (*this)[_r][_c]=_value; + }; + + + + /** Inserts a row, moving the rest to the bottom. + * If _r = numOfRows(), it insert it at the end. + * Obviously, changes number of rows. + @param _r Position where the new row will be inserted. + @param _val Vector containing the new values to be inserted. + @exception invalid_argument If _val has not numOfCols() components. + @exception out_of_range If _r is greater than numOfRows() + */ + virtual void insertRow( const unsigned _r, + const vector& _val ) { + // Test errors. + if ( _r > numOfRows() ) { + ostrstream msg; + msg << "ERROR in eo2dVector::insertRow: row out of range. " + << "It should be <=" << numOfRows() << '\0' << endl; + throw out_of_range( msg.str() ); + } + if ( _val.size() != numOfCols() ) { + ostrstream msg; + msg << "ERROR in eo2dVector::insertRow: " + << "Incorrect number of values to be added. " + << "It should be ==" << numOfCols() << '\0' << endl; + throw invalid_argument( msg.str() ); + } + + // Insert the row. + vector< vector >::iterator ite = begin()+_r; + insert( ite, _val ); + }; + + /** Eliminates the row at position _r; all the other genes will + be shifted up. + @param _r Number of he row to be deleted. + @exception out_of_range if _r >=numOfRows() + */ + virtual void deleteRow( const unsigned _r ) { + // Test error. + if ( _r >= numOfRows() ) { + ostrstream msg; + msg << "ERROR in eo2dVector::deleteRow: " + << "Row out of range. " + << "It should be <" << numOfRows() << '\0' << endl; + throw out_of_range( msg.str() ); + } + // Delete row. + vector< vector >::iterator ite = this->begin()+_r; + this->erase( ite ); + }; + + /** Inserts a column, moving the rest to the right. + * If _c = numOfCols(), it insert it at the end. + * Obviously, changes number of cols. + @param _r Position where the new column will be inserted. + @param _val Vector containing the new values to be inserted. + @exception invalid_argument if _val has not numOfRows() components. + */ + virtual void insertCol( const unsigned _c, + const vector& _val ) { + // Test errors. + if ( _c > numOfCols() ) { + ostrstream msg; + msg << "ERROR in eo2dVector::insertCol: " + << "Column out of range. " + << "It should be >=" << numOfCols() << '\0' << endl; + throw out_of_range( msg.str() ); + } + if ( _val.size() != numOfRows() ) { + ostrstream msg; + msg << "ERROR in eo2dVector::insertCol: " + << "Incorrect number of values to be added. " + << "It should be ==" << numOfRows() << '\0' << endl; + throw invalid_argument( msg.str() ); + } + + // Insert column. + for( unsigned r=0; r >::iterator it1 = begin()+r; + vector::iterator it2 = (*it1).begin()+_c; + (*it1).insert( it2, _val[r] ); + }; + } + + /** Eliminates the column at position _c; all the other columns will + be shifted left. + @param _c Number of he column to be deleted. + @exception out_of_range if _c >=numOfCols() + */ + virtual void deleteCol( const unsigned _c ) { + // Test error. + if ( _c >= numOfCols() ) { + ostrstream msg; + msg << "ERROR in eo2dVector::deleteCol: " + << "Column out of range. " + << "It should be <" << numOfCols() << '\0' << endl; + throw out_of_range( msg.str() ); + } + // Delete columns. + for( unsigned r=0; r >::iterator it1 = begin()+r; + vector::iterator it2 = (*it1).begin()+_c; + (*it1).erase( it2 ); + } + }; + + /// Returns the number of rows in the eo2d + virtual unsigned numOfRows() const { + return size(); + }; + + /// Returns the number of columns in the eo2d + virtual unsigned numOfCols() const { + return begin()->size(); + }; + + + /** @name Methods from eoObject + readFrom and printOn are directly inherited from eo1d + */ + //@{ + /** Inherited from eoObject + @see eoObject + */ + string className() const {return "eo2dVector";}; + //@} + +}; + + +//____________________________ Some method implementation ____________________ + +// Ctors_______________________________________________________________________ +//_____________________________________________________________________________ +template +eo2dVector::eo2dVector( const unsigned _rows, + const unsigned _cols, + eoRnd& _rnd ) + : eo2d(), vector< vector >( _rows, vector( _cols, T() ) ){ + for ( vector< vector >::iterator i = begin(); i != end(); ++i ) { + for( vector::iterator j=(*i).begin(); j!= (*i).end(); ++j ) { + *j = _rnd(); + } + } +}; + +//_____________________________________________________________________________ +/*template +eoVector::eoVector( istream& _is) + : eo1d(), vector( ){ + while (_is ) { + T tmp; + _is >> tmp; + push_back( tmp ); + } + +}; +*/ + +//_____________________________________________________________________________ +template +ostream& operator<<( ostream& _os, const eo2dVector& _eo) { + for( unsigned i=0; i<_eo.numOfRows(); ++i ) { + for( unsigned j=0; j<_eo.numOfCols(); ++j ) { + _os << _eo.getGene( i,j ) << " "; + } + _os << endl; + } + return _os; +}; + +#endif diff --git a/eo/src/eoAged.h b/eo/src/eoAged.h index 7c626e019..2e37c1a1f 100644 --- a/eo/src/eoAged.h +++ b/eo/src/eoAged.h @@ -1,41 +1,41 @@ -// eoAged.h +// 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 // istream, ostream -#include // para string +// (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 // istream, ostream +#include // para string using namespace std; - -//----------------------------------------------------------------------------- -// eoAge -//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// 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 @@ -43,18 +43,18 @@ and a copy ctor. The Object must be an eoObject, thus, it must have its methods: printOn, readFrom. @see eoObject */ -template -class eoAged: public Object -{ - public: +template +class eoAged: public Object +{ + public: /// Main ctor from an already built Object. eoAged( const Object& _o): Object( _o ), age(0) {}; - - /// Copy constructor. + + /// Copy constructor. eoAged( const eoAged& _a): Object( _a ), age( _a.age ) {}; /// Virtual dtor. They are needed in virtual class hierarchies - virtual ~eoAged() {}; + virtual ~eoAged() {}; ///returns the age of the object @@ -66,32 +66,32 @@ class eoAged: public Object /** @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. - */ +//@{ + /** 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. - */ + + + /** + * 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: @@ -102,7 +102,7 @@ class eoAged: public Object it´s turned into an Aged object*/ eoAged(): Object(), age(0) {}; - unsigned long age; + unsigned long age; }; - -#endif EOAGE_H + +#endif EOAGE_H diff --git a/eo/src/eoAtomBitFlip.h b/eo/src/eoAtomBitFlip.h new file mode 100644 index 000000000..b96d33a50 --- /dev/null +++ b/eo/src/eoAtomBitFlip.h @@ -0,0 +1,57 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoAtomCreep.h +// Increments or decrements by one a single element +// (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 _EOATOMCREEP_H +#define _EOATOMCREEP_H + +/** Flips a single bit +*/ +template +class eoAtomBitFlip: public eoAtomMutator { +public: + + /// + eoAtomBitFlip() {}; + + /// + virtual ~eoAtomBitFlip() {}; + + /// + virtual void operator()( T& _val ) const { + _val = !val; + } + + /** @name Methods from eoObject + */ + //@{ + /** Inherited from eoObject + @see eoObject + */ + string className() const {return "eoAtomBitFlip";}; + //@} + +}; + + +#endif diff --git a/eo/src/eoAtomCreep.h b/eo/src/eoAtomCreep.h new file mode 100644 index 000000000..2fc7d676c --- /dev/null +++ b/eo/src/eoAtomCreep.h @@ -0,0 +1,65 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoAtomCreep.h +// Increments or decrements by one a single element +// (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 _EOATOMCREEP_H +#define _EOATOMCREEP_H + +#include +#include + +/** With uniform probability, decrements or increments by one the value. + The value type must admit post increment and decrement. +*/ +template +class eoAtomCreep: public eoAtomMutator { +public: + + /// + eoAtomCreep() {}; + + /// + virtual ~eoAtomCreep() {}; + + /// + virtual void operator()( T& _val ) const { + if ( rng.flip( 0.5 ) ) { + _val++; + } else { + _val--; + } + } + + /** @name Methods from eoObject + */ + //@{ + /** Inherited from eoObject + @see eoObject + */ + virtual string className() const {return "eoAtomCreep";}; + //@} + +}; + + +#endif diff --git a/eo/src/eoAtomMutation.h b/eo/src/eoAtomMutation.h new file mode 100644 index 000000000..c4ff91afb --- /dev/null +++ b/eo/src/eoAtomMutation.h @@ -0,0 +1,95 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoAtomMutation.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 _EOATOMMUTATION_H +#define _EOATOMMUTATION_H + +// STL includes +#include + +// EO includes +#include +#include +#include +#include + +/** Atomic mutation of an EO. Acts on containers, and applies a mutation + operator to each element of the container with some probability. EOT must + be a container of any tipe +*/ +template +class eoAtomMutation: public eoMonOp { +public: + +#ifdef _MSC_VER + typedef EOT::Type Type; +#else + typedef typename EOT::Type Type; +#endif + + /// + eoAtomMutation(const eoAtomMutator& _atomMut, const double _rate=0.0) + : eoMonOp< EOT >(), rate(_rate), atomMutator( _atomMut ) {}; + + /// + virtual ~eoAtomMutation() {}; + + /// + virtual void operator()( EOT& _eo ) const { + typename EOT::iterator i; + for ( i = _eo.begin(); i != _eo.end(); i ++ ) + if ( rng.flip( rate ) ) { + atomMutator( *i ); + } + } + + /** To print me on a stream. + @param os The ostream. + */ + void printOn(ostream& os) const { + os << rate ; + } + + /** To read me from a stream. + @param is The istream */ + void readFrom(istream& is) { + is >> rate ; + } + + /** @name Methods from eoObject + */ + //@{ + /** Inherited from eoObject + @see eoObject + */ + string className() const {return "eoMutation";}; + //@} + +private: + + double rate; + const eoAtomMutator& atomMutator; +}; + + +#endif diff --git a/eo/src/eoAtomMutator.h b/eo/src/eoAtomMutator.h new file mode 100644 index 000000000..97510c583 --- /dev/null +++ b/eo/src/eoAtomMutator.h @@ -0,0 +1,61 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoAtomMutator.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 _EOATOMMUTATOR_H +#define _EOATOMMUTATOR_H + +/** Abstract base class for functors that modify a single element in an EO + that is composed of several atomic components. An atom would, for instance, flip + a bit, or change a real number, or things like that. +*/ +template +class eoAtomMutator: public eoPrintable { +public: + + /// + eoAtomMutator() {}; + + /// + virtual ~eoAtomMutator() {}; + + /// + virtual void operator()( T& _val ) const = 0; + + /** @name Methods from eoObject + */ + //@{ + /** Inherited from eoObject + @see eoObject + */ + /// + virtual string className() const {return "eoAtomMutator";}; + + /// + void printOn(ostream& _os) const { _os << className() << endl; }; + + //@} + +}; + + +#endif diff --git a/eo/src/eoAtomRandom.h b/eo/src/eoAtomRandom.h new file mode 100644 index 000000000..e7faaab33 --- /dev/null +++ b/eo/src/eoAtomRandom.h @@ -0,0 +1,63 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoAtomRandom.h +// Increments or decrements by one a single element +// (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 _EOATOMCREEP_H +#define _EOATOMCREEP_H + +#include + +/** Modifies using a random number generator, that is entered in the ctor. + The RNG must return positive or negative numbers, whatever. +*/ +template +class eoAtomRandom: public eoAtomMutator { +public: + + /// + eoAtomRandom( eoRandom& _rng): rng( _rng ) {}; + + /// + virtual ~eoAtomRandom() {}; + + /// + virtual void operator()( T& _val ) const { + _val += rng(); + } + + /** @name Methods from eoObject + */ + //@{ + /** Inherited from eoObject + @see eoObject + */ + string className() const {return "eoAtomRandom";}; + //@} + +private: + eoRandom rng; + +}; + + +#endif diff --git a/eo/src/eoBin.h b/eo/src/eoBin.h index b78cff475..b56054ed7 100644 --- a/eo/src/eoBin.h +++ b/eo/src/eoBin.h @@ -1,78 +1,78 @@ -//----------------------------------------------------------------------------- -// eoBin.h -//----------------------------------------------------------------------------- - -#ifndef eoBin_h -#define eoBin_h - -//----------------------------------------------------------------------------- - -#include // ostream, istream -#include // bind2nd -#include // string -#include // EO - -/***************************************************************************** - * eoBin: implementation of binary chromosome. * - * based on STL's bit_vector (vector). * - *****************************************************************************/ - -template class eoBin: public eoVector -{ - public: - - /** - * (Default) Constructor. - * @param size Size of the binary string. - */ - eoBin(unsigned size = 0, bool value = false): - eoVector(size, value) {} - - /** - * Constructor. - * @param size Size of the binary string. - */ - eoBin(unsigned size, const eoRnd& rnd): eoVector(size) - { - generate(begin(), end(), rnd); - } - - /** Constructor from istream. - @param is The istream to read from.*/ - eoBin(istream& _is):eoVector(_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(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(), '1')); - } - } -}; - -//----------------------------------------------------------------------------- - -#endif eoBin_h +//----------------------------------------------------------------------------- +// eoBin.h +//----------------------------------------------------------------------------- + +#ifndef eoBin_h +#define eoBin_h + +//----------------------------------------------------------------------------- + +#include // ostream, istream +#include // bind2nd +#include // string +#include // EO + +/***************************************************************************** + * eoBin: implementation of binary chromosome. * + * based on STL's bit_vector (vector). * + *****************************************************************************/ + +template class eoBin: public eoVector +{ + public: + + /** + * (Default) Constructor. + * @param size Size of the binary string. + */ + eoBin(unsigned size = 0, bool value = false): + eoVector(size, value) {} + + /** + * Constructor. + * @param size Size of the binary string. + */ + eoBin(unsigned size, const eoRnd& rnd): eoVector(size) + { + generate(begin(), end(), rnd); + } + + /** Constructor from istream. + @param is The istream to read from.*/ + eoBin(istream& _is):eoVector(_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(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(), '1')); + } + } +}; + +//----------------------------------------------------------------------------- + +#endif eoBin_h diff --git a/eo/src/eoBitOpFactory.h b/eo/src/eoBitOpFactory.h index b47b6459a..b44a55067 100644 --- a/eo/src/eoBitOpFactory.h +++ b/eo/src/eoBitOpFactory.h @@ -1,27 +1,27 @@ -// eoBitOpFactory.h +// 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 - */ -//----------------------------------------------------------------------------- +/* + 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 @@ -52,12 +52,12 @@ public: /** 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 + 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 + 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* make(istream& _is) { eoOp * opPtr = NULL; @@ -112,7 +112,7 @@ public: return opPtr; }; - + }; diff --git a/eo/src/eoBreeder.h b/eo/src/eoBreeder.h index 7d87c3d6a..cd21f0ed3 100644 --- a/eo/src/eoBreeder.h +++ b/eo/src/eoBreeder.h @@ -1,81 +1,82 @@ -//----------------------------------------------------------------------------- -// eoBreeder.h -//----------------------------------------------------------------------------- - -#ifndef eoBreeder_h -#define eoBreeder_h - -//----------------------------------------------------------------------------- - -#include // vector -#include // eoUniform -#include // eoOp, eoMonOp, eoBinOp -#include // eoPop -#include // eoTransform -#include // eoOpSelector - -using namespace std; - -/***************************************************************************** - * eoBreeder: transforms a population using genetic operators. * - * For every operator there is a rated to be applyed. * - *****************************************************************************/ - -template class eoBreeder: public eoTransform -{ - public: - /// Default constructor. - eoBreeder( eoOpSelector& _opSel): opSel( _opSel ) {} - - /// Destructor. - virtual ~eoBreeder() {} - - /** - * Transforms a population. - * @param pop The population to be transformed. - */ - void operator()(eoPop& pop) - { - for (unsigned i = 0; i < pop.size(); i++) { - eoOp* op = opSel.Op(); - switch (op->readArity()) { - case unary: - { - eoMonOp* monop = static_cast* >(op); - (*monop)( pop[i] ); - break; - } - case binary: - { - eoBinOp* binop = static_cast* >(op); - eoUniform u(0, pop.size() ); - (*binop)(pop[i], pop[ u() ] ); - break; - } - case Nary: - { - eoNaryOp* Nop = static_cast* >(op); - eoUniform u(0, pop.size() ); - eoPop tmpVec; - tmpVec.push_back( pop[i] ); - for ( unsigned i = 0; i < u(); i ++ ) { - tmpVec.push_back( pop[ u() ] ); - } - (*Nop)( tmpVec ); - break; - } - } - } - }; - - /// The class name. - string classname() const { return "eoBreeder"; } - - private: - eoOpSelector& opSel; - -}; - -//----------------------------------------------------------------------------- - -#endif eoBreeder_h +//----------------------------------------------------------------------------- +// eoBreeder.h +//----------------------------------------------------------------------------- + +#ifndef eoBreeder_h +#define eoBreeder_h + +//----------------------------------------------------------------------------- + +#include // vector +#include // eoUniform +#include // eoOp, eoMonOp, eoBinOp +#include // eoPop +#include // eoTransform +#include // eoOpSelector + +using namespace std; + +/***************************************************************************** + * eoBreeder: transforms a population using genetic operators. * + * For every operator there is a rated to be applyed. * + *****************************************************************************/ + +template class eoBreeder: public eoTransform +{ + public: + /// Default constructor. + eoBreeder( eoOpSelector& _opSel): opSel( _opSel ) {} + + /// Destructor. + virtual ~eoBreeder() {} + + /** + * Transforms a population. + * @param pop The population to be transformed. + */ + void operator()(eoPop& pop) + { + for (unsigned i = 0; i < pop.size(); i++) { + eoOp* op = opSel.Op(); + switch (op->readArity()) { + case unary: + { + eoMonOp* monop = static_cast* >(op); + (*monop)( pop[i] ); + break; + } + case binary: + { + eoBinOp* binop = static_cast* >(op); + eoUniform u(0, pop.size() ); + (*binop)(pop[i], pop[ u() ] ); + break; + } + case Nary: + { + eoNaryOp* Nop = static_cast* >(op); + eoUniform u(0, pop.size() ); + eoPop inVec, outVec; + inVec.push_back( pop[i] ); + unsigned numberOfOperands = u(); + for ( unsigned i = 0; i < numberOfOperands; i ++ ) { + inVec.push_back( pop[ u() ] ); + } + (*Nop)( inVec, outVec ); + break; + } + } + } + }; + + /// The class name. + string classname() const { return "eoBreeder"; } + + private: + eoOpSelector& opSel; + +}; + +//----------------------------------------------------------------------------- + +#endif eoBreeder_h diff --git a/eo/src/eoData.h b/eo/src/eoData.h index fcbf013e4..a90445d04 100644 --- a/eo/src/eoData.h +++ b/eo/src/eoData.h @@ -1,18 +1,18 @@ -//----------------------------------------------------------------------------- -// eoData.h -//----------------------------------------------------------------------------- - -#ifndef EODATA_H -#define EODATA_H - -//----------------------------------------------------------------------------- - -#include // vector -#include // set -#include // string +//----------------------------------------------------------------------------- +// eoData.h +//----------------------------------------------------------------------------- + +#ifndef EODATA_H +#define EODATA_H + +//----------------------------------------------------------------------------- + +#include // vector +#include // set +#include // string using namespace std; - + #ifdef _MSC_VER #include // MAXDOUBLE @@ -20,22 +20,22 @@ using namespace std; #define MINFLOAT numeric_limits::min() #define MAXDOUBLE numeric_limits::max() #define MAXINT numeric_limits::max() -#else - #include +#else + #include #include - #include + #include #ifndef MAXFLOAT #define MAXFLOAT (float)1e127 #define MAXDOUBLE (double)1.79769313486231570e+308 #define MAXINT 2147483647 #endif #endif - -#ifndef _MSC_VER -#include -#define _isnan isnan -#endif - -//----------------------------------------------------------------------------- - -#endif EODATA_H + +#ifndef _MSC_VER +#include +#define _isnan isnan +#endif + +//----------------------------------------------------------------------------- + +#endif EODATA_H diff --git a/eo/src/eoDup.h b/eo/src/eoDup.h index ade6c248f..7a13bd75d 100644 --- a/eo/src/eoDup.h +++ b/eo/src/eoDup.h @@ -1,26 +1,26 @@ -// eoDup.h +// eoDup.h // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- //----------------------------------------------------------------------------- // eoKill.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 - */ +/* + 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 _EODUP_h diff --git a/eo/src/eoESChrom.h b/eo/src/eoESChrom.h index b5a66a4e1..d8d87564d 100644 --- a/eo/src/eoESChrom.h +++ b/eo/src/eoESChrom.h @@ -3,23 +3,23 @@ //----------------------------------------------------------------------------- // 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 - */ +/* + 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 + */ //----------------------------------------------------------------------------- diff --git a/eo/src/eoESFullChrom.h b/eo/src/eoESFullChrom.h new file mode 100644 index 000000000..4d7d647a8 --- /dev/null +++ b/eo/src/eoESFullChrom.h @@ -0,0 +1,270 @@ +// -*- 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 // For vector<> +#include +#include +#include // for ostream + +// EO includes +#include +#include +/**@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 +class eoESFullChrom : public eoVector { + 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(_num_genes), + // ObjVar( _num_genes ), now an eoVector + StdDev( _num_sigma ), + CorCff( _num_correl ), + verbose( _verbose ), + ObjMin( _ObjMin ), + ObjMax(_ObjMax ), + StdDevInit( _StdDevInit ) {} + + /// copy constructor + eoESFullChrom( const eoESFullChrom& _eo ): + eoVector ( _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 + char sloc[20]; + sprintf(sloc, "%d", num_genes); + parser.setParamValue("--NbSigma", sloc); + } + // 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::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( _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( _s, " ") ); + if (CorCff.size()) { + _s << "\n\t"; + copy( CorCff.begin(), CorCff.end(), ostream_iterator( _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 ObjVar; /* object variable vector */ +// or shoudl the class be subclass of EOVector ??? + + vector StdDev; /* standard deviation vector */ + vector 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 + diff --git a/eo/src/eoESFullMut.h b/eo/src/eoESFullMut.h new file mode 100644 index 000000000..c8bdcb281 --- /dev/null +++ b/eo/src/eoESFullMut.h @@ -0,0 +1,243 @@ +// -*- 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 +#include +#include // for exp + +#include +#include + +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 eoESMutate: public eoMonOp< eoESFullChrom > { +public: + /// + eoESMutate( double _TauLcl, double _TauGlb, double _TauBeta ) + : eoMonOp< eoESFullChrom >( ), TauLcl(_TauLcl), TauGlb(_TauGlb), + TauBeta(_TauBeta) {}; + + /* The parser constructor + */ + eoESMutate(Parser & parser, unsigned _stdDevLength, unsigned _size, bool _correlated ): + eoMonOp< eoESFullChrom >( ) { + 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 & _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 & _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 & _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 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 + diff --git a/eo/src/eoEasyEA.h b/eo/src/eoEasyEA.h index 5c2f7c029..6c6366494 100644 --- a/eo/src/eoEasyEA.h +++ b/eo/src/eoEasyEA.h @@ -1,84 +1,84 @@ -// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - -//----------------------------------------------------------------------------- -// eoEasyEA.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 _eoEasyEA_h -#define _eoEasyEA_h - -//----------------------------------------------------------------------------- - -#include // eoPop -#include - -/** EOEasyEA: - An easy-to-use evolutionary algorithm; you can use any chromosome, - and any selection transformation, merging and evaluation - algorithms; you can even change in runtime parameters of those - sub-algorithms -*/ - -template class eoEasyEA: public eoAlgo -{ - public: - /// Constructor. - eoEasyEA(eoSelect& _select, - eoTransform& _transform, - eoMerge& _replace, - eoEvalFunc& _evaluator, - eoTerm& _terminator) - :step(_select, _transform, _replace, _evaluator), - terminator( _terminator){}; - - /// Constructor from an already created generation - eoEasyEA(eoGeneration& _gen, - eoTerm& _terminator): - step(_gen), - terminator( _terminator){}; - - /// Apply one generation of evolution to the population. - virtual void operator()(eoPop& pop) { - do { - try - { - step(pop); - } - catch (exception& e) - { - string s = e.what(); - s.append( " in eoEasyEA "); - throw runtime_error( s ); - } - } while ( terminator( pop ) ); - } - - /// Class name. - string className() const { return "eoEasyEA"; } - - private: - eoGeneration step; - eoTerm& terminator; -}; - -//----------------------------------------------------------------------------- - -#endif eoEasyEA_h +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoEasyEA.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 _eoEasyEA_h +#define _eoEasyEA_h + +//----------------------------------------------------------------------------- + +#include // eoPop +#include + +/** EOEasyEA: + An easy-to-use evolutionary algorithm; you can use any chromosome, + and any selection transformation, merging and evaluation + algorithms; you can even change in runtime parameters of those + sub-algorithms +*/ + +template class eoEasyEA: public eoAlgo +{ + public: + /// Constructor. + eoEasyEA(eoSelect& _select, + eoTransform& _transform, + eoMerge& _replace, + eoEvalFunc& _evaluator, + eoTerm& _terminator) + :step(_select, _transform, _replace, _evaluator), + terminator( _terminator){}; + + /// Constructor from an already created generation + eoEasyEA(eoGeneration& _gen, + eoTerm& _terminator): + step(_gen), + terminator( _terminator){}; + + /// Apply one generation of evolution to the population. + virtual void operator()(eoPop& pop) { + do { + try + { + step(pop); + } + catch (exception& e) + { + string s = e.what(); + s.append( " in eoEasyEA "); + throw runtime_error( s ); + } + } while ( terminator( pop ) ); + } + + /// Class name. + string className() const { return "eoEasyEA"; } + + private: + eoGeneration step; + eoTerm& terminator; +}; + +//----------------------------------------------------------------------------- + +#endif eoEasyEA_h diff --git a/eo/src/eoEvalFuncPtr.h b/eo/src/eoEvalFuncPtr.h index cacd5c478..882f4b6da 100644 --- a/eo/src/eoEvalFuncPtr.h +++ b/eo/src/eoEvalFuncPtr.h @@ -1,50 +1,50 @@ -// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - -//----------------------------------------------------------------------------- -// eoOp.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 EOEVALFUNCPTR_H -#define EOEVALFUNCPTR_H - -#include - -/** EOEvalFuncPtr: This class - * takes an existing function pointer and converts it into a evaluation - * function class. That way, old style C or C++ functions can be adapted to EO - * function classes. - */ -template< class EOT > -struct eoEvalFuncPtr: public eoEvalFunc { - - eoEvalFuncPtr( void (* _eval)( EOT& ) ) - : eoEvalFunc(), evalFunc( _eval ) {}; - - /// Effectively applies the evaluation function to an EO - virtual void operator() ( EOT & _eo ) const { - (*evalFunc)( _eo ); - }; - - private: - void (* evalFunc )( EOT& ); -}; - -#endif +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoOp.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 EOEVALFUNCPTR_H +#define EOEVALFUNCPTR_H + +#include + +/** EOEvalFuncPtr: This class + * takes an existing function pointer and converts it into a evaluation + * function class. That way, old style C or C++ functions can be adapted to EO + * function classes. + */ +template< class EOT > +struct eoEvalFuncPtr: public eoEvalFunc { + + eoEvalFuncPtr( void (* _eval)( EOT& ) ) + : eoEvalFunc(), evalFunc( _eval ) {}; + + /// Effectively applies the evaluation function to an EO + virtual void operator() ( EOT & _eo ) const { + (*evalFunc)( _eo ); + }; + + private: + void (* evalFunc )( EOT& ); +}; + +#endif diff --git a/eo/src/eoEvaluator.h b/eo/src/eoEvaluator.h index 050caf853..3ddae376c 100644 --- a/eo/src/eoEvaluator.h +++ b/eo/src/eoEvaluator.h @@ -3,58 +3,58 @@ //----------------------------------------------------------------------------- // eoEvaluator.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 - */ +/* + 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 _EOEVALUATOR_H +#ifndef _EOEVALUATOR_H #define _EOEVALUATOR_H - + //----------------------------------------------------------------------------- #include #include - -//----------------------------------------------------------------------------- -/** Evaluator takes a vector of EOs and evaluates its fitness -* returning void. Template instances must be of fitness and EO type -*/ -template -class eoEvaluator: public eoTransform{ + +//----------------------------------------------------------------------------- +/** Evaluator takes a vector of EOs and evaluates its fitness +* returning void. Template instances must be of fitness and EO type +*/ +template +class eoEvaluator: public eoTransform{ public: /// ctor eoEvaluator( const eoEvalFunc< EOT> & _ef ) : eoTransform(), repEF( _ef ){}; - - /// Needed virtual destructor - virtual ~eoEvaluator() {}; - - /* Sets the evaluation function - virtual void EF( const eoEvalFunc< EOT> & _ef ) { repEF= _ef;};*/ + + /// Needed virtual destructor + virtual ~eoEvaluator() {}; + + /* Sets the evaluation function + virtual void EF( const eoEvalFunc< EOT> & _ef ) { repEF= _ef;};*/ /// Gets the evaluation function virtual const eoEvalFunc< EOT>& EF() { return repEF;}; - + /** This is the actual function operator(); it is left without implementation. - It takes a vector of pointers to eo - * @param _vEO is a vector of pointers to eo, that will be evaluated + It takes a vector of pointers to eo + * @param _vEO is a vector of pointers to eo, that will be evaluated */ - - virtual void operator() ( EOT& _eot ) const = 0; + + virtual void operator() ( EOT& _eot ) const = 0; ///@name eoObject methods //@{ @@ -62,11 +62,11 @@ public: virtual string className() const { return "eoEvaluator"; } /** Read and print are left without implementation */ - //@} + //@} private: - const eoEvalFunc< EOT> & repEF; -}; -//@} - -#endif + const eoEvalFunc< EOT> & repEF; +}; +//@} + +#endif diff --git a/eo/src/eoFitTerm.h b/eo/src/eoFitTerm.h index d8a7087e0..4181015fc 100644 --- a/eo/src/eoFitTerm.h +++ b/eo/src/eoFitTerm.h @@ -1,64 +1,64 @@ -// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - -//----------------------------------------------------------------------------- -// eoGenTerm.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 _EOFITTERM_H -#define _EOFITTERM_H - -#include - - -/** Fitness termination: terminates after a the difference between the -fitness of the best individual and a maximum fitness to achieve is less -than certain number called epsilon., i.e., |maximum-fitness| -class eoFitTerm: public eoTerm { -public: - - /// Ctors/dtors - eoFitTerm( const float _maximum, const float _epsilon ) - : eoTerm (), maximum( _maximum ), epsilon(_epsilon){}; - - /// Copy ctor - eoFitTerm( const eoFitTerm& _t ) - : eoTerm ( _t ), maximum( _t.maximum ), - epsilon(_t.epsilon){}; - - /// - virtual ~eoFitTerm() {}; - - /** Returns false when a certain number of generations is - * reached */ - virtual bool operator() ( const eoPop& _vEO ) { - float bestFitness=_vEO[0].fitness(); - float dif=bestFitness-maximum; - dif=(dif<0)?-dif:dif; - return (dif>epsilon ) || (bestFitness > maximum); - } - -private: - float maximum, epsilon; -}; - -#endif +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoGenTerm.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 _EOFITTERM_H +#define _EOFITTERM_H + +#include + + +/** Fitness termination: terminates after a the difference between the +fitness of the best individual and a maximum fitness to achieve is less +than certain number called epsilon., i.e., |maximum-fitness| +class eoFitTerm: public eoTerm { +public: + + /// Ctors/dtors + eoFitTerm( const float _maximum, const float _epsilon ) + : eoTerm (), maximum( _maximum ), epsilon(_epsilon){}; + + /// Copy ctor + eoFitTerm( const eoFitTerm& _t ) + : eoTerm ( _t ), maximum( _t.maximum ), + epsilon(_t.epsilon){}; + + /// + virtual ~eoFitTerm() {}; + + /** Returns false when a certain number of generations is + * reached */ + virtual bool operator() ( const eoPop& _vEO ) { + float bestFitness=_vEO[0].fitness(); + float dif=bestFitness-maximum; + dif=(dif<0)?-dif:dif; + return (dif>epsilon ) || (bestFitness > maximum); + } + +private: + float maximum, epsilon; +}; + +#endif diff --git a/eo/src/eoFitness.h b/eo/src/eoFitness.h index 8696f496c..8505c34fd 100644 --- a/eo/src/eoFitness.h +++ b/eo/src/eoFitness.h @@ -1,54 +1,54 @@ -// eoFitness.h -//----------------------------------------------------------------------------- -// eoFitness.cpp -// (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 EOFITNESS_H -#define EOFITNESS_H - -//----------------------------------------------------------------------------- - -class eoFitness: public eoPersistent -{ - public: - virtual operator float() const = 0; - - virtual bool operator<(const eoFitness& other) const = 0; - - virtual bool operator>(const eoFitness& other) const - { - return !(*this < other || *this == other); - } - - virtual bool operator==(const eoFitness& other) const - { - return !(other < *this || *this < other); - } - - virtual bool operator!=(const eoFitness& other) const - { - return other < *this || *this < other; - } -}; - -//----------------------------------------------------------------------------- - -#endif EOFITNESS_H +// eoFitness.h +//----------------------------------------------------------------------------- +// eoFitness.cpp +// (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 EOFITNESS_H +#define EOFITNESS_H + +//----------------------------------------------------------------------------- + +class eoFitness: public eoPersistent +{ + public: + virtual operator float() const = 0; + + virtual bool operator<(const eoFitness& other) const = 0; + + virtual bool operator>(const eoFitness& other) const + { + return !(*this < other || *this == other); + } + + virtual bool operator==(const eoFitness& other) const + { + return !(other < *this || *this < other); + } + + virtual bool operator!=(const eoFitness& other) const + { + return other < *this || *this < other; + } +}; + +//----------------------------------------------------------------------------- + +#endif EOFITNESS_H diff --git a/eo/src/eoGenTerm.h b/eo/src/eoGenTerm.h index 7da104c08..3e6b0aa54 100644 --- a/eo/src/eoGenTerm.h +++ b/eo/src/eoGenTerm.h @@ -1,82 +1,82 @@ -// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - -//----------------------------------------------------------------------------- -// eoGenTerm.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 _EOGENTERM_H -#define _EOGENTERM_H - -#include - -/** Generational termination: terminates after a number of generations -*/ -template< class EOT> -class eoGenTerm: public eoTerm { -public: - - /// Ctors/dtors - eoGenTerm( unsigned _totalGens) - : eoTerm (), repTotalGenerations( _totalGens ), - thisGeneration(0){}; - - /// Copy Ctor - eoGenTerm( const eoGenTerm& _t) - : eoTerm ( _t ), repTotalGenerations( _t.repTotalGenerations ), - thisGeneration(0){}; - - /// Assignment Operator - const eoGenTerm& operator = ( const eoGenTerm& _t) { - if ( &_t != this ) { - repTotalGenerations = _t.repTotalGenerations; - thisGeneration = 0; +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoGenTerm.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 _EOGENTERM_H +#define _EOGENTERM_H + +#include + +/** Generational termination: terminates after a number of generations +*/ +template< class EOT> +class eoGenTerm: public eoTerm { +public: + + /// Ctors/dtors + eoGenTerm( unsigned _totalGens) + : eoTerm (), repTotalGenerations( _totalGens ), + thisGeneration(0){}; + + /// Copy Ctor + eoGenTerm( const eoGenTerm& _t) + : eoTerm ( _t ), repTotalGenerations( _t.repTotalGenerations ), + thisGeneration(0){}; + + /// Assignment Operator + const eoGenTerm& operator = ( const eoGenTerm& _t) { + if ( &_t != this ) { + repTotalGenerations = _t.repTotalGenerations; + thisGeneration = 0; } - return *this; - } - - /// Dtor - virtual ~eoGenTerm() {}; - - /** Returns false when a certain number of generations is - * reached */ - virtual bool operator() ( const eoPop& _vEO ) { - thisGeneration++; - // cout << " [" << thisGeneration << "] "; - return (thisGeneration < repTotalGenerations) ; // for the postincrement - } - - /** Sets the number of generations to reach - and sets the current generation to 0 (the begin)*/ - virtual void totalGenerations( unsigned _tg ) { - repTotalGenerations = _tg; - // thisGeneration = 0; - }; - - /** Returns the number of generations to reach*/ - virtual unsigned totalGenerations( ) { - return repTotalGenerations; - }; - -private: - unsigned repTotalGenerations, thisGeneration; -}; - -#endif + return *this; + } + + /// Dtor + virtual ~eoGenTerm() {}; + + /** Returns false when a certain number of generations is + * reached */ + virtual bool operator() ( const eoPop& _vEO ) { + thisGeneration++; + // cout << " [" << thisGeneration << "] "; + return (thisGeneration < repTotalGenerations) ; // for the postincrement + } + + /** Sets the number of generations to reach + and sets the current generation to 0 (the begin)*/ + virtual void totalGenerations( unsigned _tg ) { + repTotalGenerations = _tg; + // thisGeneration = 0; + }; + + /** Returns the number of generations to reach*/ + virtual unsigned totalGenerations( ) { + return repTotalGenerations; + }; + +private: + unsigned repTotalGenerations, thisGeneration; +}; + +#endif diff --git a/eo/src/eoGeneration.h b/eo/src/eoGeneration.h index 3adbb10e6..1bfec9a28 100644 --- a/eo/src/eoGeneration.h +++ b/eo/src/eoGeneration.h @@ -1,80 +1,80 @@ -// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - -//----------------------------------------------------------------------------- -// eoOp.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 eoGeneration_h -#define eoGeneration_h - -//----------------------------------------------------------------------------- - -#include // eoPop -#include -#include // eoSelect, eoTranform, eoMerge - -//----------------------------------------------------------------------------- -// eoGeneration -//----------------------------------------------------------------------------- - -template class eoGeneration: public eoAlgo -{ - public: - /// Constructor. - eoGeneration(eoSelect& _select, - eoTransform& _transform, - eoMerge& _replace, - eoEvalFunc& _evaluator): - select(_select), transform(_transform), - replace(_replace), evaluator( _evaluator) {}; - - /// Copy Constructor. - eoGeneration(eoGeneration& _gen): - select(_gen.select), transform(_gen.transform), - replace(_gen.replace), evaluator( _gen.evaluator ) {}; - - - /// Apply one generation of evolution to the population. - virtual void operator()(eoPop& pop) { - eoPop breeders; - select(pop, breeders); - transform(breeders); - eoPop::iterator i; - // Can't use foreach here since foreach takes the - // parameter by reference - for ( i = breeders.begin(); i != breeders.end(); i++) - evaluator(*i); - replace(breeders, pop); - } - - /// Class name. - string className() const { return "eoGeneration"; } - - private: - eoSelect& select; - eoTransform& transform; - eoMerge& replace; - eoEvalFunc& evaluator; -}; - -//----------------------------------------------------------------------------- - -#endif eoGeneration_h +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoOp.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 eoGeneration_h +#define eoGeneration_h + +//----------------------------------------------------------------------------- + +#include // eoPop +#include +#include // eoSelect, eoTranform, eoMerge + +//----------------------------------------------------------------------------- +// eoGeneration +//----------------------------------------------------------------------------- + +template class eoGeneration: public eoAlgo +{ + public: + /// Constructor. + eoGeneration(eoSelect& _select, + eoTransform& _transform, + eoMerge& _replace, + eoEvalFunc& _evaluator): + select(_select), transform(_transform), + replace(_replace), evaluator( _evaluator) {}; + + /// Copy Constructor. + eoGeneration(eoGeneration& _gen): + select(_gen.select), transform(_gen.transform), + replace(_gen.replace), evaluator( _gen.evaluator ) {}; + + + /// Apply one generation of evolution to the population. + virtual void operator()(eoPop& pop) { + eoPop breeders; + select(pop, breeders); + transform(breeders); + eoPop::iterator i; + // Can't use foreach here since foreach takes the + // parameter by reference + for ( i = breeders.begin(); i != breeders.end(); i++) + evaluator(*i); + replace(breeders, pop); + } + + /// Class name. + string className() const { return "eoGeneration"; } + + private: + eoSelect& select; + eoTransform& transform; + eoMerge& replace; + eoEvalFunc& evaluator; +}; + +//----------------------------------------------------------------------------- + +#endif eoGeneration_h diff --git a/eo/src/eoID.h b/eo/src/eoID.h index 7488d26bd..ed8ceecd3 100644 --- a/eo/src/eoID.h +++ b/eo/src/eoID.h @@ -1,40 +1,40 @@ // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- -//----------------------------------------------------------------------------- +//----------------------------------------------------------------------------- // eoID.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 EOID_H -#define EOID_H - -//----------------------------------------------------------------------------- - -#include // istream, ostream -#include // for string +// (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 EOID_H +#define EOID_H + +//----------------------------------------------------------------------------- + +#include // istream, ostream +#include // for string using namespace std; - -//----------------------------------------------------------------------------- -// eoID -//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// eoID +//----------------------------------------------------------------------------- /** eoID is a template class that adds an ID to an object.\\ Requisites for template instantiation are that the object must admit a default ctor @@ -43,18 +43,18 @@ printOn, readFrom, that is why we don IDs can be used to count objects of a a kind, or track them, or whatever. @see eoObject */ -template -class eoID: public Object -{ - public: +template +class eoID: public Object +{ + public: /// Main ctor from an already built Object. eoID( const Object& _o): Object( _o ), thisID(globalID++) {}; - - /// Copy constructor. + + /// Copy constructor. eoID( const eoID& _id): Object( _id ), thisID(globalID++ ) {}; /// Virtual dtor. They are needed in virtual class hierarchies - virtual ~eoID() {}; + virtual ~eoID() {}; ///returns the age of the object @@ -63,32 +63,32 @@ class eoID: public Object /** @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("[eoID]")+Object::className(); }; - - /** - * Read object. - * @param _is A istream. - * @throw runtime_exception If a valid object can't be read. - */ + //@{ + /** 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("[eoID]")+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 >> thisID; } - - - /** - * Write object. It's called printOn since it prints the object _on_ a stream. - * @param _os A ostream. - */ + + + /** + * 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 << thisID; - } + } //@} private: @@ -100,10 +100,10 @@ class eoID: public Object eoID(): Object(), thisID( globalID++ ) {}; unsigned long thisID; - static unsigned long globalID; + static unsigned long globalID; }; template< class Object> unsigned long eoID< Object >::globalID = 0; - -#endif EOID_H + +#endif EOID_H diff --git a/eo/src/eoInsertion.h b/eo/src/eoInsertion.h index 7674b958a..0e33cb74a 100644 --- a/eo/src/eoInsertion.h +++ b/eo/src/eoInsertion.h @@ -1,79 +1,79 @@ -//----------------------------------------------------------------------------- -// eoInsertion.h -//----------------------------------------------------------------------------- - -#ifndef eoInsertion_h -#define eoInsertion_h - -//----------------------------------------------------------------------------- - -#include // eoPop -#include // eoMerge - -/****************************************************************************** - * eoInsertion: A replacement algorithm. - * Creates a new population with all the breeders and the best individuals - * from the original population. - *****************************************************************************/ - -template class eoInsertion: public eoMerge -{ - public: - /// (Default) Constructor. - eoInsertion(const float& _rate = 1.0): eoMerge(_rate) {} - - /** - * Creates a new population based on breeders and original populations. - * @param breeders The population of breeders. - * @param pop The original population. - */ - /*void operator()(eoPop& breeders, eoPop& pop) - { - int new_size = static_cast(pop.size() * rate()); - - if (new_size == breeders.size()) - { - pop = breeders; - } - else if (new_size < breeders.size()) - { - pop = breeders; - sort(pop.begin(), pop.end()); - pop.erase(pop.begin(), pop.begin() - new_size + pop.size()); - } - else - { - sort(pop.begin(), pop.end()); - pop.erase(pop.begin(), - pop.begin() + breeders.size() + pop.size() - new_size); - copy(breeders.begin(), breeders.end(), - back_insert_iterator >(pop)); - } - }*/ - - void operator()(eoPop& breeders, eoPop& pop) - { - unsigned target = static_cast(rint(pop.size() * rate())); - - pop.swap(breeders); - - if (target < pop.size()) - { - partial_sort(pop.begin(), pop.begin() + target, pop.end(), - greater()); - pop.erase(pop.begin() + target, pop.end()); - } - else - { - target = min(target - pop.size(), breeders.size()); - partial_sort(breeders.begin(), breeders.begin() + target, - breeders.end(), greater()); - copy(breeders.begin(), breeders.begin() + target, - back_insert_iterator >(pop)); - } - } -}; - -//----------------------------------------------------------------------------- - -#endif eoInsertion_h +//----------------------------------------------------------------------------- +// eoInsertion.h +//----------------------------------------------------------------------------- + +#ifndef eoInsertion_h +#define eoInsertion_h + +//----------------------------------------------------------------------------- + +#include // eoPop +#include // eoMerge + +/****************************************************************************** + * eoInsertion: A replacement algorithm. + * Creates a new population with all the breeders and the best individuals + * from the original population. + *****************************************************************************/ + +template class eoInsertion: public eoMerge +{ + public: + /// (Default) Constructor. + eoInsertion(const float& _rate = 1.0): eoMerge(_rate) {} + + /** + * Creates a new population based on breeders and original populations. + * @param breeders The population of breeders. + * @param pop The original population. + */ + /*void operator()(eoPop& breeders, eoPop& pop) + { + int new_size = static_cast(pop.size() * rate()); + + if (new_size == breeders.size()) + { + pop = breeders; + } + else if (new_size < breeders.size()) + { + pop = breeders; + sort(pop.begin(), pop.end()); + pop.erase(pop.begin(), pop.begin() - new_size + pop.size()); + } + else + { + sort(pop.begin(), pop.end()); + pop.erase(pop.begin(), + pop.begin() + breeders.size() + pop.size() - new_size); + copy(breeders.begin(), breeders.end(), + back_insert_iterator >(pop)); + } + }*/ + + void operator()(eoPop& breeders, eoPop& pop) + { + unsigned target = static_cast(rint(pop.size() * rate())); + + pop.swap(breeders); + + if (target < pop.size()) + { + partial_sort(pop.begin(), pop.begin() + target, pop.end(), + greater()); + pop.erase(pop.begin() + target, pop.end()); + } + else + { + target = min(target - pop.size(), breeders.size()); + partial_sort(breeders.begin(), breeders.begin() + target, + breeders.end(), greater()); + copy(breeders.begin(), breeders.begin() + target, + back_insert_iterator >(pop)); + } + } +}; + +//----------------------------------------------------------------------------- + +#endif eoInsertion_h diff --git a/eo/src/eoKill.h b/eo/src/eoKill.h index bddcbb2bb..826274f06 100644 --- a/eo/src/eoKill.h +++ b/eo/src/eoKill.h @@ -3,23 +3,23 @@ //----------------------------------------------------------------------------- // eoKill.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 - */ +/* + 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 _EOKILL_h diff --git a/eo/src/eoMultiMonOp.h b/eo/src/eoMultiMonOp.h index c46f87779..c06a27947 100644 --- a/eo/src/eoMultiMonOp.h +++ b/eo/src/eoMultiMonOp.h @@ -3,23 +3,23 @@ //----------------------------------------------------------------------------- // eoMultiMonOp.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 - */ +/* + 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 _EOMULTIMONOP_h diff --git a/eo/src/eoMutation.h b/eo/src/eoMutation.h index 466c377ee..fbc3641c0 100644 --- a/eo/src/eoMutation.h +++ b/eo/src/eoMutation.h @@ -1,133 +1,90 @@ -// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - -//----------------------------------------------------------------------------- -// eoMutation.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 _EOMUTATION_H -#define _EOMUTATION_H - -#include -// EO includes -#include -#include - -/** Generic Mutation of an EO. - This is a virtual class, just to establish the interface -*/ - -template -class eoMutation: public eoMonOp { -public: - - /// - eoMutation(const double _rate=0.0) : eoMonOp< EOT >(), rate(_rate) {}; - - /// - virtual ~eoMutation() {}; - - /// - virtual void operator()( EOT& _eo ) const { - for ( unsigned i = 0; i < _eo.length(); i ++ ) - applyAt( _eo, i ); - } - - /// To print me on a stream. - /// @param os The ostream. - void printOn(ostream& os) const { - os << rate ; - } - - /// To read me from a stream. - /// @param is The istream. - void readFrom(istream& is) { - is >> rate ; - } - - /** @name Methods from eoObject - */ - //@{ - /** Inherited from eoObject - @see eoObject - */ - string className() const {return "eoMutation";}; - //@} - -protected: - double rate; - -private: -#ifdef _MSC_VER - typedef EOT::Type Type; -#else - typedef typename EOT::Type Type; -#endif - - /// applies operator to one gene in the EO. It is empty, so each descent class must define it. - virtual void applyAt( EOT& _eo, unsigned _i ) const = 0 ; -}; - - - -/** Mutation of an eoString. - The eoString's genes are changed by adding or substracting 1 to -*/ - -template -class eoStringMutation: public eoMutation { - 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 uniform( 0, 1 ); - if( rate < uniform() ) { - _eo.gene(_i) += ( uniform()>=0.5 )? (1) : (-1) ; - } - } - -}; - -//----------------------------------------------------------------------------- - -#endif +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoMutation.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 _EOMUTATION_H +#define _EOMUTATION_H + +#include +// EO includes +#include +#include + +/** Generic Mutation of an EO. + This is a virtual class, just to establish the interface for the ctor. + Mutation is usually type-specific +*/ + +template +class eoMutation: public eoMonOp { +public: + + /// + eoMutation(const double _rate=0.0) : eoMonOp< EOT >(), rate(_rate) {}; + + /// + virtual ~eoMutation() {}; + + /// + virtual void operator()( EOT& _eo ) const { + typename EOT::iterator i; + for ( i = _eo.begin(); i != _eo.end(); i ++ ) + applyAt( _eo, *i ); + } + + /// To print me on a stream. + /// @param os The ostream. + void printOn(ostream& os) const { + os << rate ; + } + + /// To read me from a stream. + /// @param is The istream. + void readFrom(istream& is) { + is >> rate ; + } + + /** @name Methods from eoObject + */ + //@{ + /** Inherited from eoObject + @see eoObject + */ + string className() const {return "eoMutation";}; + //@} + +protected: + double rate; + +private: +#ifdef _MSC_VER + typedef EOT::Type Type; +#else + typedef typename EOT::Type Type; +#endif + + /// applies operator to one gene in the EO. It is empty, so each descent class must define it. + virtual void applyAt( EOT& _eo, unsigned _i ) const = 0 ; +}; + + +#endif diff --git a/eo/src/eoNegExp.h b/eo/src/eoNegExp.h index 3805669b7..beb63479f 100644 --- a/eo/src/eoNegExp.h +++ b/eo/src/eoNegExp.h @@ -1,66 +1,66 @@ -// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - -//----------------------------------------------------------------------------- -// eoNegExp.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 _EONEGEXP_H -#define _EONEGEXP_H - -//----------------------------------------------------------------------------- - -#include - -#include // for base class -#include // for base class - -//----------------------------------------------------------------------------- -// Class eoNegExp -//----------------------------------------------------------------------------- - -/// Generates random numbers using a negative exponential distribution -template -class eoNegExp: public eoRnd -{ - public: - /** - * Default constructor. - * @param _mean Dsitribution mean - */ - eoNegExp(T _mean): eoRnd(), mean(_mean) {}; - - /** - * Copy constructor. - * @param _rnd the copyee - */ - eoNegExp( const eoNegExp& _rnd): eoRnd( _rnd), mean(_rnd.mean) {}; - - /// Returns an uniform dandom number over the interval [min, max). - virtual T operator()() { - return T( -mean*log((double)rng.rand() / rng.rand_max())); } - - private: - T mean; -}; - -//----------------------------------------------------------------------------- - -#endif +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoNegExp.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 _EONEGEXP_H +#define _EONEGEXP_H + +//----------------------------------------------------------------------------- + +#include + +#include // for base class +#include // for base class + +//----------------------------------------------------------------------------- +// Class eoNegExp +//----------------------------------------------------------------------------- + +/// Generates random numbers using a negative exponential distribution +template +class eoNegExp: public eoRnd +{ + public: + /** + * Default constructor. + * @param _mean Dsitribution mean + */ + eoNegExp(T _mean): eoRnd(), mean(_mean) {}; + + /** + * Copy constructor. + * @param _rnd the copyee + */ + eoNegExp( const eoNegExp& _rnd): eoRnd( _rnd), mean(_rnd.mean) {}; + + /// Returns an uniform dandom number over the interval [min, max). + virtual T operator()() { + return T( -mean*log((double)rng.rand() / rng.rand_max())); } + + private: + T mean; +}; + +//----------------------------------------------------------------------------- + +#endif diff --git a/eo/src/eoNonUniform.h b/eo/src/eoNonUniform.h index 438f72660..c894806fb 100644 --- a/eo/src/eoNonUniform.h +++ b/eo/src/eoNonUniform.h @@ -1,86 +1,86 @@ -//----------------------------------------------------------------------------- -// eoNonUniform.h -//----------------------------------------------------------------------------- - -#ifndef EONONUNIFORM_H -#define EONONUNIFORM_H - -//----------------------------------------------------------------------------- - -#include // pow - -//----------------------------------------------------------------------------- -// eoNonUniform -//----------------------------------------------------------------------------- - -class eoNonUniform -{ -public: - eoNonUniform(const unsigned _num_step): - step_value(0), num_step_value(_num_step) {} - - void reset() { step_value = 0; } - - const unsigned& step() const { return step_value; } - const unsigned& num_step() const { return num_step_value; } - - operator int() const { return step_value < num_step_value; } - - void operator++() { ++step_value; } - void operator++(int) { ++step_value; } - -private: - unsigned step_value, num_step_value; -}; - -//----------------------------------------------------------------------------- -// eoLinear -//----------------------------------------------------------------------------- - -class eoLinear -{ -public: - eoLinear(const double _first, - const double _last, - const eoNonUniform& _non_uniform): - first(_first), - diff((_last - _first) / (_non_uniform.num_step() - 1)), - non_uniform(_non_uniform) {} - - double operator()() const - { - return first + diff * non_uniform.step(); - } - -private: - double first, diff; - const eoNonUniform& non_uniform; -}; - -//----------------------------------------------------------------------------- -// eoNegExp2 -//----------------------------------------------------------------------------- - -class eoNegExp2 -{ - public: - eoNegExp2(const double _r, - const double _b, - const eoNonUniform& _non_uniform): - r(_r), b(_b), - non_uniform(_non_uniform) {} - - double operator()() const - { - return 1.0 - pow(r, pow(1.0 - (double)non_uniform.step() / - non_uniform.num_step(), b)); - } - - private: - double r, b; - const eoNonUniform& non_uniform; -}; - -//----------------------------------------------------------------------------- - -#endif NON_UNIFORM_HH +//----------------------------------------------------------------------------- +// eoNonUniform.h +//----------------------------------------------------------------------------- + +#ifndef EONONUNIFORM_H +#define EONONUNIFORM_H + +//----------------------------------------------------------------------------- + +#include // pow + +//----------------------------------------------------------------------------- +// eoNonUniform +//----------------------------------------------------------------------------- + +class eoNonUniform +{ +public: + eoNonUniform(const unsigned _num_step): + step_value(0), num_step_value(_num_step) {} + + void reset() { step_value = 0; } + + const unsigned& step() const { return step_value; } + const unsigned& num_step() const { return num_step_value; } + + operator int() const { return step_value < num_step_value; } + + void operator++() { ++step_value; } + void operator++(int) { ++step_value; } + +private: + unsigned step_value, num_step_value; +}; + +//----------------------------------------------------------------------------- +// eoLinear +//----------------------------------------------------------------------------- + +class eoLinear +{ +public: + eoLinear(const double _first, + const double _last, + const eoNonUniform& _non_uniform): + first(_first), + diff((_last - _first) / (_non_uniform.num_step() - 1)), + non_uniform(_non_uniform) {} + + double operator()() const + { + return first + diff * non_uniform.step(); + } + +private: + double first, diff; + const eoNonUniform& non_uniform; +}; + +//----------------------------------------------------------------------------- +// eoNegExp2 +//----------------------------------------------------------------------------- + +class eoNegExp2 +{ + public: + eoNegExp2(const double _r, + const double _b, + const eoNonUniform& _non_uniform): + r(_r), b(_b), + non_uniform(_non_uniform) {} + + double operator()() const + { + return 1.0 - pow(r, pow(1.0 - (double)non_uniform.step() / + non_uniform.num_step(), b)); + } + + private: + double r, b; + const eoNonUniform& non_uniform; +}; + +//----------------------------------------------------------------------------- + +#endif NON_UNIFORM_HH diff --git a/eo/src/eoNormal.h b/eo/src/eoNormal.h index 5dfe49bd1..e7302c76d 100644 --- a/eo/src/eoNormal.h +++ b/eo/src/eoNormal.h @@ -1,51 +1,51 @@ -// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - -//----------------------------------------------------------------------------- -// eoNormal.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 _EONORMAL_H -#define _EONORMAL_H - -//----------------------------------------------------------------------------- - -#include -#include // for base class -#include // for random number generator - -//----------------------------------------------------------------------------- -// Class eoNormal -//----------------------------------------------------------------------------- - -/// Generates random number using a normal distribution -template -class eoNormal: public eoRnd -{ - public: - /** - * Default constructor. - * @param _mean Dsitribution mean - * @param _sd Standard Deviation - */ - eoNormal(T _mean, T _sd) +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoNormal.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 _EONORMAL_H +#define _EONORMAL_H + +//----------------------------------------------------------------------------- + +#include +#include // for base class +#include // for random number generator + +//----------------------------------------------------------------------------- +// Class eoNormal +//----------------------------------------------------------------------------- + +/// Generates random number using a normal distribution +template +class eoNormal: public eoRnd +{ + public: + /** + * Default constructor. + * @param _mean Dsitribution mean + * @param _sd Standard Deviation + */ + eoNormal(T _mean, T _sd) : eoRnd(), mean(_mean), sd(_sd), phase(false) {} /** @@ -53,36 +53,36 @@ class eoNormal: public eoRnd * @param _rnd the other one */ eoNormal( const eoNormal& _rnd ) - : eoRnd( _rnd), mean(_rnd.mean), sd(_rnd.sd), phase(false) {} - - /** Returns an uniform random number over the interval [min, max). - @return an uniform random number over the interval [min, max). - */ - virtual T operator()() { - if (phase) { // Already have one stored up. - phase = false; - return T ( (sqRatio * q * sd) + mean ); - } - - double p, v; - do { - p = ((double)rng.rand() / rng.rand_max())*2-1; - q = ((double)rng.rand() / rng.rand_max())*2-1; - v = p*p + q*q; - } while(v > 1.0 || v <0.25); - - sqRatio = sqrt(-2*log((double)rand() / rng.rand_max()) / v); - phase = true; - return T( (sqRatio * p * sd) + mean ); - }; - - private: - T mean; - T sd; - bool phase; - double sqRatio, q; -}; - -//----------------------------------------------------------------------------- - -#endif + : eoRnd( _rnd), mean(_rnd.mean), sd(_rnd.sd), phase(false) {} + + /** Returns an uniform random number over the interval [min, max). + @return an uniform random number over the interval [min, max). + */ + virtual T operator()() { + if (phase) { // Already have one stored up. + phase = false; + return T ( (sqRatio * q * sd) + mean ); + } + + double p, v; + do { + p = ((double)rng.rand() / rng.rand_max())*2-1; + q = ((double)rng.rand() / rng.rand_max())*2-1; + v = p*p + q*q; + } while(v > 1.0 || v <0.25); + + sqRatio = sqrt(-2*log((double)rand() / rng.rand_max()) / v); + phase = true; + return T( (sqRatio * p * sd) + mean ); + }; + + private: + T mean; + T sd; + bool phase; + double sqRatio, q; +}; + +//----------------------------------------------------------------------------- + +#endif diff --git a/eo/src/eoObject.h b/eo/src/eoObject.h index 56a746b58..8bf2e1372 100644 --- a/eo/src/eoObject.h +++ b/eo/src/eoObject.h @@ -1,66 +1,66 @@ // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- -//----------------------------------------------------------------------------- +//----------------------------------------------------------------------------- // eoObject.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 EOOBJECT_H -#define EOOBJECT_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. -#include // For limits definition -#include // istream, ostream -#include // string + 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 EOOBJECT_H +#define EOOBJECT_H + +//----------------------------------------------------------------------------- + +#include // For limits definition +#include // istream, ostream +#include // string using namespace std; - -//----------------------------------------------------------------------------- -// eoObject -//----------------------------------------------------------------------------- -/** -This is the base class for the whole hierarchy; an eoObject defines -basically an interface for the whole hierarchy: each object should + +//----------------------------------------------------------------------------- +// eoObject +//----------------------------------------------------------------------------- +/** +This is the base class for the whole hierarchy; an eoObject defines +basically an interface for the whole hierarchy: each object should know its name (#className#). Previously, this object defined a print and read -interface, but it´s been moved to eoPrintable and eoPersistent. - */ -class eoObject -{ - public: - - /// Default Constructor. - eoObject() {} - - /// Copy constructor. - eoObject( const eoObject& ) {} - - /// Virtual dtor. They are needed in virtual class hierarchies. - virtual ~eoObject() {} - - /** 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 "eoObject"; } - -}; - -#endif EOOBJECT_H +interface, but it´s been moved to eoPrintable and eoPersistent. + */ +class eoObject +{ + public: + + /// Default Constructor. + eoObject() {} + + /// Copy constructor. + eoObject( const eoObject& ) {} + + /// Virtual dtor. They are needed in virtual class hierarchies. + virtual ~eoObject() {} + + /** 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 "eoObject"; } + +}; + +#endif EOOBJECT_H diff --git a/eo/src/eoOp.h b/eo/src/eoOp.h index d93c2a36a..5a1cb8288 100644 --- a/eo/src/eoOp.h +++ b/eo/src/eoOp.h @@ -1,204 +1,204 @@ -// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - -//----------------------------------------------------------------------------- -// eoOp.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 _eoOp_H -#define _eoOp_H - -#include -#include -#include - -/** @name Genetic operators - -What is a genetic algorithm without genetic operators? There is a genetic operator hierarchy, with -eoOp as father and eoMonOp (monary or unary operator) and eoBinOp (binary operator) as siblings. Nobody -should subclass eoOp, you should subclass eoBinOp or eoMonOp, those are the ones actually used here.\\ -#eoOp#s are only printable objects, so if you want to build them from a file, it has to -be done in another class, namely factories. Each hierarchy of #eoOp#s should have its own -factory, which know how to build them from a description in a file. -@author GeNeura Team -@version 0.1 -@see eoOpFactory -*/ -//@{ - -/// -enum Arity { unary = 0, binary = 1, Nary = 2}; - -/** Abstract data types for EO operators. - * Genetic operators act on chromosomes, changing them. The type to instantiate them should - * be an eoObject, but in any case, they are type-specific; each kind of evolvable object - * can have its own operators - */ -template -class eoOp: public eoObject, public eoPrintable { -public: - - /// Ctor - eoOp( Arity _arity = unary ) - :arity( _arity ) {}; - - /// Copy Ctor - eoOp( const eoOp& _eop ) - :arity( _eop.arity ) {}; - - /// Needed virtual destructor - virtual ~eoOp(){}; - - /// Arity: number of operands - Arity readArity() const {return arity;}; - - /** @name Methods from eoObject */ - //@{ - - /** - * Write object. It's called printOn since it prints the object _on_ a stream. - * @param _os A ostream. - */ - virtual void printOn(ostream& _os) const { - _os << className(); -// _os << arity; - }; - - /** Inherited from eoObject - @see eoObject - */ - virtual string className() const {return "eoOp";}; - //@} - - -private: - /// arity is the number of operands it takes - Arity arity; - -}; - -/** Binary genetic operator: subclasses eoOp, and defines -basically the operator() with two operands -*/ -template -class eoBinOp: public eoOp { -public: - - /// Ctor - eoBinOp() - :eoOp( binary ) {}; - - /// Copy Ctor - eoBinOp( const eoBinOp& _ebop ) - : eoOp( _ebop ){}; - - /// Dtor - ~eoBinOp () {}; - - /** applies operator, to the object. If arity is more than 1, - * keeps a copy of the operand in a cache. - */ - virtual void operator()( EOType& _eo1, EOType& _eo2 ) const = 0; - - /** @name Methods from eoObject - readFrom and printOn are directly inherited from eoObject - */ - //@{ - /** Inherited from eoObject - @see eoObject - */ - virtual string className() const {return "eoBinOp";}; - //@} - -}; - -/** eoMonOp is the monary operator: genetic operator that takes - only one EO -*/ -template -class eoMonOp: public eoOp { -public: - - /// Ctor - eoMonOp( ) - :eoOp( unary ) {}; - - /// Copy Ctor - eoMonOp( const eoMonOp& _emop ) - : eoOp( _emop ){}; - - /// Dtor - ~eoMonOp() {}; - - /** applies randomly operator, to the object. If arity is more than 1, - * keeps a copy of the operand in a cache. - */ - virtual void operator()( EOType& _eo1) const = 0; - - /** @name Methods from eoObject - readFrom and printOn are directly inherited from eoObject - */ - //@{ - /** Inherited from eoObject - @see eoObject - */ - virtual string className() const {return "eoMonOp";}; - //@} - - -}; - -#include -/** eoNaryOp is the N-ary operator: genetic operator that takes - several EOs. It could be called an {\em orgy} operator -*/ -template -class eoNaryOp: public eoOp { -public: - - /// Ctor - eoNaryOp( ) - :eoOp( Nary ) {}; - - /// Copy Ctor - eoNaryOp( const eoNaryOp& _emop ) - : eoOp( _emop ){}; - - /// Dtor - ~eoNaryOp() {}; - - /** applies randomly operator, to the object. - */ - virtual void operator()( eoPop & _eop) const = 0; - - /** @name Methods from eoObject - readFrom and printOn are directly inherited from eoObject. - */ - //@{ - /** Inherited from eoObject - @see eoObject - */ - string className() const {return "eoNaryOp";}; - //@} - -}; -//@} - -#endif +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoOp.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 _eoOp_H +#define _eoOp_H + +#include +#include +#include + +/** @name Genetic operators + +What is a genetic algorithm without genetic operators? There is a genetic operator hierarchy, with +eoOp as father and eoMonOp (monary or unary operator) and eoBinOp (binary operator) as siblings. Nobody +should subclass eoOp, you should subclass eoBinOp or eoMonOp, those are the ones actually used here.\\ +#eoOp#s are only printable objects, so if you want to build them from a file, it has to +be done in another class, namely factories. Each hierarchy of #eoOp#s should have its own +factory, which know how to build them from a description in a file. +@author GeNeura Team +@version 0.1 +@see eoOpFactory +*/ +//@{ + +/// +enum Arity { unary = 0, binary = 1, Nary = 2}; + +/** Abstract data types for EO operators. + * Genetic operators act on chromosomes, changing them. The type to instantiate them should + * be an eoObject, but in any case, they are type-specific; each kind of evolvable object + * can have its own operators + */ +template +class eoOp: public eoObject, public eoPrintable { +public: + + /// Ctor + eoOp( Arity _arity = unary ) + :arity( _arity ) {}; + + /// Copy Ctor + eoOp( const eoOp& _eop ) + :arity( _eop.arity ) {}; + + /// Needed virtual destructor + virtual ~eoOp(){}; + + /// Arity: number of operands + Arity readArity() const {return arity;}; + + /** @name Methods from eoObject */ + //@{ + + /** + * Write object. It's called printOn since it prints the object _on_ a stream. + * @param _os A ostream. + */ + virtual void printOn(ostream& _os) const { + _os << className(); +// _os << arity; + }; + + /** Inherited from eoObject + @see eoObject + */ + virtual string className() const {return "eoOp";}; + //@} + + +private: + /// arity is the number of operands it takes + Arity arity; + +}; + +/** Binary genetic operator: subclasses eoOp, and defines +basically the operator() with two operands +*/ +template +class eoBinOp: public eoOp { +public: + + /// Ctor + eoBinOp() + :eoOp( binary ) {}; + + /// Copy Ctor + eoBinOp( const eoBinOp& _ebop ) + : eoOp( _ebop ){}; + + /// Dtor + ~eoBinOp () {}; + + /** applies operator, to the object. Modifies both operands. + */ + virtual void operator()( EOType& _eo1, EOType& _eo2 ) const = 0; + + /** @name Methods from eoObject + readFrom and printOn are directly inherited from eoObject + */ + //@{ + /** Inherited from eoObject + @see eoObject + */ + virtual string className() const {return "eoBinOp";}; + //@} + +}; + +/** eoMonOp is the monary operator: genetic operator that takes + only one EO +*/ +template +class eoMonOp: public eoOp { +public: + + /// Ctor + eoMonOp( ) + :eoOp( unary ) {}; + + /// Copy Ctor + eoMonOp( const eoMonOp& _emop ) + : eoOp( _emop ){}; + + /// Dtor + ~eoMonOp() {}; + + /** applies randomly operator, to the object. If arity is more than 1, + * keeps a copy of the operand in a cache. + */ + virtual void operator()( EOType& _eo1) const = 0; + + /** @name Methods from eoObject + readFrom and printOn are directly inherited from eoObject + */ + //@{ + /** Inherited from eoObject + @see eoObject + */ + virtual string className() const {return "eoMonOp";}; + //@} + + +}; + +#include +/** eoNaryOp is the N-ary operator: genetic operator that takes + several EOs. It could be called an {\em orgy} operator. It's a general operator + that takes any number of inputs and spits out any number of outputs +*/ +template +class eoNaryOp: public eoOp { +public: + + /// Ctor + eoNaryOp( ) + :eoOp( Nary ) {}; + + /// Copy Ctor + eoNaryOp( const eoNaryOp& _emop ) + : eoOp( _emop ){}; + + /// Dtor + ~eoNaryOp() {}; + + /** applies randomly operator, to the object. + */ + virtual void operator()( const eoPop & _in, eoPop _out ) const = 0; + + /** @name Methods from eoObject + readFrom and printOn are directly inherited from eoObject. + */ + //@{ + /** Inherited from eoObject + @see eoObject + */ + string className() const {return "eoNaryOp";}; + //@} + +}; +//@} + +#endif diff --git a/eo/src/eoOpSelector.h b/eo/src/eoOpSelector.h index 2ee11205c..d4c9940b9 100644 --- a/eo/src/eoOpSelector.h +++ b/eo/src/eoOpSelector.h @@ -3,23 +3,23 @@ //----------------------------------------------------------------------------- // eoOpSelector.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 - */ +/* + 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 EOOPSELECTOR_H diff --git a/eo/src/eoParser.h b/eo/src/eoParser.h index 0bfe70c06..df6ed49cc 100644 --- a/eo/src/eoParser.h +++ b/eo/src/eoParser.h @@ -1,790 +1,847 @@ -// -*- 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 - */ -//----------------------------------------------------------------------------- -/* eoParser.h - some classes to parser either the command line or a parameter file - - (c) geneura team, 1999 ------------------------------------------------------------------------------*/ - -#ifndef _PARSER_H -#define _PARSER_H - -// Standard C libraries -#include -#include -#include -#include -// STL includes -#include -#include -#include -#include -#include - -#include "UException.h" - -using namespace std; - - -//----------------------------------------------------------------------------- -// 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 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 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'; - return tmpStr; - } - - bool stop = false; - while (_is && !stop) { - _is >> paramValue; - // test last character of paramValue for " - if (paramValue[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: ,"<shortName()<<", ,"<environment().c_str())<> 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" --> 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 != ">") ) { // 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::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; - } - }; - - friend ostream & operator<< ( ostream & os, Parser & _parser ) - { - vector::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() == "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()<<" "<value(); - break; - - case Param::ARRAY : - os << p->longName() << " < " << p->value() << " >" ; - break; - case Param::STRING: - os << p->longName()<<" \""<value()<<"\" "; - break; - case Param::TITLE: - os << endl; // Title is in the description below - break; - } // switch - os << "\t # " << p->description() << " [" << p->defValue() << "]" << 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::iterator p; - unsigned i; - - // print program name and description - cout << this->programName <<":"<valType() != Param::TITLE ) { - if( p->valType() != Param::BOOL ){ - cout << ( (!p->required())?"[":""); - cout <shortName()<<" value"<required())?"]":"")<<" "; - }else{ - cout << "["<shortName()<<"] "; - } - } // for p - cout << endl<valType() != Param::TITLE ) { - cout << p->shortName()<<","<longName()<<":\t"<description()<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: "<defValue()< in array value - */ - class BadArrayParam : public UException { - public: - - /** - * Constructor - * @param _param The param - * @param _first_word The first word read after the "<" - */ - BadArrayParam(const string& _param, const string &_first_word) : - UException("Array parameter " + _param + ": No matching > (" + _first_word - + "... )") {}; - }; - -private: - vector params; - string programName; - string programDescription; - int parse_argc; - char **parse_argv; - string InputFileName; - -}; - -#endif +// -*- 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 // for strcasecmp ... maybe there's a c++ way of doing it? +#ifdef _MSC_VER +#define strcasecmp(a,b) _strnicmp(a,b,strlen(a)) +#endif + +// STL includes +#include +#include +#include +#include +#include +#include + +//----------------------------------------------------------------------------- +// Class UExceptions - probably useless ??? +//----------------------------------------------------------------------------- +/** + * This class manages exceptions. It´s barely an extension of the standard except +ion, + * but it can be initialized with an STL string. Called UException (utils-except +ion)+ + * to avoid conflicts with other classes. + */ +class UException: public exception { + public: + /// + UException( const string& _msg ): msg( _msg ) { }; + + /// + virtual const char* what() const { return msg.c_str(); }; + + private: + string msg; +}; + + +//----------------------------------------------------------------------------- +// 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 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 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'; + return tmpStr; + } + + bool stop = false; + while (_is && !stop) { + _is >> paramValue; + // test last character of paramValue for " + if (paramValue[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: ,"<shortName()<<", ,"<environment().c_str())<> 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" --> 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 != ">") ) { // 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::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::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() == "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()<<" "<value(); + break; + + case Param::ARRAY : + os << p->longName() << " < " << p->value().c_str() << " >" ; + break; + case Param::STRING: + os << p->longName()<<" \""<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::iterator p; +// unsigned i; + + // print program name and description + cout << this->programName <<": "<valType() != Param::TITLE ) { +// if( p->valType() != Param::BOOL ){ +// cout << ( (!p->required())?"[":""); +// cout <shortName()<<" value"<required())?"]":"")<<" "; +// }else{ +// cout << "["<shortName()<<"] "; +// } +// } // for p + cout << "Where:"<valType() != Param::TITLE ) { + cout << p->shortName()<<","<longName()<<":\t"<description()<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: "<defValue()<description() << endl; + } + } // for p + cout << endl; + }; + + /** + * This class managges unknown argument exceptions. + */ + class UnknownArg : public UException { + public: + + /** + * Constructor + * @param _arg string to be shown when the exception occurs + */ + UnknownArg( const string& _arg): UException( "Invalid argument: "+_arg ) { }; + }; + + /** + * This class managges bad param types. + */ + class BadType : public UException { + public: + + /** + * Constructor + * @param _param The param + * @param _value The value of the param + */ + BadType(const string& _param, const string& _value, const string& _correctType) + : UException("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 UException { + public: + + /** + * Constructor + * @param _param The param + */ + MissingVal(const string& _param) : UException("Missing value for parameter " + _param) {}; + }; + + /** + * This class managges exceptions produced when the user forgot a required parameter. + */ + class MissingReqParam : public UException { + public: + + /** + * Constructor + * @param _shortName The param's short name + */ + MissingReqParam(const string& _shortName) : UException("Missing required parameter " + _shortName) {}; + }; + + /** + * This class managges exceptions du to < without a > in array value + */ + class BadArrayParam : public UException { + public: + + /** + * Constructor + * @param _param The param + * @param _first_word The first word read after the "<" + */ + BadArrayParam(const string& _param, const string &_first_word) : + UException("Array parameter " + _param + ": No matching > (" + _first_word + + "... )") {}; + }; + +private: + vector params; + string programName; + string programDescription; + int parse_argc; + char **parse_argv; + string InputFileName; + +}; + +/// Reproducible random seed +// Maybe there is a better place for this subroutine (a separate .cpp?) +#include + +//---------------------------------- +void InitRandom( Parser & parser) { +//---------------------------------- + unsigned long _seed; + try { + _seed = parser.getUnsignedLong("-S", "--seed", "0", "Seed for Random number generator" ); + } + catch (UException & 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 + } + rng.reseed(_seed); + + return; +} + + +#endif diff --git a/eo/src/eoPersistent.cpp b/eo/src/eoPersistent.cpp index 174aee622..756353f5f 100644 --- a/eo/src/eoPersistent.cpp +++ b/eo/src/eoPersistent.cpp @@ -2,9 +2,9 @@ //Implementation of these objects -//----------------------------------------------------------------------------- - +//----------------------------------------------------------------------------- + istream & operator >> ( istream& _is, eoPersistent& _o ) { _o.readFrom(_is); return _is; -}; +}; diff --git a/eo/src/eoPersistent.h b/eo/src/eoPersistent.h index 1fe0acdf2..2902e732d 100644 --- a/eo/src/eoPersistent.h +++ b/eo/src/eoPersistent.h @@ -1,70 +1,70 @@ // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- -//----------------------------------------------------------------------------- +//----------------------------------------------------------------------------- // eoPersistent.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 EOPERSISTENT_H -#define EOPERSISTENT_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 EOPERSISTENT_H +#define EOPERSISTENT_H /// @name variables Some definitions of variables used throughout the program //@{ /// max length to store stuff read const unsigned MAXLINELENGTH=1024; //@} - -//----------------------------------------------------------------------------- - -#include // istream, ostream -#include // para string + +//----------------------------------------------------------------------------- + +#include // istream, ostream +#include // para string //----------------------------------------------------------------------------- #include using namespace std; - -//----------------------------------------------------------------------------- -// eoPersistent -//----------------------------------------------------------------------------- -/** + +//----------------------------------------------------------------------------- +// eoPersistent +//----------------------------------------------------------------------------- +/** An persistent object that knows how to write (through functions inherited from -#eoPrintable#) and read itself - */ -class eoPersistent: public eoPrintable -{ - public: - /// Virtual dtor. They are needed in virtual class hierarchies. - virtual ~eoPersistent() {} - - /** - * Read object. - * @param _is A istream. - * @throw runtime_exception If a valid object can't be read. - */ - virtual void readFrom(istream& _is) = 0; - -}; +#eoPrintable#) and read itself + */ +class eoPersistent: public eoPrintable +{ + public: + /// Virtual dtor. They are needed in virtual class hierarchies. + virtual ~eoPersistent() {} + + /** + * Read object. + * @param _is A istream. + * @throw runtime_exception If a valid object can't be read. + */ + virtual void readFrom(istream& _is) = 0; + +}; //----------------------------------------------------------------------------- ///Standard input for all objects in the EO hierarchy istream & operator >> ( istream& _is, eoPersistent& _o ); - -#endif EOOBJECT_H + +#endif EOOBJECT_H diff --git a/eo/src/eoPop.h b/eo/src/eoPop.h index bd1c3390b..89c5c2ff0 100644 --- a/eo/src/eoPop.h +++ b/eo/src/eoPop.h @@ -3,145 +3,145 @@ //----------------------------------------------------------------------------- // eoPop.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 - */ +/* + 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 _EOPOP_H -#define _EOPOP_H - -#include -#include - -using namespace std; -// from file - +#ifndef _EOPOP_H +#define _EOPOP_H + +#include +#include + +using namespace std; +// from file + #include -#include - -/** Subpopulation: it is used to move parts of population - from one algorithm to another and one population to another. It is safer -to declare it as a separate object. I have no idea if a population can be -some other thing that a vector, but if somebody thinks of it, this concrete -implementation will be moved to "generic" and an abstract Population -interface will be provided. -It can be instantiated with anything, provided that it accepts a "size" and a -random generator in the ctor. This happens to all the eo1d chromosomes declared -so far. EOT must also have a copy ctor, since temporaries are created and copied -to the population. -@author Geneura Team -@version 0.0 -*/ - -template -class eoPop: public vector, public eoObject, public eoPersistent { - -/// Type is the type of each gene in the chromosome -#ifdef _MSC_VER - typedef EOT::Type Type; -#else - typedef typename EOT::Type Type; -#endif - - public: - /** Protected ctor. This is intended to avoid creation of void populations, except - from sibling classes - */ - eoPop() - :vector() {}; - - - /** Ctor for fixed-size chromosomes, with variable content - @param _popSize total population size - @param _eoSize chromosome size. EOT should accept a fixed-size ctor - @param _geneRdn random number generator for each of the genes - */ - eoPop( unsigned _popSize, unsigned _eoSize, eoRnd & _geneRnd ) - :vector() { - for ( unsigned i = 0; i < _popSize; i ++ ){ - EOT tmpEOT( _eoSize, _geneRnd); - push_back( tmpEOT ); - } - }; - - /** Ctor for variable-size chromosomes, with variable content - @param _popSize total population size - @param _sizeRnd RNG for the chromosome size. This will be added 1, just in case. - @param _geneRdn random number generator for each of the genes - */ - eoPop( unsigned _popSize, eoRnd & _sizeRnd, eoRnd & _geneRnd ) - :vector() { - for ( unsigned i = 0; i < _popSize; i ++ ){ - unsigned size = 1 + _sizeRnd(); - EOT tmpEOT( size, _geneRnd); - push_back( tmpEOT ); - } - }; - - /** Ctor from an istream; reads the population from a stream, - each element should be in different lines - @param _is the stream - */ - eoPop( istream& _is ):vector() { - readFrom( _is ); - } - - /// - ~eoPop() {}; - +#include + +/** Subpopulation: it is used to move parts of population + from one algorithm to another and one population to another. It is safer +to declare it as a separate object. I have no idea if a population can be +some other thing that a vector, but if somebody thinks of it, this concrete +implementation will be moved to "generic" and an abstract Population +interface will be provided. +It can be instantiated with anything, provided that it accepts a "size" and a +random generator in the ctor. This happens to all the eo1d chromosomes declared +so far. EOT must also have a copy ctor, since temporaries are created and copied +to the population. +@author Geneura Team +@version 0.0 +*/ + +template +class eoPop: public vector, public eoObject, public eoPersistent { + +/// Type is the type of each gene in the chromosome +#ifdef _MSC_VER + typedef EOT::Type Type; +#else + typedef typename EOT::Type Type; +#endif + + public: + /** Protected ctor. This is intended to avoid creation of void populations, except + from sibling classes + */ + eoPop() + :vector() {}; + + + /** Ctor for fixed-size chromosomes, with variable content + @param _popSize total population size + @param _eoSize chromosome size. EOT should accept a fixed-size ctor + @param _geneRdn random number generator for each of the genes + */ + eoPop( unsigned _popSize, unsigned _eoSize, eoRnd & _geneRnd ) + :vector() { + for ( unsigned i = 0; i < _popSize; i ++ ){ + EOT tmpEOT( _eoSize, _geneRnd); + push_back( tmpEOT ); + } + }; + + /** Ctor for variable-size chromosomes, with variable content + @param _popSize total population size + @param _sizeRnd RNG for the chromosome size. This will be added 1, just in case. + @param _geneRdn random number generator for each of the genes + */ + eoPop( unsigned _popSize, eoRnd & _sizeRnd, eoRnd & _geneRnd ) + :vector() { + for ( unsigned i = 0; i < _popSize; i ++ ){ + unsigned size = 1 + _sizeRnd(); + EOT tmpEOT( size, _geneRnd); + push_back( tmpEOT ); + } + }; + + /** Ctor from an istream; reads the population from a stream, + each element should be in different lines + @param _is the stream + */ + eoPop( istream& _is ):vector() { + readFrom( _is ); + } + + /// + ~eoPop() {}; + /** @name Methods from eoObject */ //@{ /** - * Read object. The EOT class must have a ctor from a stream; - in this case, a strstream is used. + * Read object. The EOT class must have a ctor from a stream; + in this case, a strstream is used. * @param _is A istream. - + */ virtual void readFrom(istream& _is) { - while( _is ) { // reads line by line, and creates an object per - // line - char line[MAXLINELENGTH]; + while( _is ) { // reads line by line, and creates an object per + // line + char line[MAXLINELENGTH]; _is.getline( line, MAXLINELENGTH-1 ); - if (strlen( line ) ) { - istrstream s( line ); - EOT thisEOT( s ); + if (strlen( line ) ) { + istrstream s( line ); + EOT thisEOT( s ); push_back( thisEOT ); - } - } - } - + } + } + } + /** * Write object. It's called printOn since it prints the object _on_ a stream. - * @param _os A ostream. In this case, prints the population to - standard output. The EOT class must hav standard output with cout, - but since it should be an eoObject anyways, it's no big deal. + * @param _os A ostream. In this case, prints the population to + standard output. The EOT class must hav standard output with cout, + but since it should be an eoObject anyways, it's no big deal. */ virtual void printOn(ostream& _os) const { - copy( begin(), end(), ostream_iterator( _os, "\n") ); + copy( begin(), end(), ostream_iterator( _os, "\n") ); }; - /** Inherited from eoObject. Returns the class name. + /** Inherited from eoObject. Returns the class name. @see eoObject */ - string className() const {return "eoPop";}; + virtual string className() const {return "eoPop";}; //@} - - protected: - -}; -#endif + + protected: + +}; +#endif diff --git a/eo/src/eoPopOps.h b/eo/src/eoPopOps.h index 7f39c2100..8e8177497 100644 --- a/eo/src/eoPopOps.h +++ b/eo/src/eoPopOps.h @@ -1,143 +1,143 @@ -// eoPopOps.h -// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - -//----------------------------------------------------------------------------- -// eo1d.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 _EOPOPOPS_H -#define _EOPOPOPS_H - -using namespace std; - -/** -@author Geneura Team -@version 0.0 -*/ - -//----------------------------------------------------------------------------- -#include - -//----------------------------------------------------------------------------- -/** eoTransform is a class that transforms or does something on a population. - */ -template -class eoTransform: public eoObject{ - - public: - /** ctor */ - eoTransform() {}; - - /// Dtor - virtual ~eoTransform(){}; - - /// Pure virtual transformation function. Does something on the population - virtual void operator () ( eoPop& _pop ) = 0; - - /** @name Methods from eoObject */ - //@{ - /** readFrom and printOn are not overriden - */ - /** Inherited from eoObject. Returns the class name. - @see eoObject - */ - string className() const {return "eoTransform";}; - //@} - -}; - -//----------------------------------------------------------------------------- - -/** eoSelect usually takes elements from one population, with or without transformation, and transfers them to the other population */ -template -class eoSelect: public eoObject{ - - public: - /** ctor - */ - eoSelect() {}; - - /// Dtor - virtual ~eoSelect(){}; - - /** Pure virtual transformation function. Extracts something from the parents, - and transfers it to the siblings - @param _parents the initial generation. Will be kept constant - @param _siblings the created offspring. Will be usually an empty population - */ - virtual void operator () ( const eoPop& _parents, eoPop& _siblings ) const = 0; - - /** @name Methods from eoObject */ - //@{ - /** readFrom and printOn are not overriden - */ - /** Inherited from eoObject. Returns the class name. - @see eoObject - */ - string className() const {return "eoSelect";}; - //@} - -}; - -/** eoMerge involves three populations, that can be merged and transformed to -give a third -*/ -template -class eoMerge: public eoObject{ - - public: - /// (Default) Constructor. - eoMerge(const float& _rate = 1.0): rep_rate(_rate) {} - - /// Dtor - virtual ~eoMerge() {} - - /** Pure virtual transformation function. Extracts something from breeders - * and transfers it to the pop - * @param breeders Tranformed individuals. - * @param pop The original population at the begining, the result at the end - */ - virtual void operator () ( eoPop& breeders, eoPop& pop ) = 0; - - /** @name Methods from eoObject */ - //@{ - /** readFrom and printOn are not overriden - */ - /** Inherited from eoObject. Returns the class name. - @see eoObject - */ - string className() const {return "eoMerge";}; - //@} - - /// Return the rate to be selected from the original population - float rate() const { return rep_rate; } - - /// Set the rate to be obtained after replacement. - /// @param _rate The rate. - void rate(const float& _rate) { rep_rate = _rate; } - - private: - float rep_rate; -}; - -//----------------------------------------------------------------------------- - -#endif +// eoPopOps.h +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eo1d.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 _EOPOPOPS_H +#define _EOPOPOPS_H + +using namespace std; + +/** +@author Geneura Team +@version 0.0 +*/ + +//----------------------------------------------------------------------------- +#include + +//----------------------------------------------------------------------------- +/** eoTransform is a class that transforms or does something on a population. + */ +template +class eoTransform: public eoObject{ + + public: + /** ctor */ + eoTransform() {}; + + /// Dtor + virtual ~eoTransform(){}; + + /// Pure virtual transformation function. Does something on the population + virtual void operator () ( eoPop& _pop ) = 0; + + /** @name Methods from eoObject */ + //@{ + /** readFrom and printOn are not overriden + */ + /** Inherited from eoObject. Returns the class name. + @see eoObject + */ + virtual string className() const {return "eoTransform";}; + //@} + +}; + +//----------------------------------------------------------------------------- + +/** eoSelect usually takes elements from one population, with or without transformation, and transfers them to the other population */ +template +class eoSelect: public eoObject{ + + public: + /** ctor + */ + eoSelect() {}; + + /// Dtor + virtual ~eoSelect(){}; + + /** Pure virtual transformation function. Extracts something from the parents, + and transfers it to the siblings + @param _parents the initial generation. Will be kept constant + @param _siblings the created offspring. Will be usually an empty population + */ + virtual void operator () ( const eoPop& _parents, eoPop& _siblings ) const = 0; + + /** @name Methods from eoObject */ + //@{ + /** readFrom and printOn are not overriden + */ + /** Inherited from eoObject. Returns the class name. + @see eoObject + */ + virtual string className() const {return "eoSelect";}; + //@} + +}; + +/** eoMerge involves three populations, that can be merged and transformed to +give a third +*/ +template +class eoMerge: public eoObject{ + + public: + /// (Default) Constructor. + eoMerge(const float& _rate = 1.0): rep_rate(_rate) {} + + /// Dtor + virtual ~eoMerge() {} + + /** Pure virtual transformation function. Extracts something from breeders + * and transfers it to the pop + * @param breeders Tranformed individuals. + * @param pop The original population at the begining, the result at the end + */ + virtual void operator () ( eoPop& breeders, eoPop& pop ) = 0; + + /** @name Methods from eoObject */ + //@{ + /** readFrom and printOn are not overriden + */ + /** Inherited from eoObject. Returns the class name. + @see eoObject + */ + virtual string className() const {return "eoMerge";}; + //@} + + /// Return the rate to be selected from the original population + float rate() const { return rep_rate; } + + /// Set the rate to be obtained after replacement. + /// @param _rate The rate. + void rate(const float& _rate) { rep_rate = _rate; } + + private: + float rep_rate; +}; + +//----------------------------------------------------------------------------- + +#endif diff --git a/eo/src/eoPrintable.h b/eo/src/eoPrintable.h index dc761ebf6..9757d36c3 100644 --- a/eo/src/eoPrintable.h +++ b/eo/src/eoPrintable.h @@ -1,62 +1,62 @@ // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- -//----------------------------------------------------------------------------- +//----------------------------------------------------------------------------- // eoPrintable.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 EOPRINTABLE_H -#define EOPRINTABLE_H - -//----------------------------------------------------------------------------- - -#include // istream, ostream -#include // para string +// (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 EOPRINTABLE_H +#define EOPRINTABLE_H + +//----------------------------------------------------------------------------- + +#include // istream, ostream +#include // para string using namespace std; - -//----------------------------------------------------------------------------- -// eoPrintable -//----------------------------------------------------------------------------- -/** -Base class for objects that can print themselves + +//----------------------------------------------------------------------------- +// eoPrintable +//----------------------------------------------------------------------------- +/** +Base class for objects that can print themselves (#printOn#). Besides, this file defines the standard output for all the objects; if the objects define printOn there's no need to define #operator <<#.\\ This functionality was separated from eoObject, since it makes no sense to print -some objects (for instance, a #eoFactory# or a random number generator. - */ -class eoPrintable -{ - public: - /// Virtual dtor. They are needed in virtual class hierarchies. - virtual ~eoPrintable() {} - - /** - * Write object. It's called printOn since it prints the object on a stream. - * @param _os A ostream. - */ - virtual void printOn(ostream& _os) const = 0; -}; - -//----------------------------------------------------------------------------- -///Standard output for all objects in the EO hierarchy -ostream & operator << ( ostream& _os, const eoPrintable& _o ); - -#endif EOPRINTABLE_H +some objects (for instance, a #eoFactory# or a random number generator. + */ +class eoPrintable +{ + public: + /// Virtual dtor. They are needed in virtual class hierarchies. + virtual ~eoPrintable() {} + + /** + * Write object. It's called printOn since it prints the object on a stream. + * @param _os A ostream. + */ + virtual void printOn(ostream& _os) const = 0; +}; + +//----------------------------------------------------------------------------- +///Standard output for all objects in the EO hierarchy +ostream & operator << ( ostream& _os, const eoPrintable& _o ); + +#endif EOPRINTABLE_H diff --git a/eo/src/eoProblem.h b/eo/src/eoProblem.h index c8ab40449..892a14e48 100644 --- a/eo/src/eoProblem.h +++ b/eo/src/eoProblem.h @@ -1,40 +1,40 @@ -//----------------------------------------------------------------------------- -// 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 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 +//----------------------------------------------------------------------------- +// 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 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 diff --git a/eo/src/eoProportionalOpSel.h b/eo/src/eoProportionalOpSel.h index 0e4d93add..d34fa47d6 100644 --- a/eo/src/eoProportionalOpSel.h +++ b/eo/src/eoProportionalOpSel.h @@ -3,23 +3,23 @@ //----------------------------------------------------------------------------- // eoProportionalOpSel.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 - */ +/* + 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 EOPROPORTIONALOPSEL_H @@ -90,6 +90,7 @@ public: for ( i=begin(), j=1; i!=end(); i++,j++ ) { if( j == _id ) erase( i ); + return; } if ( i == end() ) throw runtime_error( "No such id in eoProportionalOpSel::op\n" ); diff --git a/eo/src/eoRNG.h b/eo/src/eoRNG.h index 4233f8e4a..e5998f365 100644 --- a/eo/src/eoRNG.h +++ b/eo/src/eoRNG.h @@ -1,446 +1,449 @@ -/* -* 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 -// (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 with -// an appropriate reference to your work. -// -// It would be nice to CC: 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 -#include - -// 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 seed not unintentionally defaulted at 42. - */ - eoRng(uint32 s = 42U) : state(0), next(0), left(-1), cached(false) - { - 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 - int roulette_wheel(const std::vector& vec, T total = 0) - { - if (total == 0) - { // count - for (int 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; - - static const int N; - static const int M; - static const uint32 K; // a magic constant - -}; - -// Initialization of statics -const int eoRng::N = 624; -const int eoRng::M = 397; -const uint32 eoRng::K = (0x9908B0DFU); // a magic constant - -/** - The one and only global eoRng object -*/ -static 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 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 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 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 +/* +* 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 +// (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 with +// an appropriate reference to your work. +// +// It would be nice to CC: 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 + +#include +#include + +// 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) + { + 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 + int roulette_wheel(const std::vector& vec, T total = 0) + { + if (total == 0) + { // count + for (int 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; + + static const int N; + static const int M; + static const uint32 K; // a magic constant + +}; + +// Initialization of statics +const int eoRng::N = 624; +const int eoRng::M = 397; +const uint32 eoRng::K = (0x9908B0DFU); // a magic constant + +/** + The one and only global eoRng object +*/ +static 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 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 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 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 diff --git a/eo/src/eoRnd.h b/eo/src/eoRnd.h index 84a4a66a9..76e40324e 100644 --- a/eo/src/eoRnd.h +++ b/eo/src/eoRnd.h @@ -1,99 +1,99 @@ -// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - -//----------------------------------------------------------------------------- -// eoRnd.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 _EORND_H -#define _EORND_H - -//----------------------------------------------------------------------------- - -#include - -//----------------------------------------------------------------------------- -// Class eoRnd -//----------------------------------------------------------------------------- - -#include // srand -#include // time -#include // runtime_error +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoRnd.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 _EORND_H +#define _EORND_H + +//----------------------------------------------------------------------------- + +#include + +//----------------------------------------------------------------------------- +// Class eoRnd +//----------------------------------------------------------------------------- + +#include // srand +#include // time +#include // runtime_error //----------------------------------------------------------------------------- #include -//----------------------------------------------------------------------------- -/** - * Base class for a family of random number generators. Generates numbers - * according to the parameters given in the constructor. Uses the machine's - * own random number generators. Which is not too good, after all. - */ -template -class eoRnd: public eoObject, public eoPersistent -{ -public: - - /// default constructor +//----------------------------------------------------------------------------- +/** + * Base class for a family of random number generators. Generates numbers + * according to the parameters given in the constructor. Uses the machine's + * own random number generators. Which is not too good, after all. + */ +template +class eoRnd: public eoObject, public eoPersistent +{ +public: + + /// default constructor eoRnd(unsigned _seed = 0) { if ( !started ) { srand(_seed?_seed:time(0)); started = true; } - } - - /// Copy cotor - eoRnd(const eoRnd& _r ) {srand(time(0));}; - + } + + /// Copy cotor + eoRnd(const eoRnd& _r ) {srand(time(0));}; + /** Main function: random generators act as functors, that return random numbers. It´s non-const because it might modify a seed @return return a random number - */ - virtual T operator()() = 0; - + */ + virtual T operator()() = 0; + /** Return the class id. - @return the class name as a string - */ - virtual string className() const { return "eoRandom"; }; - - /** - * Read object. - * @param is A istream. - * @throw runtime_exception If a valid object can't be read. - */ - virtual void readFrom(istream& _is); - - /** - * print object. Prints just the ID, since the seed is not accesible. - * @param is A ostream. - */ + @return the class name as a string + */ + virtual string className() const { return "eoRandom"; }; + + /** + * Read object. + * @param is A istream. + * @throw runtime_exception If a valid object can't be read. + */ + virtual void readFrom(istream& _is); + + /** + * print object. Prints just the ID, since the seed is not accesible. + * @param is A ostream. + */ void printOn(ostream& _os) const { _os << endl; }; private: /// true if the RNG has been started already. If it starts every time, means trouble. - static bool started; + static bool started; }; -template bool eoRnd::started = false; - +template bool eoRnd::started = false; + //-------------------------------------------------------------------------- @@ -110,5 +110,5 @@ void eoRnd::readFrom(istream& _is) { _is >> seed; srand(seed); } - -#endif + +#endif diff --git a/eo/src/eoString.h b/eo/src/eoString.h index f2e60f451..548d4c354 100644 --- a/eo/src/eoString.h +++ b/eo/src/eoString.h @@ -3,23 +3,23 @@ //----------------------------------------------------------------------------- // 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 - */ +/* + 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 @@ -83,7 +83,7 @@ public: /** methods that implement the eo1d protocol @exception out_of_range if _i is larger than EO´s size */ - virtual char gene( unsigned _i ) const { + virtual char getGene( unsigned _i ) const { if ( _i >= length() ) throw out_of_range( "out_of_range when reading gene"); return (*this)[_i]; @@ -92,10 +92,10 @@ public: /** methods that implement the eo1d protocol @exception out_of_range if _i is larger than EO´s size */ - virtual char& gene( unsigned _i ) { + virtual void setGene( unsigned _i, const char& _value ) { if ( _i >= size() ) throw out_of_range( "out_of_range when writing a gene"); - return (*this)[_i]; + (*this)[_i] = _value; }; /** Inserts a value after _i, displacing anything to the right @@ -130,7 +130,7 @@ public: /** Inherited from eoObject @see eoObject */ - string className() const {return "eoString";}; + virtual string className() const {return "eoString";}; //@} diff --git a/eo/src/eoStringMutation.h b/eo/src/eoStringMutation.h new file mode 100644 index 000000000..5cebc8ebc --- /dev/null +++ b/eo/src/eoStringMutation.h @@ -0,0 +1,78 @@ +// -*- 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 +// EO includes +#include +#include +#include + +/** Mutation of an eoString. + The eoString's genes are changed by adding or substracting 1 to +*/ + +template +class eoStringMutation: public eoMutation { + 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 uniform( 0, 1 ); + if( rate < uniform() ) { + _eo.gene(_i) += ( uniform()>=0.5 )? (1) : (-1) ; + } + } + +}; + +//----------------------------------------------------------------------------- + +#endif diff --git a/eo/src/eoTranspose.h b/eo/src/eoTranspose.h index 2987fca0a..a46b8328b 100644 --- a/eo/src/eoTranspose.h +++ b/eo/src/eoTranspose.h @@ -3,23 +3,23 @@ //----------------------------------------------------------------------------- // eoTranspose.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 - */ +/* + 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 _EOTRANSPOSE_h diff --git a/eo/src/eoUniform.h b/eo/src/eoUniform.h index fd9946bd5..b825d9ab1 100644 --- a/eo/src/eoUniform.h +++ b/eo/src/eoUniform.h @@ -1,71 +1,71 @@ -// eoUniform.h -// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - -//----------------------------------------------------------------------------- -// EOUniform.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 _EOUNIFORM_H -#define _EOUNIFORM_H - -//----------------------------------------------------------------------------- - -#include -#include - -//----------------------------------------------------------------------------- -// Class eoUniform -//----------------------------------------------------------------------------- - -/// Generates uniform random number over the interval [min, max) -template -class eoUniform: public eoRnd -{ - public: - /** - * Default constructor. - * @param _min The minimum value in the interval. - * @param _max The maximum value in the interval. - */ - eoUniform(T _min = 0, T _max = 1) - : eoRnd(), min(_min), diff(_max - _min) {} - - /** - * copy constructor. - * @param _rnd the other rnd - */ - eoUniform( const eoUniform& _rnd) - : eoRnd( _rnd), min(_rnd.minim), diff(_rnd.diff) {} - - /** Returns an uniform random number over the interval [min, max) - Uses global rng object */ - virtual T operator()() { - return min + T( rng.uniform( diff ) ); - } - - private: - T min; - double diff; -}; - -//----------------------------------------------------------------------------- - -#endif +// eoUniform.h +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// EOUniform.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 _EOUNIFORM_H +#define _EOUNIFORM_H + +//----------------------------------------------------------------------------- + +#include +#include + +//----------------------------------------------------------------------------- +// Class eoUniform +//----------------------------------------------------------------------------- + +/// Generates uniform random number over the interval [min, max) +template +class eoUniform: public eoRnd +{ + public: + /** + * Default constructor. + * @param _min The minimum value in the interval. + * @param _max The maximum value in the interval. + */ + eoUniform(T _min = 0, T _max = 1) + : eoRnd(), min(_min), diff(_max - _min) {} + + /** + * copy constructor. + * @param _rnd the other rnd + */ + eoUniform( const eoUniform& _rnd) + : eoRnd( _rnd), min(_rnd.minim), diff(_rnd.diff) {} + + /** Returns an uniform random number over the interval [min, max) + Uses global rng object */ + virtual T operator()() { + return min + T( rng.uniform( diff ) ); + } + + private: + T min; + double diff; +}; + +//----------------------------------------------------------------------------- + +#endif diff --git a/eo/src/eoVector.h b/eo/src/eoVector.h index f116608c7..4a0a7e6f7 100644 --- a/eo/src/eoVector.h +++ b/eo/src/eoVector.h @@ -1,169 +1,169 @@ -// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - -//----------------------------------------------------------------------------- -// eoVector.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 _eoVector_H -#define _eoVector_H - -// STL libraries -#include // For vector -#include -#include - -#include -#include - -/** Adaptor that turns an STL vector into an EO - with the same gene type as the type with which - the vector has been instantiated -*/ -template -class eoVector: public eo1d, public vector { -public: - typedef T Type ; - - /// Canonical part of the objects: several ctors, copy ctor, dtor and assignment operator - //@{ - - /** Ctor. - @param _size Lineal length of the object - @param _val Common initial value - */ - eoVector( unsigned _size = 0, T _val = 0) - : eo1d(), vector( _size, _val ){ }; - - /** 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 - */ - eoVector( unsigned _size, eoRnd& _rnd ); - - /** Ctor from a istream. The T class should accept reading from a istream. It doesn't read fitness, -which is supposed to be dynamic and dependent on environment. - @param _is the input stream; should have all values in a single line, separated by whitespace - */ - eoVector( istream& _is); - - - /// copy ctor - eoVector( const eoVector & _eo ) - : eo1d( _eo ), vector( _eo ){ }; - - /// Assignment operator - const eoVector& operator =( const eoVector & _eo ) { - if ( this != &_eo ){ - eo1d::operator=( _eo ); - vector::operator=( _eo ); - } - return *this; - } - - /// dtor - virtual ~eoVector() {}; - - //@} - - /** methods that implement the eo1d protocol - @exception out_of_range if _i is larger than EO´s size - */ - virtual T 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 protocol - @exception out_of_range if _i is larger than EO´s size - */ - virtual void setGene( unsigned _i, const T& _value ) { - if ( _i >= size() ) - throw out_of_range( "out_of_range when writing a gene"); - (*this)[_i] = _value; - }; - - /** methods that implement the eo1d protocol - @exception out_of_range if _i is larger than EO´s size - */ - virtual void insertGene( unsigned _i, T _val ) { - if (_i <= size() ) { - vector::iterator i = begin()+_i; - insert( i, _val ); - } else { - throw out_of_range( "out_of_range when inserting a 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() ) { - vector::iterator i = this->begin()+_i; - this->erase( i ); - } else { - throw out_of_range( "out_of_range when deleting a gene"); - }; - }; - - /// methods that implement the EO protocol - virtual unsigned length() const { return this->size(); }; - - /** @name Methods from eoObject - readFrom and printOn are directly inherited from eo1d - */ - //@{ - /** Inherited from eoObject - @see eoObject - */ - string className() const {return "eoVector";}; - //@} - -}; - - -//____________________________ Some method implementation _______________________ - -// Ctors______________________________________________________________________________ -//____________________________________________________________________________________ -template -eoVector::eoVector( unsigned _size, eoRnd& _rnd ) - : eo1d(), vector( _size ){ - for ( iterator i = begin(); i != end(); i ++ ) { - *i = _rnd(); - } -}; - -//____________________________________________________________________________________ -template -eoVector::eoVector( istream& _is) - : eo1d(), vector( ){ - while (_is ) { - T tmp; - _is >> tmp; - push_back( tmp ); - } - -}; - -#endif +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoVector.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 _eoVector_H +#define _eoVector_H + +// STL libraries +#include // For vector +#include +#include + +#include +#include + +/** Adaptor that turns an STL vector into an EO + with the same gene type as the type with which + the vector has been instantiated +*/ +template +class eoVector: public eo1d, public vector { +public: + typedef T Type ; + + /// Canonical part of the objects: several ctors, copy ctor, dtor and assignment operator + //@{ + + /** Ctor. + @param _size Lineal length of the object + @param _val Common initial value + */ + eoVector( unsigned _size = 0, T _val = 0) + : eo1d(), vector( _size, _val ){ }; + + /** 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 + */ + eoVector( unsigned _size, eoRnd& _rnd ); + + /** Ctor from a istream. The T class should accept reading from a istream. It doesn't read fitness, +which is supposed to be dynamic and dependent on environment. + @param _is the input stream; should have all values in a single line, separated by whitespace + */ + eoVector( istream& _is); + + + /// copy ctor + eoVector( const eoVector & _eo ) + : eo1d( _eo ), vector( _eo ){ }; + + /// Assignment operator + const eoVector& operator =( const eoVector & _eo ) { + if ( this != &_eo ){ + eo1d::operator=( _eo ); + vector::operator=( _eo ); + } + return *this; + } + + /// dtor + virtual ~eoVector() {}; + + //@} + + /** methods that implement the eo1d protocol + @exception out_of_range if _i is larger than EO´s size + */ + virtual T 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 protocol + @exception out_of_range if _i is larger than EO´s size + */ + virtual void setGene( unsigned _i, const T& _value ) { + if ( _i >= size() ) + throw out_of_range( "out_of_range when writing a gene"); + (*this)[_i] = _value; + }; + + /** methods that implement the eo1d protocol + @exception out_of_range if _i is larger than EO´s size + */ + virtual void insertGene( unsigned _i, T _val ) { + if (_i <= size() ) { + vector::iterator i = begin()+_i; + insert( i, _val ); + } else { + throw out_of_range( "out_of_range when inserting a 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() ) { + vector::iterator i = this->begin()+_i; + this->erase( i ); + } else { + throw out_of_range( "out_of_range when deleting a gene"); + }; + }; + + /// methods that implement the EO protocol + virtual unsigned length() const { return this->size(); }; + + /** @name Methods from eoObject + readFrom and printOn are directly inherited from eo1d + */ + //@{ + /** Inherited from eoObject + @see eoObject + */ + string className() const {return "eoVector";}; + //@} + +}; + + +//____________________________ Some method implementation _______________________ + +// Ctors______________________________________________________________________________ +//____________________________________________________________________________________ +template +eoVector::eoVector( unsigned _size, eoRnd& _rnd ) + : eo1d(), vector( _size ){ + for ( iterator i = begin(); i != end(); i ++ ) { + *i = _rnd(); + } +}; + +//____________________________________________________________________________________ +template +eoVector::eoVector( istream& _is) + : eo1d(), vector( ){ + while (_is ) { + T tmp; + _is >> tmp; + push_back( tmp ); + } + +}; + +#endif diff --git a/eo/src/eoXOver2.h b/eo/src/eoXOver2.h index 9361f91ec..ddb6c41cb 100644 --- a/eo/src/eoXOver2.h +++ b/eo/src/eoXOver2.h @@ -3,23 +3,23 @@ //----------------------------------------------------------------------------- // eoXOver2.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 - */ +/* + 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 _EOXOVER2_h @@ -103,4 +103,4 @@ private: }; -#endif +#endif diff --git a/eo/test/Makefile.am b/eo/test/Makefile.am index 3833080a7..b83574807 100644 --- a/eo/test/Makefile.am +++ b/eo/test/Makefile.am @@ -13,7 +13,28 @@ LDADDS = $(top_builddir)/src/libeo.a ############################################################################### -noinst_PROGRAMS = t-eobreeder t-eoinclusion t-eoinsertion t-eo t-eofitness t-eoproblem t-eobin t-eolottery t-eo2dVector t-eogeneration t-eoEasyEA t-eoNonUniform t-eoUniform t-eoRandom t-parser +noinst_PROGRAMS = t-eobreeder t-eoinclusion t-eoinsertion t-eo t-eofitness t-eoproblem t-eobin t-eolottery t-eo2dVector t-eogeneration t-eoEasyEA t-eoNonUniform t-eoUniform t-eoRandom t-parser t-eoESFull t-eoESOps t-eoAtomOps + +############################################################################### + +t_eoAtomOps_SOURCES = t-eoAtomOps.cpp +t_eoAtomOps_DEPENDENCIES = $(DEPS) +t_eoAtomOps_LDFLAGS = -lm +t_eoAtomOps_LDADD = $(LDADDS) + +############################################################################### + +t_eoESOps_SOURCES = t-eoESOps.cpp +t_eoESOps_DEPENDENCIES = $(DEPS) +t_eoESOps_LDFLAGS = -lm +t_eoESOps_LDADD = $(LDADDS) + +############################################################################### + +t_eoESFull_SOURCES = t-eoESFull.cpp real_value.h +t_eoESFull_DEPENDENCIES = $(DEPS) +t_eoESFull_LDFLAGS = -lm +t_eoESFull_LDADD = $(LDADDS) ############################################################################### diff --git a/eo/test/Makefile.in b/eo/test/Makefile.in index 44669bf6b..67ed6e7d8 100644 --- a/eo/test/Makefile.in +++ b/eo/test/Makefile.in @@ -1,4 +1,4 @@ -# Makefile.in generated automatically by automake 1.4 from Makefile.am +# Makefile.in generated automatically by automake 1.4a from Makefile.am # Copyright (C) 1994, 1995-8, 1999 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation @@ -49,9 +49,10 @@ AUTOMAKE = @AUTOMAKE@ AUTOHEADER = @AUTOHEADER@ INSTALL = @INSTALL@ -INSTALL_PROGRAM = @INSTALL_PROGRAM@ $(AM_INSTALL_PROGRAM_FLAGS) +INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_FLAG = transform = @program_transform_name@ NORMAL_INSTALL = : @@ -86,7 +87,28 @@ LDADDS = $(top_builddir)/src/libeo.a ############################################################################### -noinst_PROGRAMS = t-eobreeder t-eoinclusion t-eoinsertion t-eo t-eofitness t-eoproblem t-eobin t-eolottery t-eo2dVector t-eogeneration t-eoEasyEA t-eoNonUniform t-eoUniform t-eoRandom t-parser +noinst_PROGRAMS = t-eobreeder t-eoinclusion t-eoinsertion t-eo t-eofitness t-eoproblem t-eobin t-eolottery t-eo2dVector t-eogeneration t-eoEasyEA t-eoNonUniform t-eoUniform t-eoRandom t-parser t-eoESFull t-eoESOps t-eoAtomOps + +############################################################################### + +t_eoAtomOps_SOURCES = t-eoAtomOps.cpp +t_eoAtomOps_DEPENDENCIES = $(DEPS) +t_eoAtomOps_LDFLAGS = -lm +t_eoAtomOps_LDADD = $(LDADDS) + +############################################################################### + +t_eoESOps_SOURCES = t-eoESOps.cpp +t_eoESOps_DEPENDENCIES = $(DEPS) +t_eoESOps_LDFLAGS = -lm +t_eoESOps_LDADD = $(LDADDS) + +############################################################################### + +t_eoESFull_SOURCES = t-eoESFull.cpp real_value.h +t_eoESFull_DEPENDENCIES = $(DEPS) +t_eoESFull_LDFLAGS = -lm +t_eoESFull_LDADD = $(LDADDS) ############################################################################### @@ -216,6 +238,9 @@ t_eoNonUniform_OBJECTS = t-eoNonUniform.o t_eoUniform_OBJECTS = t-eoUniform.o t_eoRandom_OBJECTS = t-eoRandom.o t_parser_OBJECTS = t-parser.o +t_eoESFull_OBJECTS = t-eoESFull.o +t_eoESOps_OBJECTS = t-eoESOps.o +t_eoAtomOps_OBJECTS = t-eoAtomOps.o CXXFLAGS = @CXXFLAGS@ CXXCOMPILE = $(CXX) $(DEFS) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) LTCXXCOMPILE = $(LIBTOOL) --mode=compile $(CXX) $(DEFS) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) @@ -233,21 +258,16 @@ DISTFILES = $(DIST_COMMON) $(SOURCES) $(HEADERS) $(TEXINFOS) $(EXTRA_DIST) TAR = gtar GZIP_ENV = --best -DEP_FILES = .deps/t-eo.P .deps/t-eo2dVector.P .deps/t-eoEasyEA.P \ -.deps/t-eoNonUniform.P .deps/t-eoRandom.P .deps/t-eoUniform.P \ -.deps/t-eobin.P .deps/t-eobreeder.P .deps/t-eofitness.P \ -.deps/t-eogeneration.P .deps/t-eoinclusion.P .deps/t-eoinsertion.P \ -.deps/t-eolottery.P .deps/t-eoproblem.P .deps/t-parser.P -SOURCES = $(t_eobreeder_SOURCES) $(t_eoinclusion_SOURCES) $(t_eoinsertion_SOURCES) $(t_eo_SOURCES) $(t_eofitness_SOURCES) $(t_eoproblem_SOURCES) $(t_eobin_SOURCES) $(t_eolottery_SOURCES) $(t_eo2dVector_SOURCES) $(t_eogeneration_SOURCES) $(t_eoEasyEA_SOURCES) $(t_eoNonUniform_SOURCES) $(t_eoUniform_SOURCES) $(t_eoRandom_SOURCES) $(t_parser_SOURCES) -OBJECTS = $(t_eobreeder_OBJECTS) $(t_eoinclusion_OBJECTS) $(t_eoinsertion_OBJECTS) $(t_eo_OBJECTS) $(t_eofitness_OBJECTS) $(t_eoproblem_OBJECTS) $(t_eobin_OBJECTS) $(t_eolottery_OBJECTS) $(t_eo2dVector_OBJECTS) $(t_eogeneration_OBJECTS) $(t_eoEasyEA_OBJECTS) $(t_eoNonUniform_OBJECTS) $(t_eoUniform_OBJECTS) $(t_eoRandom_OBJECTS) $(t_parser_OBJECTS) +SOURCES = $(t_eobreeder_SOURCES) $(t_eoinclusion_SOURCES) $(t_eoinsertion_SOURCES) $(t_eo_SOURCES) $(t_eofitness_SOURCES) $(t_eoproblem_SOURCES) $(t_eobin_SOURCES) $(t_eolottery_SOURCES) $(t_eo2dVector_SOURCES) $(t_eogeneration_SOURCES) $(t_eoEasyEA_SOURCES) $(t_eoNonUniform_SOURCES) $(t_eoUniform_SOURCES) $(t_eoRandom_SOURCES) $(t_parser_SOURCES) $(t_eoESFull_SOURCES) $(t_eoESOps_SOURCES) $(t_eoAtomOps_SOURCES) +OBJECTS = $(t_eobreeder_OBJECTS) $(t_eoinclusion_OBJECTS) $(t_eoinsertion_OBJECTS) $(t_eo_OBJECTS) $(t_eofitness_OBJECTS) $(t_eoproblem_OBJECTS) $(t_eobin_OBJECTS) $(t_eolottery_OBJECTS) $(t_eo2dVector_OBJECTS) $(t_eogeneration_OBJECTS) $(t_eoEasyEA_OBJECTS) $(t_eoNonUniform_OBJECTS) $(t_eoUniform_OBJECTS) $(t_eoRandom_OBJECTS) $(t_parser_OBJECTS) $(t_eoESFull_OBJECTS) $(t_eoESOps_OBJECTS) $(t_eoAtomOps_OBJECTS) all: all-redirect .SUFFIXES: .SUFFIXES: .S .c .cc .cpp .lo .o .s $(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ Makefile.am $(top_srcdir)/configure.in $(ACLOCAL_M4) - cd $(top_srcdir) && $(AUTOMAKE) --gnu test/Makefile + cd $(top_srcdir) && $(AUTOMAKE) --gnu --include-deps test/Makefile -Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status $(BUILT_SOURCES) +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status cd $(top_builddir) \ && CONFIG_FILES=$(subdir)/$@ CONFIG_HEADERS= $(SHELL) ./config.status @@ -261,6 +281,9 @@ distclean-noinstPROGRAMS: maintainer-clean-noinstPROGRAMS: +.c.o: + $(COMPILE) -c $< + .s.o: $(COMPILE) -c $< @@ -277,6 +300,9 @@ distclean-compile: maintainer-clean-compile: +.c.lo: + $(LIBTOOL) --mode=compile $(COMPILE) -c $< + .s.lo: $(LIBTOOL) --mode=compile $(COMPILE) -c $< @@ -352,6 +378,18 @@ t-eoRandom: $(t_eoRandom_OBJECTS) $(t_eoRandom_DEPENDENCIES) t-parser: $(t_parser_OBJECTS) $(t_parser_DEPENDENCIES) @rm -f t-parser $(CXXLINK) $(t_parser_LDFLAGS) $(t_parser_OBJECTS) $(t_parser_LDADD) $(LIBS) + +t-eoESFull: $(t_eoESFull_OBJECTS) $(t_eoESFull_DEPENDENCIES) + @rm -f t-eoESFull + $(CXXLINK) $(t_eoESFull_LDFLAGS) $(t_eoESFull_OBJECTS) $(t_eoESFull_LDADD) $(LIBS) + +t-eoESOps: $(t_eoESOps_OBJECTS) $(t_eoESOps_DEPENDENCIES) + @rm -f t-eoESOps + $(CXXLINK) $(t_eoESOps_LDFLAGS) $(t_eoESOps_OBJECTS) $(t_eoESOps_LDADD) $(LIBS) + +t-eoAtomOps: $(t_eoAtomOps_OBJECTS) $(t_eoAtomOps_DEPENDENCIES) + @rm -f t-eoAtomOps + $(CXXLINK) $(t_eoAtomOps_LDFLAGS) $(t_eoAtomOps_OBJECTS) $(t_eoAtomOps_LDADD) $(LIBS) .cc.o: $(CXXCOMPILE) -c $< .cc.lo: @@ -395,91 +433,16 @@ distdir = $(top_builddir)/$(PACKAGE)-$(VERSION)/$(subdir) subdir = test distdir: $(DISTFILES) - here=`cd $(top_builddir) && pwd`; \ - top_distdir=`cd $(top_distdir) && pwd`; \ - distdir=`cd $(distdir) && pwd`; \ - cd $(top_srcdir) \ - && $(AUTOMAKE) --include-deps --build-dir=$$here --srcdir-name=$(top_srcdir) --output-dir=$$top_distdir --gnu test/Makefile @for file in $(DISTFILES); do \ d=$(srcdir); \ if test -d $$d/$$file; then \ - cp -pr $$/$$file $(distdir)/$$file; \ + cp -pr $$d/$$file $(distdir)/$$file; \ else \ test -f $(distdir)/$$file \ || ln $$d/$$file $(distdir)/$$file 2> /dev/null \ || cp -p $$d/$$file $(distdir)/$$file || :; \ fi; \ done - -DEPS_MAGIC := $(shell mkdir .deps > /dev/null 2>&1 || :) - --include $(DEP_FILES) - -mostlyclean-depend: - -clean-depend: - -distclean-depend: - -rm -rf .deps - -maintainer-clean-depend: - -%.o: %.c - @echo '$(COMPILE) -c $<'; \ - $(COMPILE) -Wp,-MD,.deps/$(*F).pp -c $< - @-cp .deps/$(*F).pp .deps/$(*F).P; \ - tr ' ' '\012' < .deps/$(*F).pp \ - | sed -e 's/^\\$$//' -e '/^$$/ d' -e '/:$$/ d' -e 's/$$/ :/' \ - >> .deps/$(*F).P; \ - rm .deps/$(*F).pp - -%.lo: %.c - @echo '$(LTCOMPILE) -c $<'; \ - $(LTCOMPILE) -Wp,-MD,.deps/$(*F).pp -c $< - @-sed -e 's/^\([^:]*\)\.o[ ]*:/\1.lo \1.o :/' \ - < .deps/$(*F).pp > .deps/$(*F).P; \ - tr ' ' '\012' < .deps/$(*F).pp \ - | sed -e 's/^\\$$//' -e '/^$$/ d' -e '/:$$/ d' -e 's/$$/ :/' \ - >> .deps/$(*F).P; \ - rm -f .deps/$(*F).pp - -%.o: %.cc - @echo '$(CXXCOMPILE) -c $<'; \ - $(CXXCOMPILE) -Wp,-MD,.deps/$(*F).pp -c $< - @-cp .deps/$(*F).pp .deps/$(*F).P; \ - tr ' ' '\012' < .deps/$(*F).pp \ - | sed -e 's/^\\$$//' -e '/^$$/ d' -e '/:$$/ d' -e 's/$$/ :/' \ - >> .deps/$(*F).P; \ - rm .deps/$(*F).pp - -%.lo: %.cc - @echo '$(LTCXXCOMPILE) -c $<'; \ - $(LTCXXCOMPILE) -Wp,-MD,.deps/$(*F).pp -c $< - @-sed -e 's/^\([^:]*\)\.o[ ]*:/\1.lo \1.o :/' \ - < .deps/$(*F).pp > .deps/$(*F).P; \ - tr ' ' '\012' < .deps/$(*F).pp \ - | sed -e 's/^\\$$//' -e '/^$$/ d' -e '/:$$/ d' -e 's/$$/ :/' \ - >> .deps/$(*F).P; \ - rm -f .deps/$(*F).pp - -%.o: %.cpp - @echo '$(CXXCOMPILE) -c $<'; \ - $(CXXCOMPILE) -Wp,-MD,.deps/$(*F).pp -c $< - @-cp .deps/$(*F).pp .deps/$(*F).P; \ - tr ' ' '\012' < .deps/$(*F).pp \ - | sed -e 's/^\\$$//' -e '/^$$/ d' -e '/:$$/ d' -e 's/$$/ :/' \ - >> .deps/$(*F).P; \ - rm .deps/$(*F).pp - -%.lo: %.cpp - @echo '$(LTCXXCOMPILE) -c $<'; \ - $(LTCXXCOMPILE) -Wp,-MD,.deps/$(*F).pp -c $< - @-sed -e 's/^\([^:]*\)\.o[ ]*:/\1.lo \1.o :/' \ - < .deps/$(*F).pp > .deps/$(*F).P; \ - tr ' ' '\012' < .deps/$(*F).pp \ - | sed -e 's/^\\$$//' -e '/^$$/ d' -e '/:$$/ d' -e 's/$$/ :/' \ - >> .deps/$(*F).P; \ - rm -f .deps/$(*F).pp info-am: info: info-am dvi-am: @@ -502,7 +465,7 @@ uninstall: uninstall-am all-am: Makefile $(PROGRAMS) all-redirect: all-am install-strip: - $(MAKE) $(AM_MAKEFLAGS) AM_INSTALL_PROGRAM_FLAGS=-s install + $(MAKE) $(AM_MAKEFLAGS) INSTALL_STRIP_FLAG=-s install installdirs: @@ -516,27 +479,27 @@ distclean-generic: maintainer-clean-generic: mostlyclean-am: mostlyclean-noinstPROGRAMS mostlyclean-compile \ - mostlyclean-libtool mostlyclean-tags mostlyclean-depend \ + mostlyclean-libtool mostlyclean-tags \ mostlyclean-generic mostlyclean: mostlyclean-am clean-am: clean-noinstPROGRAMS clean-compile clean-libtool clean-tags \ - clean-depend clean-generic mostlyclean-am + clean-generic mostlyclean-am clean: clean-am distclean-am: distclean-noinstPROGRAMS distclean-compile \ - distclean-libtool distclean-tags distclean-depend \ - distclean-generic clean-am + distclean-libtool distclean-tags distclean-generic \ + clean-am -rm -f libtool distclean: distclean-am maintainer-clean-am: maintainer-clean-noinstPROGRAMS \ maintainer-clean-compile maintainer-clean-libtool \ - maintainer-clean-tags maintainer-clean-depend \ - maintainer-clean-generic distclean-am + maintainer-clean-tags maintainer-clean-generic \ + distclean-am @echo "This command is intended for maintainers to use;" @echo "it deletes files that may require special tools to rebuild." @@ -547,14 +510,12 @@ clean-noinstPROGRAMS maintainer-clean-noinstPROGRAMS \ mostlyclean-compile distclean-compile clean-compile \ maintainer-clean-compile mostlyclean-libtool distclean-libtool \ clean-libtool maintainer-clean-libtool tags mostlyclean-tags \ -distclean-tags clean-tags maintainer-clean-tags distdir \ -mostlyclean-depend distclean-depend clean-depend \ -maintainer-clean-depend info-am info dvi-am dvi check check-am \ -installcheck-am installcheck install-exec-am install-exec \ -install-data-am install-data install-am install uninstall-am uninstall \ -all-redirect all-am all installdirs mostlyclean-generic \ -distclean-generic clean-generic maintainer-clean-generic clean \ -mostlyclean distclean maintainer-clean +distclean-tags clean-tags maintainer-clean-tags distdir info-am info \ +dvi-am dvi check check-am installcheck-am installcheck install-exec-am \ +install-exec install-data-am install-data install-am install \ +uninstall-am uninstall all-redirect all-am all installdirs \ +mostlyclean-generic distclean-generic clean-generic \ +maintainer-clean-generic clean mostlyclean distclean maintainer-clean ############################################################################### diff --git a/eo/test/real_value.h b/eo/test/real_value.h new file mode 100644 index 000000000..1822f2902 --- /dev/null +++ b/eo/test/real_value.h @@ -0,0 +1,23 @@ +#include + +//----------------------------------------------------------------------------- + +typedef vector Vec; + +/** Just a simple function that takes an eoVector and sets the fitnes + to -sphere (we'll see later how to minimize rather than maximize!) + @param _ind A floatingpoint vector +*/ +float the_real_value(Vec& _ind) +{ + double sum = 0; /* compute in double format, even if return a float */ + for (unsigned i = 0; i < _ind.size(); i++) + sum += _ind[i] * _ind[i]; + return -sum; +} + +typedef eoESFullChrom Ind; + +void real_value(Ind & _ind) { + _ind.fitness( the_real_value(_ind) ); +} diff --git a/eo/test/t-eoAtomOps.cpp b/eo/test/t-eoAtomOps.cpp new file mode 100644 index 000000000..03bb367d1 --- /dev/null +++ b/eo/test/t-eoAtomOps.cpp @@ -0,0 +1,33 @@ +// Program to test several EO-ES features + +#ifdef _MSC_VER +#pragma warning(disable:4786) +#endif + +#include +#include +#include + +using namespace std; + +// Operators we are going to test +#include +#include +#include +#include + +// Several EOs +#include + +main(int argc, char *argv[]) { + eoString aString("123456"); + eoAtomCreep creeper; + eoAtomMutation< eoString > mutator( creeper, 0.5 ); + + cout << "Before aString " << aString; + mutator( aString); + cout << " after mutator " << aString; + + return 0; // to avoid VC++ complaints +} + diff --git a/eo/test/t-eoESFull.cpp b/eo/test/t-eoESFull.cpp new file mode 100644 index 000000000..71e573762 --- /dev/null +++ b/eo/test/t-eoESFull.cpp @@ -0,0 +1,107 @@ +// Program to test several EO-ES features + +#ifdef _MSC_VER +#pragma warning(disable:4786) +#endif + +#include +#include +#include + +using namespace std; + +// general +#include // though contained in all others! +// evolution specific +#include +//#include +//#include +// representation specific + +#include // though contained in following +//#include +//#include +//#include +// this fitness +#include "real_value.h" // the sphere fitness + +// Now the main +/////////////// +typedef eoESFullChrom Ind; + +main(int argc, char *argv[]) { +// unsigned mu, lambda; +// bool comma; + + // Create the command-line parser + Parser parser( argc, argv, "Basic EA for vector with adaptive mutations"); + + //reproducible random seed - thanks, Maarten + InitRandom(parser); + + // a first Ind, reading its parameters from the parser + // will be used later to inialize the whole population + Ind FirstEO(parser); + + // Evaluation + // here we should call some parser-based constructor, + // as many evaluation function need parameters + // and also have some preliminary stuffs to do + eoEvalFuncPtr eval( real_value ); + + /* + // Evolution and population parameters + eoScheme the_scheme(parser); + + // recombination and mutation operators, reading their parameters from the parser + eoESReco MyReco(parser, FirstEO); + eoESMutate MyMut(parser, FirstEO); + + // termination conditions read by the parser + eoTermVector the_terms(parser); + + // Initialization of the population + // shoudl be called using the parser, in case you want to read from file(s) + eoESRandomize randomize; // an eoESInd randomnizer + eoPop pop(the_scheme.PopSize(), FirstEO, randomize); + // eval(pop); // shoudl we call it from inside the constructor??? + + // ALL parmeters have been read: write them out + // Writing the parameters on arv[0].status + // but of course this can be modified - see the example parser.cpp + parser.outputParam(); + // except the help parameter??? + if( parser.getBool("-h" , "--help" , "Shows this help")) { + parser.printHelp(); + exit(1); + } + + unsigned i, iind; + + + cout << "Initial population: \n" << endl; + for (i = 0; i < pop.size(); ++i) { + eval(pop[i]); + cout << pop[i].fitness() << "\t" << pop[i] << endl; + } + + // the Operators + eoSequentialOpHolder seqholder; + // seqholder.addOp(MyReco, 1.0); + seqholder.addOp(MyMut, 1.0); + + // One generation + eoEvolStep evol_scheme(the_scheme, seqholder, eval); + + // the algorithm: + eoFullEA ea(evol_scheme, the_terms); + + ea(pop); + + cout << "Final population: \n" << endl; + for (i = 0; i < pop.size(); ++i) + cout << pop[i].fitness() << "\t" << pop[i] << endl; + */ + return 0; +} + diff --git a/eo/test/t-eoESOps.cpp b/eo/test/t-eoESOps.cpp new file mode 100644 index 000000000..253a830e5 --- /dev/null +++ b/eo/test/t-eoESOps.cpp @@ -0,0 +1,116 @@ +// Program to test several EO-ES features + +#ifdef _MSC_VER +#pragma warning(disable:4786) +#endif + +#include +#include +#include + +using namespace std; + +// general +#include // though contained in all others! +// evolution specific +#include +//#include +//#include +// representation specific + +#include // though contained in following +//#include +#include +//#include +// this fitness +#include "real_value.h" // the sphere fitness + +// Now the main +/////////////// +typedef eoESFullChrom Ind; + +main(int argc, char *argv[]) { + unsigned mu, lambda; + bool comma; + + // Create the command-line parser + Parser parser( argc, argv, "Basic EA for vector with adaptive mutations"); + + //reproducible random seed - thanks, Maarten + InitRandom(parser); + + // a first Ind, reading its parameters from the parser + // will be used later to inialize the whole population + Ind FirstEO(parser); + + // Evaluation + // here we should call some parser-based constructor, + // as many evaluation function need parameters + // and also have some preliminary stuffs to do + eoEvalFuncPtr eval( real_value ); + + // recombination and mutation operators, reading their parameters from the parser + eoESMutate MyMut(parser, + FirstEO.StdDevLength(), FirstEO.size(), + FirstEO.CorCffLength() ); + + cout << "First EO " << FirstEO << endl; + MyMut(FirstEO); + cout << "First EO mutated" << FirstEO << endl; + + /* + // Evolution and population parameters + eoScheme the_scheme(parser); + + // recombination and mutation operators, reading their parameters from the parser + eoESReco MyReco(parser, FirstEO); + eoESMutate MyMut(parser, FirstEO); + + // termination conditions read by the parser + eoTermVector the_terms(parser); + + // Initialization of the population + // shoudl be called using the parser, in case you want to read from file(s) + eoESRandomize randomize; // an eoESInd randomnizer + eoPop pop(the_scheme.PopSize(), FirstEO, randomize); + // eval(pop); // shoudl we call it from inside the constructor??? + + // ALL parmeters have been read: write them out + // Writing the parameters on arv[0].status + // but of course this can be modified - see the example parser.cpp + parser.outputParam(); + // except the help parameter??? + if( parser.getBool("-h" , "--help" , "Shows this help")) { + parser.printHelp(); + exit(1); + } + + unsigned i, iind; + + + cout << "Initial population: \n" << endl; + for (i = 0; i < pop.size(); ++i) { + eval(pop[i]); + cout << pop[i].fitness() << "\t" << pop[i] << endl; + } + + // the Operators + eoSequentialOpHolder seqholder; + // seqholder.addOp(MyReco, 1.0); + seqholder.addOp(MyMut, 1.0); + + // One generation + eoEvolStep evol_scheme(the_scheme, seqholder, eval); + + // the algorithm: + eoFullEA ea(evol_scheme, the_terms); + + ea(pop); + + cout << "Final population: \n" << endl; + for (i = 0; i < pop.size(); ++i) + cout << pop[i].fitness() << "\t" << pop[i] << endl; + return 0; + */ +} + diff --git a/eo/test/t-eoNonUniform.cpp b/eo/test/t-eoNonUniform.cpp index 352b229b2..647b78c92 100644 --- a/eo/test/t-eoNonUniform.cpp +++ b/eo/test/t-eoNonUniform.cpp @@ -1,31 +1,31 @@ -//----------------------------------------------------------------------------- -// t-eoNonUniform.cc -//----------------------------------------------------------------------------- - -#include -#include - -//----------------------------------------------------------------------------- - -main() -{ - eoNonUniform nu(1000); - - cout << "----------------------------------------------------------" << endl - << "nu.step() = " << nu.step() - << "\t nu.num_step() = " << nu.num_step() << endl - << "----------------------------------------------------------" << endl; - - eoLinear l1(0, 1, nu), l2(1, 0, nu); - eoNegExp2 n1(0.1, 8, nu), n2(0.75, 3, nu); - - for (; nu; ++nu) - { - cout << nu.step() - << "\t" << l1() << "\t" << l2() - << "\t" << n1() << "\t" << n2() - << endl; - } -} - -//----------------------------------------------------------------------------- +//----------------------------------------------------------------------------- +// t-eoNonUniform.cc +//----------------------------------------------------------------------------- + +#include +#include + +//----------------------------------------------------------------------------- + +main() +{ + eoNonUniform nu(1000); + + cout << "----------------------------------------------------------" << endl + << "nu.step() = " << nu.step() + << "\t nu.num_step() = " << nu.num_step() << endl + << "----------------------------------------------------------" << endl; + + eoLinear l1(0, 1, nu), l2(1, 0, nu); + eoNegExp2 n1(0.1, 8, nu), n2(0.75, 3, nu); + + for (; nu; ++nu) + { + cout << nu.step() + << "\t" << l1() << "\t" << l2() + << "\t" << n1() << "\t" << n2() + << endl; + } +} + +//----------------------------------------------------------------------------- diff --git a/eo/test/t-eoRandom.cpp b/eo/test/t-eoRandom.cpp index 0923e8508..764b0dacb 100644 --- a/eo/test/t-eoRandom.cpp +++ b/eo/test/t-eoRandom.cpp @@ -1,28 +1,29 @@ -//----------------------------------------------------------------------------- -// t-eouniform -//----------------------------------------------------------------------------- - -#include // cout -#include // ostrstream, istrstream -#include // eoBin -#include -#include - -//----------------------------------------------------------------------------- - -main() { - eoNormal n1(-2.5,3.5); - eoNormal n2(0.003, 0.0005 ); - eoNormal n3( 10000000U, 10000U); - eoNegExp e1(3.5); - eoNegExp e2(0.003 ); - eoNegExp e3( 10000U); - cout << "n1\t\tn2\t\tn3\t\te1\t\te2\t\te3" << endl; - for ( unsigned i = 0; i < 100; i ++) { - cout << n1() << "\t" << n2() << "\t" << n3() << "\t" << - e1() << "\t" << e2() << "\t" << e3() << endl; - } - -} - -//----------------------------------------------------------------------------- +//----------------------------------------------------------------------------- +// t-eouniform +//----------------------------------------------------------------------------- + +#include // cout +#include // ostrstream, istrstream +#include // eoBin +#include +#include + +//----------------------------------------------------------------------------- + +main() { + eoNormal n1(-2.5,3.5); + eoNormal n2(0.003, 0.0005 ); + eoNormal n3( 10000000U, 10000U); + eoNegExp e1(3.5); + eoNegExp e2(0.003 ); + eoNegExp e3( 10000U); + cout << "n1\t\tn2\t\tn3\t\te1\t\te2\t\te3" << endl; + for ( unsigned i = 0; i < 100; i ++) { + cout << n1() << "\t" << n2() << "\t" << n3() << "\t" << + e1() << "\t" << e2() << "\t" << e3() << endl; + } + + return 0; // to avoid VC++ complaints +} + +//----------------------------------------------------------------------------- diff --git a/eo/test/t-eoUniform.cpp b/eo/test/t-eoUniform.cpp index 1e1e9594d..5e14a7284 100644 --- a/eo/test/t-eoUniform.cpp +++ b/eo/test/t-eoUniform.cpp @@ -1,22 +1,22 @@ -//----------------------------------------------------------------------------- -// t-eouniform -//----------------------------------------------------------------------------- - -#include // cout -#include // ostrstream, istrstream -#include // eoBin - -//----------------------------------------------------------------------------- - -main() { - eoUniform u1(-2.5,3.5); - eoUniform u2(0.003, 0 ); - eoUniform u3( 10000U, 10000000U); - cout << "u1\t\tu2\t\tu3" << endl; - for ( unsigned i = 0; i < 100; i ++) { - cout << u1() << "\t" << u2() << "\t" << u3() << endl; - } - -} - -//----------------------------------------------------------------------------- +//----------------------------------------------------------------------------- +// t-eouniform +//----------------------------------------------------------------------------- + +#include // cout +#include // ostrstream, istrstream +#include // eoBin + +//----------------------------------------------------------------------------- + +main() { + eoUniform u1(-2.5,3.5); + eoUniform u2(0.003, 0 ); + eoUniform u3( 10000U, 10000000U); + cout << "u1\t\tu2\t\tu3" << endl; + for ( unsigned i = 0; i < 100; i ++) { + cout << u1() << "\t" << u2() << "\t" << u3() << endl; + } + +} + +//----------------------------------------------------------------------------- diff --git a/eo/test/t-eobreeder.cpp b/eo/test/t-eobreeder.cpp index 0e632bc8b..876aa94b1 100644 --- a/eo/test/t-eobreeder.cpp +++ b/eo/test/t-eobreeder.cpp @@ -1,71 +1,71 @@ -//----------------------------------------------------------------------------- -// t-eobreeder.cpp -//----------------------------------------------------------------------------- +//----------------------------------------------------------------------------- +// t-eobreeder.cpp +//----------------------------------------------------------------------------- // to avoid long name warnings #pragma warning(disable:4786) - -#include // eoBin, eoPop, eoBreeder + +#include // eoBin, eoPop, eoBreeder #include #include #include #include - -//----------------------------------------------------------------------------- - -typedef eoBin Chrom; - -//----------------------------------------------------------------------------- - -void binary_value(Chrom& chrom) -{ - float sum = 0; - for (unsigned i = 0; i < chrom.size(); i++) - if (chrom[i]) - sum += pow(2, chrom.size() - i - 1); - chrom.fitness(sum); -} - -//----------------------------------------------------------------------------- - -main() -{ - const unsigned POP_SIZE = 8, CHROM_SIZE = 4; - unsigned i; - - eoUniform uniform(false, true); - eoBinRandom random; - eoPop pop; - - for (i = 0; i < POP_SIZE; ++i) - { - Chrom chrom(CHROM_SIZE); - random(chrom); - binary_value(chrom); - pop.push_back(chrom); - } - - cout << "population:" << endl; - for (i = 0; i < pop.size(); ++i) - cout << pop[i] << " " << pop[i].fitness() << endl; - - eoBinBitFlip bitflip; - eoBinCrossover xover; - eoProportionalOpSel propSel; - eoBreeder breeder( propSel ); - propSel.addOp(bitflip, 0.25); - propSel.addOp(xover, 0.75); - - breeder(pop); - - // reevaluation of fitness - for_each(pop.begin(), pop.end(), binary_value); - - cout << "new population:" << endl; - for (i = 0; i < pop.size(); ++i) - cout << pop[i] << " " << pop[i].fitness() << endl; - - return 0; -} - -//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- + +typedef eoBin Chrom; + +//----------------------------------------------------------------------------- + +void binary_value(Chrom& chrom) +{ + float sum = 0; + for (unsigned i = 0; i < chrom.size(); i++) + if (chrom[i]) + sum += pow(2, chrom.size() - i - 1); + chrom.fitness(sum); +} + +//----------------------------------------------------------------------------- + +main() +{ + const unsigned POP_SIZE = 8, CHROM_SIZE = 4; + unsigned i; + + eoUniform uniform(false, true); + eoBinRandom random; + eoPop pop; + + for (i = 0; i < POP_SIZE; ++i) + { + Chrom chrom(CHROM_SIZE); + random(chrom); + binary_value(chrom); + pop.push_back(chrom); + } + + cout << "population:" << endl; + for (i = 0; i < pop.size(); ++i) + cout << pop[i] << " " << pop[i].fitness() << endl; + + eoBinBitFlip bitflip; + eoBinCrossover xover; + eoProportionalOpSel propSel; + eoBreeder breeder( propSel ); + propSel.addOp(bitflip, 0.25); + propSel.addOp(xover, 0.75); + + breeder(pop); + + // reevaluation of fitness + for_each(pop.begin(), pop.end(), binary_value); + + cout << "new population:" << endl; + for (i = 0; i < pop.size(); ++i) + cout << pop[i] << " " << pop[i].fitness() << endl; + + return 0; +} + +//----------------------------------------------------------------------------- diff --git a/eo/test/t-eofitness.cpp b/eo/test/t-eofitness.cpp index a8604d245..f31616203 100644 --- a/eo/test/t-eofitness.cpp +++ b/eo/test/t-eofitness.cpp @@ -1,87 +1,87 @@ -//----------------------------------------------------------------------------- -// t-eofitness.cpp -// (c) GeNeura Team 1998 -//----------------------------------------------------------------------------- - -#include // time -#include // srand, rand -#include // cout -#include // eoFitness - -//----------------------------------------------------------------------------- - -class eoFloat: public eoFitness -{ -public: - eoFloat(const float x) { fitness = x; } - eoFloat(const int x) { fitness = static_cast(x); } - - bool operator<(const eoFitness& other) const - { - const eoFloat& x = (const eoFloat&) other; - return fitness < x.fitness; - } - - operator float() const - { - return fitness; - } - - void printOn(ostream& os) const - { - os << fitness; - } - - void readFrom(istream& is) - { - is >> fitness; - } - -private: - float fitness; -}; - -//----------------------------------------------------------------------------- - -main() -{ - srand(time(0)); - - eoFloat a = static_cast(rand()) / RAND_MAX, - b = static_cast(rand()) / RAND_MAX; - - cout.precision(2); - - unsigned repeat = 2; - while (repeat--) - { - cout << "------------------------------------------------------" << endl; - cout << "testing < "; - if (a < b) - cout << a << " < " << b << " is true" << endl; - else - cout << a << " < " << b << " is false" < "; - if (a > b) - cout << a << " > " << b << " is true" << endl; - else - cout << a << " > " << b << " is false" < // time +#include // srand, rand +#include // cout +#include // eoFitness + +//----------------------------------------------------------------------------- + +class eoFloat: public eoFitness +{ +public: + eoFloat(const float x) { fitness = x; } + eoFloat(const int x) { fitness = static_cast(x); } + + bool operator<(const eoFitness& other) const + { + const eoFloat& x = (const eoFloat&) other; + return fitness < x.fitness; + } + + operator float() const + { + return fitness; + } + + void printOn(ostream& os) const + { + os << fitness; + } + + void readFrom(istream& is) + { + is >> fitness; + } + +private: + float fitness; +}; + +//----------------------------------------------------------------------------- + +main() +{ + srand(time(0)); + + eoFloat a = static_cast(rand()) / RAND_MAX, + b = static_cast(rand()) / RAND_MAX; + + cout.precision(2); + + unsigned repeat = 2; + while (repeat--) + { + cout << "------------------------------------------------------" << endl; + cout << "testing < "; + if (a < b) + cout << a << " < " << b << " is true" << endl; + else + cout << a << " < " << b << " is false" < "; + if (a > b) + cout << a << " > " << b << " is true" << endl; + else + cout << a << " > " << b << " is false" < - -#include "binary_value.h" - -//----------------------------------------------------------------------------- - -typedef eoBin Chrom; - -//----------------------------------------------------------------------------- - -main() -{ - const unsigned POP_SIZE = 8, CHROM_SIZE = 16; - unsigned i; - - eoUniform uniform(false, true); - eoBinRandom random; - eoPop pop; - - for (i = 0; i < POP_SIZE; ++i) - { - Chrom chrom(CHROM_SIZE); - random(chrom); - binary_value(chrom); - pop.push_back(chrom); - } - - cout << "population:" << endl; - for (i = 0; i < pop.size(); ++i) - cout << "\t" << pop[i] << " " << pop[i].fitness() << endl; - - - // selection - eoLottery lottery; - - // breeder - eoBinBitFlip bitflip; - eoBinCrossover xover; - eoProportionalOpSel propSel; - eoBreeder breeder( propSel ); - propSel.addOp(bitflip, 0.25); - propSel.addOp(xover, 0.75); - - // replacement - eoInclusion inclusion; - - // Evaluation - eoEvalFuncPtr eval( binary_value ); - - // GA generation - eoGeneration generation(lottery, breeder, inclusion, eval); - - // evolution - unsigned g = 0; - do { - try - { - generation(pop); - } - catch (exception& e) - { - cout << "exception: " << e.what() << endl;; - exit(EXIT_FAILURE); - } - - cout << "pop[" << ++g << "]" << endl; - for (i = 0; i < pop.size(); ++i) - cout << "\t" << pop[i] << " " << pop[i].fitness() << endl; - - } while (pop[0].fitness() < pow(2.0, CHROM_SIZE) - 1); - - return 0; -} - -//----------------------------------------------------------------------------- +//----------------------------------------------------------------------------- +// t-eogeneration.cpp +//----------------------------------------------------------------------------- + +// to avoid long name warnings +#pragma warning(disable:4786) + +#include + +#include "binary_value.h" + +//----------------------------------------------------------------------------- + +typedef eoBin Chrom; + +//----------------------------------------------------------------------------- + +main() +{ + const unsigned POP_SIZE = 8, CHROM_SIZE = 16; + unsigned i; + + eoUniform uniform(false, true); + eoBinRandom random; + eoPop pop; + + for (i = 0; i < POP_SIZE; ++i) + { + Chrom chrom(CHROM_SIZE); + random(chrom); + binary_value(chrom); + pop.push_back(chrom); + } + + cout << "population:" << endl; + for (i = 0; i < pop.size(); ++i) + cout << "\t" << pop[i] << " " << pop[i].fitness() << endl; + + + // selection + eoLottery lottery; + + // breeder + eoBinBitFlip bitflip; + eoBinCrossover xover; + eoProportionalOpSel propSel; + eoBreeder breeder( propSel ); + propSel.addOp(bitflip, 0.25); + propSel.addOp(xover, 0.75); + + // replacement + eoInclusion inclusion; + + // Evaluation + eoEvalFuncPtr eval( binary_value ); + + // GA generation + eoGeneration generation(lottery, breeder, inclusion, eval); + + // evolution + unsigned g = 0; + do { + try + { + generation(pop); + } + catch (exception& e) + { + cout << "exception: " << e.what() << endl;; + exit(EXIT_FAILURE); + } + + cout << "pop[" << ++g << "]" << endl; + for (i = 0; i < pop.size(); ++i) + cout << "\t" << pop[i] << " " << pop[i].fitness() << endl; + + } while (pop[0].fitness() < pow(2.0, CHROM_SIZE) - 1); + + return 0; +} + +//----------------------------------------------------------------------------- diff --git a/eo/test/t-eoinsertion.cpp b/eo/test/t-eoinsertion.cpp index c21c61d7c..cb590c262 100644 --- a/eo/test/t-eoinsertion.cpp +++ b/eo/test/t-eoinsertion.cpp @@ -1,108 +1,108 @@ -//----------------------------------------------------------------------------- -// t-eoinsertion.cpp -//----------------------------------------------------------------------------- - -#include // eoBin, eoPop, eoInsertion - -//----------------------------------------------------------------------------- - -typedef eoBin Chrom; - -//----------------------------------------------------------------------------- - -void binary_value(Chrom& chrom) -{ - float sum = 0; - for (unsigned i = 0; i < chrom.size(); i++) - if (chrom[i]) - sum += pow(2, chrom.size() - i - 1); - chrom.fitness(sum); -} - -//----------------------------------------------------------------------------- - -main() -{ - const unsigned CHROM_SIZE = 4; - unsigned i; - - eoUniform uniform(false, true); - eoBinRandom random; - - for (unsigned POP_SIZE = 4; POP_SIZE <=6; POP_SIZE++) - { - eoPop pop; - - for (i = 0; i < POP_SIZE; i++) - { - Chrom chrom(CHROM_SIZE); - random(chrom); - binary_value(chrom); - pop.push_back(chrom); - } - - for (unsigned POP2_SIZE = 4; POP2_SIZE <=6; POP2_SIZE++) - { - eoPop pop2, pop3, pop4, pop5, popx; - - for (i = 0; i < POP2_SIZE; i++) - { - Chrom chrom(CHROM_SIZE); - random(chrom); - binary_value(chrom); - pop2.push_back(chrom); - } - - cout << "--------------------------------------------------" << endl - << "breeders \tpop" << endl - << "--------------------------------------------------" << endl; - for (i = 0; i < max(pop.size(), pop2.size()); i++) - { - if (pop.size() > i) - cout << pop[i] << " " << pop[i].fitness() << " \t"; - else - cout << "\t\t"; - if (pop2.size() > i) - cout << pop2[i] << " " << pop2[i].fitness(); - cout << endl; - } - - eoInsertion insertion(0.75); - popx = pop; - pop3 = pop2; - insertion(popx, pop3); - - eoInsertion insertion2; - popx = pop; - pop4 = pop2; - insertion2(popx, pop4); - - eoInsertion insertion3(1.5); - popx = pop; - pop5 = pop2; - insertion3(popx, pop5); - - cout << endl - << "0.75 \t\t1.0 \t\t1.5" << endl - << "---- \t\t--- \t\t---" << endl; - for (i = 0; i < pop5.size(); i++) - { - if (pop3.size() > i) - cout << pop3[i] << " " << pop3[i].fitness() << " \t"; - else - cout << " \t\t"; - if (pop4.size() > i) - cout << pop4[i] << " " << pop4[i].fitness() << " \t"; - else - cout << " \t\t"; - if (pop5.size() > i) - cout << pop5[i] << " " << pop5[i].fitness(); - cout << endl; - } - } - } - - return 0; -} - -//----------------------------------------------------------------------------- +//----------------------------------------------------------------------------- +// t-eoinsertion.cpp +//----------------------------------------------------------------------------- + +#include // eoBin, eoPop, eoInsertion + +//----------------------------------------------------------------------------- + +typedef eoBin Chrom; + +//----------------------------------------------------------------------------- + +void binary_value(Chrom& chrom) +{ + float sum = 0; + for (unsigned i = 0; i < chrom.size(); i++) + if (chrom[i]) + sum += pow(2, chrom.size() - i - 1); + chrom.fitness(sum); +} + +//----------------------------------------------------------------------------- + +main() +{ + const unsigned CHROM_SIZE = 4; + unsigned i; + + eoUniform uniform(false, true); + eoBinRandom random; + + for (unsigned POP_SIZE = 4; POP_SIZE <=6; POP_SIZE++) + { + eoPop pop; + + for (i = 0; i < POP_SIZE; i++) + { + Chrom chrom(CHROM_SIZE); + random(chrom); + binary_value(chrom); + pop.push_back(chrom); + } + + for (unsigned POP2_SIZE = 4; POP2_SIZE <=6; POP2_SIZE++) + { + eoPop pop2, pop3, pop4, pop5, popx; + + for (i = 0; i < POP2_SIZE; i++) + { + Chrom chrom(CHROM_SIZE); + random(chrom); + binary_value(chrom); + pop2.push_back(chrom); + } + + cout << "--------------------------------------------------" << endl + << "breeders \tpop" << endl + << "--------------------------------------------------" << endl; + for (i = 0; i < max(pop.size(), pop2.size()); i++) + { + if (pop.size() > i) + cout << pop[i] << " " << pop[i].fitness() << " \t"; + else + cout << "\t\t"; + if (pop2.size() > i) + cout << pop2[i] << " " << pop2[i].fitness(); + cout << endl; + } + + eoInsertion insertion(0.75); + popx = pop; + pop3 = pop2; + insertion(popx, pop3); + + eoInsertion insertion2; + popx = pop; + pop4 = pop2; + insertion2(popx, pop4); + + eoInsertion insertion3(1.5); + popx = pop; + pop5 = pop2; + insertion3(popx, pop5); + + cout << endl + << "0.75 \t\t1.0 \t\t1.5" << endl + << "---- \t\t--- \t\t---" << endl; + for (i = 0; i < pop5.size(); i++) + { + if (pop3.size() > i) + cout << pop3[i] << " " << pop3[i].fitness() << " \t"; + else + cout << " \t\t"; + if (pop4.size() > i) + cout << pop4[i] << " " << pop4[i].fitness() << " \t"; + else + cout << " \t\t"; + if (pop5.size() > i) + cout << pop5[i] << " " << pop5[i].fitness(); + cout << endl; + } + } + } + + return 0; +} + +//----------------------------------------------------------------------------- diff --git a/eo/test/t-parser.cpp b/eo/test/t-parser.cpp index 2980bb436..268f391c9 100644 --- a/eo/test/t-parser.cpp +++ b/eo/test/t-parser.cpp @@ -1,165 +1,133 @@ -// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - -//----------------------------------------------------------------------------- -/* parser.cpp - example of use of Parser.h - - (c) geneura team, 1999 ------------------------------------------------------------------------------*/ - -#include -#include -#include - -void GetOutputParam(Parser & parser, - string & _string) { - - try { - parser.AddTitle("Separate parameter: the output file name"); - _string = parser.getString("-O", "--OutputFile", "", "The output file name" ); - } catch (UException & e) { - cout << e.what() << endl; - parser.printHelp(); - exit(1); - } catch (exception & e) { - cout << e.what() << endl; - exit(1); - } -} - -void sub(Parser & parser) { - int i; - cout << "Function sub:" << endl; - - try { - parser.AddTitle("Private parameters of subroutine sub"); - i = parser.getInt("-j", "--sint", "5", "private integer of subroutine" ); - } catch (UException & e) { - cout << e.what() << endl; - parser.printHelp(); - exit(1); - } catch (exception & e) { - cout << e.what() << endl; - exit(1); - } - - cout << "Read " << i << endl; -} - - -/// Uses the parser and returns param values -void getParams( Parser & parser, - unsigned & _integer, - float & _floating, - string & _string, - vector & _array, - bool & _boolean) { - - try { - _integer = parser.getInt("-i", "--int", "2", "interger number" ); - _floating = parser.getFloat("-f", "--float", "0.2", "floating point number" ); - _string = parser.getString("-s", "--string", "string", "a string" ); - _array = parser.getArray("-a", "--array", "a b", "an array enclosed within < >" ); - _boolean = parser.getBool("-b","--bool", "a bool value" ); - } - catch (UException & e) - { - cout << e.what() << endl; - parser.printHelp(); - exit(1); - } - catch (exception & e) - { - cout << e.what() << endl; - exit(1); - } - -} - -/// Uses the parser and returns param values -void InitRandom( Parser & parser) { - unsigned long _seed; - try { - _seed = parser.getUnsignedLong("-S", "--seed", "0", "Seed for Random number generator" ); - } - catch (UException & e) - { - cout << e.what() << endl; - parser.printHelp(); - exit(1); - } - catch (exception & e) - { - cout << e.what() << endl; - exit(1); - } - if (_seed == 0) { // use clock to get a "random" seed - struct timeval tval; - struct timezone tzp; - - gettimeofday (&tval, &tzp); // time since midnight January 1, 1970. - _seed = tval.tv_usec ; // micro seconds - char s[32]; - sprintf(s,"%ld", _seed); - parser.setParamValue("--seed", s); // so it will be printed out in the status file, and canbe later re-used to re-run EXACTLY the same run - } - rng.reseed(_seed); - - return; -} - -int main( int argc, char* argv[]) { - - unsigned in; - float f; - string s; - vector a; - bool b; - - // Create the command-line parser - Parser parser( argc, argv, "Parser example"); - InitRandom(parser); - parser.AddTitle("General parameters"); - getParams(parser, in, f, s, a, b); - - cout << "\n integer: " << in << endl - << " float: "<< f << endl - << " string: /"<< s << "/" << endl - << " boolean: "<< b << endl - << " array: < "; - vector::const_iterator i; - for (i=a.begin() ; i" << endl << endl ; - - // call to the subroutine that also needs some parameters - sub(parser); - - // writing all parameters - // - // if programmer wishes, the name of the output file can be set as a parameter itself - // otherwise it will be argv[0].status - string OutputFileName; - GetOutputParam(parser, OutputFileName); - - parser.outputParam(OutputFileName); - if( parser.getBool("-h" , "--help" , "Shows this help")) { - parser.printHelp(); - exit(1); - } - - // but progrmamer should be careful to write the parser parameters - // after the last bit that uses it has finished - - - // Now the main body of the program - - for (int i=0; i<20; i++) { - cout << rng.normal() << endl; - } - cout << "C'est fini" << endl; - - return 0; -} - +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +/* parser.cpp + example of use of Parser.h + + (c) geneura team, 1999 +-----------------------------------------------------------------------------*/ + +#include +#include +#include + +void GetOutputParam(Parser & parser, + string & _string) { + + try { + parser.AddTitle("Separate parameter: the output file name"); + _string = parser.getString("-O", "--OutputFile", "", "The output file name" ); + } catch (UException & e) { + cout << e.what() << endl; + parser.printHelp(); + exit(1); + } catch (exception & e) { + cout << e.what() << endl; + exit(1); + } +} + +void sub(Parser & parser) { + int i; + cout << "Function sub:" << endl; + + try { + parser.AddTitle("Private parameters of subroutine sub"); + i = parser.getInt("-j", "--sint", "5", "private integer of subroutine" ); + } catch (UException & e) { + cout << e.what() << endl; + parser.printHelp(); + exit(1); + } catch (exception & e) { + cout << e.what() << endl; + exit(1); + } + + cout << "Read " << i << endl; +} + + +/// Uses the parser and returns param values +void getParams( Parser & parser, + unsigned & _integer, + float & _floating, + string & _string, + vector & _array, + bool & _boolean) { + + try { + _integer = parser.getInt("-i", "--int", "2", "interger number" ); + _floating = parser.getFloat("-f", "--float", "0.2", "floating point number" ); + _string = parser.getString("-s", "--string", "string", "a string" ); + _array = parser.getArray("-a", "--array", "a b", "an array enclosed within < >" ); + _boolean = parser.getBool("-b","--bool", "a bool value" ); + } + catch (UException & e) + { + cout << e.what() << endl; + parser.printHelp(); + exit(1); + } + catch (exception & e) + { + cout << e.what() << endl; + exit(1); + } + +} + +int main( int argc, char* argv[]) { + + unsigned in; + float f; + string s; + vector a; + bool b; + + // Create the command-line parser + Parser parser( argc, argv, "Parser example"); + InitRandom(parser); + parser.AddTitle("General parameters"); + getParams(parser, in, f, s, a, b); + + cout << "\n integer: " << in << endl + << " float: "<< f << endl + << " string: /"<< s << "/" << endl + << " boolean: "<< b << endl + << " array: < "; + vector::const_iterator i; + for (i=a.begin() ; i" << endl << endl ; + + // call to the subroutine that also needs some parameters + sub(parser); + + // writing all parameters + // + // if programmer wishes, the name of the output file can be set as a parameter itself + // otherwise it will be argv[0].status + string OutputFileName; + GetOutputParam(parser, OutputFileName); + + parser.outputParam(OutputFileName); + if( parser.getBool("-h" , "--help" , "Shows this help")) { + parser.printHelp(); + exit(1); + } + + // but progrmamer should be careful to write the parser parameters + // after the last bit that uses it has finished + + + // Now the main body of the program + + for (int i=0; i<20; i++) { + cout << rng.normal() << endl; + } + cout << "C'est fini" << endl; + + return 0; +} + diff --git a/eo/win/atomops.dsp b/eo/win/atomops.dsp new file mode 100644 index 000000000..7ca9d3b0b --- /dev/null +++ b/eo/win/atomops.dsp @@ -0,0 +1,101 @@ +# Microsoft Developer Studio Project File - Name="atomops" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Console Application" 0x0103 + +CFG=atomops - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "atomops.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "atomops.mak" CFG="atomops - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "atomops - Win32 Release" (based on "Win32 (x86) Console Application") +!MESSAGE "atomops - Win32 Debug" (based on "Win32 (x86) Console Application") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "atomops - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD BASE RSC /l 0xc0a /d "NDEBUG" +# ADD RSC /l 0xc0a /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 + +!ELSEIF "$(CFG)" == "atomops - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "atomops___Win32_Debug" +# PROP BASE Intermediate_Dir "atomops___Win32_Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "atomops___Win32_Debug" +# PROP Intermediate_Dir "atomops___Win32_Debug" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c +# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c +# ADD BASE RSC /l 0xc0a /d "_DEBUG" +# ADD RSC /l 0xc0a /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept +# ADD LINK32 eo.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept + +!ENDIF + +# Begin Target + +# Name "atomops - Win32 Release" +# Name "atomops - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE="..\test\t-eoAtomOps.cpp" +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# End Group +# Begin Group "Resource Files" + +# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" +# End Group +# End Target +# End Project diff --git a/eo/win/eo.dsp b/eo/win/eo.dsp index 55ad35260..c735f606b 100644 --- a/eo/win/eo.dsp +++ b/eo/win/eo.dsp @@ -63,8 +63,8 @@ LIB32=link.exe -lib # PROP Output_Dir "eo___Win32_Debug" # PROP Intermediate_Dir "eo___Win32_Debug" # PROP Target_Dir "" -# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c -# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c +# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c # ADD BASE RSC /l 0xc0a /d "_DEBUG" # ADD RSC /l 0xc0a /d "_DEBUG" BSC32=bscmake.exe @@ -95,46 +95,6 @@ SOURCE=..\src\eoPrintable.cpp # Begin Group "Header Files" # PROP Default_Filter "h;hpp;hxx;hm;inl" -# Begin Source File - -SOURCE=..\src\EO.h -# End Source File -# Begin Source File - -SOURCE=..\src\eo1d.h -# End Source File -# Begin Source File - -SOURCE=..\src\eoFitness.h -# End Source File -# Begin Source File - -SOURCE=..\src\eoNegExp.h -# End Source File -# Begin Source File - -SOURCE=..\src\eoNormal.h -# End Source File -# Begin Source File - -SOURCE=..\src\eoObject.h -# End Source File -# Begin Source File - -SOURCE=..\src\eoProblem.h -# End Source File -# Begin Source File - -SOURCE=..\src\eoRnd.h -# End Source File -# Begin Source File - -SOURCE=..\src\eoUniform.h -# End Source File -# Begin Source File - -SOURCE=..\src\eoVector.h -# End Source File # End Group # End Target # End Project diff --git a/eo/win/eo.dsw b/eo/win/eo.dsw new file mode 100644 index 000000000..176e89324 --- /dev/null +++ b/eo/win/eo.dsw @@ -0,0 +1,74 @@ +Microsoft Developer Studio Workspace File, Format Version 6.00 +# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! + +############################################################################### + +Project: "atomops"=".\atomops.dsp" - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Project: "eo"=".\eo.dsp" - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ + Begin Project Dependency + Project_Dep_Name random + End Project Dependency + Begin Project Dependency + Project_Dep_Name atomops + End Project Dependency + Begin Project Dependency + Project_Dep_Name esfull + End Project Dependency +}}} + +############################################################################### + +Project: "esfull"=".\esfull.dsp" - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Project: "random"=".\random.dsp" - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ +}}} + +############################################################################### + +Global: + +Package=<5> +{{{ +}}} + +Package=<3> +{{{ +}}} + +############################################################################### + diff --git a/eo/win/esfull.dsp b/eo/win/esfull.dsp new file mode 100644 index 000000000..f1b5bac36 --- /dev/null +++ b/eo/win/esfull.dsp @@ -0,0 +1,101 @@ +# Microsoft Developer Studio Project File - Name="esfull" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Console Application" 0x0103 + +CFG=esfull - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "esfull.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "esfull.mak" CFG="esfull - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "esfull - Win32 Release" (based on "Win32 (x86) Console Application") +!MESSAGE "esfull - Win32 Debug" (based on "Win32 (x86) Console Application") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "esfull - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD BASE RSC /l 0xc0a /d "NDEBUG" +# ADD RSC /l 0xc0a /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 + +!ELSEIF "$(CFG)" == "esfull - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "esfull___Win32_Debug" +# PROP BASE Intermediate_Dir "esfull___Win32_Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "esfull___Win32_Debug" +# PROP Intermediate_Dir "esfull___Win32_Debug" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c +# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /FR /YX /FD /GZ /c +# ADD BASE RSC /l 0xc0a /d "_DEBUG" +# ADD RSC /l 0xc0a /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept +# ADD LINK32 eo.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept + +!ENDIF + +# Begin Target + +# Name "esfull - Win32 Release" +# Name "esfull - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE="..\test\t-eoESFull.cpp" +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# End Group +# Begin Group "Resource Files" + +# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" +# End Group +# End Target +# End Project diff --git a/eo/win/random.dsp b/eo/win/random.dsp new file mode 100644 index 000000000..63fe9bb02 --- /dev/null +++ b/eo/win/random.dsp @@ -0,0 +1,101 @@ +# Microsoft Developer Studio Project File - Name="random" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Console Application" 0x0103 + +CFG=random - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "random.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "random.mak" CFG="random - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "random - Win32 Release" (based on "Win32 (x86) Console Application") +!MESSAGE "random - Win32 Debug" (based on "Win32 (x86) Console Application") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "random - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD BASE RSC /l 0xc0a /d "NDEBUG" +# ADD RSC /l 0xc0a /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 + +!ELSEIF "$(CFG)" == "random - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "random___Win32_Debug" +# PROP BASE Intermediate_Dir "random___Win32_Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "random___Win32_Debug" +# PROP Intermediate_Dir "random___Win32_Debug" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c +# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c +# ADD BASE RSC /l 0xc0a /d "_DEBUG" +# ADD RSC /l 0xc0a /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept +# ADD LINK32 eo.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept + +!ENDIF + +# Begin Target + +# Name "random - Win32 Release" +# Name "random - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE="..\test\t-eoRandom.cpp" +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# End Group +# Begin Group "Resource Files" + +# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" +# End Group +# End Target +# End Project