Migration from SVN
This commit is contained in:
parent
d7d6c3a217
commit
8cd56f37db
29069 changed files with 0 additions and 4096888 deletions
46
eo/src/utils/CMakeLists.txt
Normal file
46
eo/src/utils/CMakeLists.txt
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
######################################################################################
|
||||
### 1) Include the sources
|
||||
######################################################################################
|
||||
|
||||
INCLUDE_DIRECTORIES(${EO_SOURCE_DIR}/src)
|
||||
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR})
|
||||
|
||||
######################################################################################
|
||||
### 2) Define the ga target
|
||||
######################################################################################
|
||||
|
||||
SET(EOUTILS_LIB_OUTPUT_PATH ${EO_BINARY_DIR}/lib)
|
||||
SET(LIBRARY_OUTPUT_PATH ${EOUTILS_LIB_OUTPUT_PATH})
|
||||
|
||||
SET(EOUTILS_SOURCES
|
||||
eoData.cpp
|
||||
eoFileMonitor.cpp
|
||||
eoGnuplot.cpp
|
||||
eoGnuplot1DMonitor.cpp
|
||||
eoGnuplot1DSnapshot.cpp
|
||||
eoIntBounds.cpp
|
||||
eoParser.cpp
|
||||
eoRealBounds.cpp
|
||||
eoRNG.cpp
|
||||
eoState.cpp
|
||||
eoOStreamMonitor.cpp
|
||||
eoUpdater.cpp
|
||||
make_help.cpp
|
||||
pipecom.cpp
|
||||
eoLogger.cpp
|
||||
eoParallel.cpp
|
||||
eoSignal.cpp
|
||||
)
|
||||
|
||||
ADD_LIBRARY(eoutils STATIC ${EOUTILS_SOURCES})
|
||||
INSTALL(TARGETS eoutils ARCHIVE DESTINATION local/${LIB} COMPONENT libraries)
|
||||
|
||||
|
||||
######################################################################################
|
||||
### 3) Optionnal
|
||||
######################################################################################
|
||||
|
||||
SET(EOUTILS_VERSION ${GLOBAL_VERSION})
|
||||
SET_TARGET_PROPERTIES(eoutils PROPERTIES VERSION "${EOUTILS_VERSION}")
|
||||
|
||||
######################################################################################
|
||||
42
eo/src/utils/ChangeLog
Normal file
42
eo/src/utils/ChangeLog
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
2007-08-22 Jochen Küpper <jochen@fhi-berlin.mpg.de>
|
||||
|
||||
* eoRNG.h (eoRng::random): Add comment on truncation as standard way of
|
||||
floating point to integer conversion.
|
||||
|
||||
2006-12-04 Jochen Küpper <jochen@fhi-berlin.mpg.de>
|
||||
|
||||
* eoRNG.h (eoRng::normal(stdev)): Revert erroneous change.
|
||||
|
||||
2006-12-02 Jochen Küpper <jochen@fhi-berlin.mpg.de>
|
||||
|
||||
* eoTimedMonitor.h (eoTimedMonitor::seconds): Make unsigned.
|
||||
|
||||
* eoRNG.h: Cleanup docs and document /all/ members.
|
||||
|
||||
* eoRNG.cpp, eoRNG.h (K, M, N): Declare static and initialize in cpp.
|
||||
|
||||
2006-12-01 Jochen Küpper <jochen@fhi-berlin.mpg.de>
|
||||
|
||||
* eoRNG.cpp: Use C++ style cast.
|
||||
|
||||
* Makefile.am: Add missing header for distribution.
|
||||
|
||||
2006-11-30 Jochen Küpper <jochen@fhi-berlin.mpg.de>
|
||||
|
||||
* eoRNG.h: Generally include <cmath>
|
||||
|
||||
2006-11-16 Jochen Küpper <jochen@fhi-berlin.mpg.de>
|
||||
|
||||
* eoParser.h (eoParser::getORcreateParam): Make this a real if-then-else
|
||||
clause around ptParam (found or not).
|
||||
|
||||
* eoParam.h (eoValueParam::setValue): Document.
|
||||
(eoValueParam<std::vector<double> >::setValue): Allow delimiters ',' and
|
||||
';'. A plain ' ' does not work, as it is not correctly read by
|
||||
eoParser::readFrom.
|
||||
|
||||
* Local Variables:
|
||||
* coding: iso-8859-1
|
||||
* mode: flyspell
|
||||
* fill-column: 80
|
||||
* End:
|
||||
56
eo/src/utils/checkpointing
Normal file
56
eo/src/utils/checkpointing
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
/*
|
||||
-----------------------------------------------------------------------------
|
||||
checkpointing
|
||||
|
||||
(c) Maarten Keijzer (mak@dhi.dk) and GeNeura Team, 1999, 2000
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
|
||||
*/
|
||||
|
||||
#ifndef _CHECKPOINTING_
|
||||
#define _CHECKPOINTING_
|
||||
|
||||
#include <utils/eoParser.h>
|
||||
#include <utils/eoState.h>
|
||||
#include <utils/eoUpdater.h>
|
||||
#include <utils/eoMonitor.h>
|
||||
#include <utils/eoFileMonitor.h>
|
||||
#include <utils/eoStdoutMonitor.h>
|
||||
#include <utils/eoOStreamMonitor.h>
|
||||
#ifndef _MSC_VER
|
||||
#include <utils/eoGnuplot1DMonitor.h>
|
||||
#include <utils/eoGnuplot1DSnapshot.h>
|
||||
#endif
|
||||
#include <utils/eoCheckPoint.h>
|
||||
#include <utils/eoSignal.h>
|
||||
#include <utils/eoStat.h>
|
||||
#include <utils/eoScalarFitnessStat.h>
|
||||
#include <utils/eoAssembledFitnessStat.h>
|
||||
#include <utils/eoFDCStat.h>
|
||||
#include <utils/eoMOFitnessStat.h>
|
||||
#include <utils/eoPopStat.h>
|
||||
#include <utils/eoTimeCounter.h>
|
||||
#include <utils/eoGenCounter.h>
|
||||
|
||||
// and make_help - any better suggestion to include it?
|
||||
void make_help(eoParser & _parser);
|
||||
|
||||
#endif // !_CHECKPOINTING_
|
||||
|
||||
// Local Variables:
|
||||
// mode: C++
|
||||
// End:
|
||||
82
eo/src/utils/compatibility.h
Normal file
82
eo/src/utils/compatibility.h
Normal file
|
|
@ -0,0 +1,82 @@
|
|||
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
-----------------------------------------------------------------------------
|
||||
compatibility.h
|
||||
File to store some compiler specific stuff in. Currently handles, or
|
||||
least tries to handle the min() max() problems when using MSVC
|
||||
|
||||
|
||||
(c) Maarten Keijzer (mak@dhi.dk) and GeNeura Team, 1999, 2000
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
|
||||
*/
|
||||
|
||||
#ifndef COMPAT_H
|
||||
#define COMPAT_H
|
||||
|
||||
#include <string>
|
||||
#include <iostream>
|
||||
|
||||
#ifdef __GNUC__
|
||||
#if __GNUC__ < 3
|
||||
// check for stdlibc++v3 which does have ios_base
|
||||
#ifndef _CPP_BITS_IOSBASE_H
|
||||
typedef ios ios_base; // not currently defined in GCC
|
||||
#endif
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#if defined(_MSC_VER) && (_MSC_VER < 1300)
|
||||
/*
|
||||
Maarten: added this code here because Mirkosoft has the
|
||||
nasty habit of #define min and max in stdlib.h (and windows.h)
|
||||
I'm trying to undo this horrible macro magic (microsoft yet macrohard)
|
||||
here. Sure hope it works
|
||||
Olivier: this has been removed in .NET :) One step more standard...
|
||||
*/
|
||||
#pragma warning(disable:4786)
|
||||
|
||||
#include <stdlib.h>
|
||||
|
||||
#ifdef min
|
||||
#undef min
|
||||
#undef max // as they come in std::pairs
|
||||
#endif
|
||||
|
||||
// add min and max to std...
|
||||
namespace std
|
||||
{
|
||||
template <class T> const T& min(const T& a, const T& b)
|
||||
{
|
||||
if(a < b)
|
||||
return a;
|
||||
// else
|
||||
return b;
|
||||
}
|
||||
|
||||
template <class T> const T& max(const T& a, const T& b)
|
||||
{
|
||||
if(a > b)
|
||||
return a;
|
||||
// else
|
||||
return b;
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
// _MSC_VER
|
||||
#endif
|
||||
117
eo/src/utils/eoAssembledFitnessStat.h
Normal file
117
eo/src/utils/eoAssembledFitnessStat.h
Normal file
|
|
@ -0,0 +1,117 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoAssembledFitnessStat.h
|
||||
// Marc Wintermantel & Oliver Koenig
|
||||
// IMES-ST@ETHZ.CH
|
||||
// April 2003
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoStat.h
|
||||
// (c) Marc Schoenauer, Maarten Keijzer and GeNeura Team, 2000
|
||||
/*
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
|
||||
Marc.Schoenauer@polytechnique.fr
|
||||
mkeijzer@dhi.dk
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _eoAssembledFitnessStat_h
|
||||
#define _eoAssembledFitnessStat_h
|
||||
|
||||
#include <utils/eoStat.h>
|
||||
#include <eoScalarFitnessAssembled.h>
|
||||
|
||||
/** @addtogroup Stats
|
||||
* @{
|
||||
*/
|
||||
|
||||
/**
|
||||
Average fitness values of a population, where the fitness is
|
||||
of type eoScalarAssembledFitness. Specify in the constructor,
|
||||
for which fitness term (index) the average should be evaluated.
|
||||
Only values of object where the failed boolean = false is set are counted.
|
||||
*/
|
||||
template <class EOT>
|
||||
class eoAssembledFitnessAverageStat : public eoStat<EOT, double>
|
||||
{
|
||||
public :
|
||||
|
||||
using eoStat<EOT, double>::value;
|
||||
|
||||
typedef typename EOT::Fitness Fitness;
|
||||
|
||||
|
||||
eoAssembledFitnessAverageStat(unsigned _whichTerm=0, std::string _description = "Average Fitness")
|
||||
: eoStat<EOT, double>(Fitness(), _description), whichFitnessTerm(_whichTerm)
|
||||
{}
|
||||
|
||||
|
||||
virtual void operator()(const eoPop<EOT>& _pop) {
|
||||
if( whichFitnessTerm >= _pop[0].fitness().size() )
|
||||
throw std::logic_error("Fitness term requested out of range");
|
||||
|
||||
double result =0.0;
|
||||
unsigned count = 0;
|
||||
for (typename eoPop<EOT>::const_iterator it = _pop.begin(); it != _pop.end(); ++it){
|
||||
if ( it->fitness().failed == false ){
|
||||
result+= it->fitness()[whichFitnessTerm];
|
||||
++count;
|
||||
}
|
||||
}
|
||||
|
||||
value() = result / (double) count;
|
||||
}
|
||||
|
||||
private:
|
||||
// Store an index of the fitness term to be evaluated in eoScalarFitnessAssembled
|
||||
unsigned whichFitnessTerm;
|
||||
};
|
||||
|
||||
/**
|
||||
Fitness values of best individuum in a population, where the fitness is
|
||||
of type eoScalarAssembledFitness. Specify in the constructor,
|
||||
for which fitness term (index) the value should be evaluated.
|
||||
*/
|
||||
template <class EOT>
|
||||
class eoAssembledFitnessBestStat : public eoStat<EOT, double>
|
||||
{
|
||||
public:
|
||||
|
||||
using eoStat<EOT, double>::value;
|
||||
|
||||
typedef typename EOT::Fitness Fitness;
|
||||
|
||||
eoAssembledFitnessBestStat(unsigned _whichTerm=0, std::string _description = "Best Fitness")
|
||||
: eoStat<EOT, double>(Fitness(), _description), whichFitnessTerm(_whichTerm)
|
||||
{}
|
||||
|
||||
virtual void operator()(const eoPop<EOT>& _pop) {
|
||||
if( whichFitnessTerm >= _pop[0].fitness().size() )
|
||||
throw std::logic_error("Fitness term requested out of range");
|
||||
|
||||
value() = _pop.best_element().fitness()[whichFitnessTerm];
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
// Store an index of the fitness term to be evaluated in eoScalarFitnessAssembled
|
||||
unsigned whichFitnessTerm;
|
||||
};
|
||||
|
||||
/** @} */
|
||||
#endif
|
||||
183
eo/src/utils/eoCheckPoint.h
Normal file
183
eo/src/utils/eoCheckPoint.h
Normal file
|
|
@ -0,0 +1,183 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoCheckPoint.h
|
||||
// (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2000
|
||||
/*
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
|
||||
Marc.Schoenauer@polytechnique.fr
|
||||
mkeijzer@dhi.dk
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _eoCheckPoint_h
|
||||
#define _eoCheckPoint_h
|
||||
|
||||
#include <eoContinue.h>
|
||||
#include <utils/eoUpdater.h>
|
||||
#include <utils/eoMonitor.h>
|
||||
#include <utils/eoStat.h>
|
||||
|
||||
/** @defgroup Checkpoints Checkpointing
|
||||
*
|
||||
* Checkpoints are supposed to be called perodically (for instance at each generation) and
|
||||
* will call every functors you put in them.
|
||||
*
|
||||
* Use them with eoStats, eoUpdater and eoMonitor to get statistics at each generation.
|
||||
*
|
||||
* @see eoStat
|
||||
* @see eoMonitor
|
||||
* @see eoUpdater
|
||||
*
|
||||
* Example of a test program using checkpointing:
|
||||
* @include t-eoCheckpointing.cpp
|
||||
*
|
||||
* @ingroup Utilities
|
||||
*
|
||||
* @{
|
||||
*/
|
||||
|
||||
/** eoCheckPoint is a container class.
|
||||
It contains std::vectors of (pointers to)
|
||||
eoContinue (modif. MS July 16. 2002)
|
||||
eoStats, eoUpdater and eoMonitor
|
||||
it is an eoContinue, so its operator() will be called every generation -
|
||||
and will return the contained-combined-eoContinue result
|
||||
but before that it will call in turn every single
|
||||
{statistics, updaters, monitors} that it has been given,
|
||||
and after that, if stopping, all lastCall methods of the above.
|
||||
*/
|
||||
template <class EOT>
|
||||
class eoCheckPoint : public eoContinue<EOT>
|
||||
{
|
||||
public :
|
||||
|
||||
eoCheckPoint(eoContinue<EOT>& _cont)
|
||||
{
|
||||
continuators.push_back(&_cont);
|
||||
}
|
||||
|
||||
bool operator()(const eoPop<EOT>& _pop);
|
||||
|
||||
void add(eoContinue<EOT>& _cont) { continuators.push_back(&_cont); }
|
||||
void add(eoSortedStatBase<EOT>& _stat) { sorted.push_back(&_stat); }
|
||||
void add(eoStatBase<EOT>& _stat) { stats.push_back(&_stat); }
|
||||
void add(eoMonitor& _mon) { monitors.push_back(&_mon); }
|
||||
void add(eoUpdater& _upd) { updaters.push_back(&_upd); }
|
||||
|
||||
virtual std::string className(void) const { return "eoCheckPoint"; }
|
||||
std::string allClassNames() const ;
|
||||
|
||||
private :
|
||||
|
||||
std::vector<eoContinue<EOT>*> continuators;
|
||||
std::vector<eoSortedStatBase<EOT>*> sorted;
|
||||
std::vector<eoStatBase<EOT>*> stats;
|
||||
std::vector<eoMonitor*> monitors;
|
||||
std::vector<eoUpdater*> updaters;
|
||||
};
|
||||
|
||||
template <class EOT>
|
||||
bool eoCheckPoint<EOT>::operator()(const eoPop<EOT>& _pop)
|
||||
{
|
||||
unsigned i;
|
||||
|
||||
std::vector<const EOT*> sorted_pop;
|
||||
if (!sorted.empty())
|
||||
{
|
||||
_pop.sort(sorted_pop);
|
||||
|
||||
for (i = 0; i < sorted.size(); ++i)
|
||||
{
|
||||
(*sorted[i])(sorted_pop);
|
||||
}
|
||||
}
|
||||
|
||||
for (i = 0; i < stats.size(); ++i)
|
||||
(*stats[i])(_pop);
|
||||
|
||||
for (i = 0; i < updaters.size(); ++i)
|
||||
(*updaters[i])();
|
||||
|
||||
for (i = 0; i < monitors.size(); ++i)
|
||||
(*monitors[i])();
|
||||
|
||||
bool bContinue = true;
|
||||
for (i = 0; i < continuators.size(); ++i)
|
||||
if ( !(*continuators[i])(_pop) )
|
||||
bContinue = false;
|
||||
|
||||
if (! bContinue) // we're going to stop: lastCall, gentlemen
|
||||
{
|
||||
if (!sorted.empty())
|
||||
{
|
||||
for (i = 0; i < sorted.size(); ++i)
|
||||
{
|
||||
sorted[i]->lastCall(sorted_pop);
|
||||
}
|
||||
}
|
||||
for (i = 0; i < stats.size(); ++i)
|
||||
stats[i]->lastCall(_pop);
|
||||
|
||||
for (i = 0; i < updaters.size(); ++i)
|
||||
updaters[i]->lastCall();
|
||||
|
||||
for (i = 0; i < monitors.size(); ++i)
|
||||
monitors[i]->lastCall();
|
||||
}
|
||||
return bContinue;
|
||||
}
|
||||
|
||||
/** returns a string with all className()
|
||||
* of data separated with "\n" (for debugging)
|
||||
*/
|
||||
template <class EOT>
|
||||
std::string eoCheckPoint<EOT>::allClassNames() const
|
||||
{
|
||||
unsigned i;
|
||||
std::string s = "\n" + className() + "\n";
|
||||
|
||||
s += "Sorted Stats\n";
|
||||
for (i = 0; i < sorted.size(); ++i)
|
||||
s += sorted[i]->className() + "\n";
|
||||
s += "\n";
|
||||
|
||||
s += "Stats\n";
|
||||
for (i = 0; i < stats.size(); ++i)
|
||||
s += stats[i]->className() + "\n";
|
||||
s += "\n";
|
||||
|
||||
s += "Updaters\n";
|
||||
for (i = 0; i < updaters.size(); ++i)
|
||||
s += updaters[i]->className() + "\n";
|
||||
s += "\n";
|
||||
|
||||
s += "Monitors\n";
|
||||
for (i = 0; i < monitors.size(); ++i)
|
||||
s += monitors[i]->className() + "\n";
|
||||
s += "\n";
|
||||
|
||||
s += "Continuators\n";
|
||||
for (i = 0; i < continuators.size(); ++i)
|
||||
s += continuators[i]->className() + "\n";
|
||||
s += "\n";
|
||||
|
||||
return s;
|
||||
}
|
||||
|
||||
/** @} */
|
||||
#endif
|
||||
11
eo/src/utils/eoData.cpp
Normal file
11
eo/src/utils/eoData.cpp
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
// Copyright (C) 2005 Jochen Küpper <jochen@fhi-berlin.mpg.de>
|
||||
|
||||
|
||||
#include "eoData.h"
|
||||
|
||||
|
||||
|
||||
// Local Variables:
|
||||
// c-file-style: "Stroustrup"
|
||||
// fill-column: 80
|
||||
// End:
|
||||
47
eo/src/utils/eoData.h
Normal file
47
eo/src/utils/eoData.h
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
-----------------------------------------------------------------------------
|
||||
eoData.h
|
||||
|
||||
(c) GeNeura Team & Maarten Keijzer, 1998, 1999, 2000
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
|
||||
*/
|
||||
|
||||
#ifndef EODATA_H
|
||||
#define EODATA_H
|
||||
|
||||
#ifndef _MSC_VER
|
||||
#include <math.h>
|
||||
#define _isnan isnan
|
||||
#endif
|
||||
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// some defines to make things easier to get at first sight
|
||||
|
||||
// to be used in selection / replacement procedures to indicate whether
|
||||
// the argument (rate, a double) shoudl be treated as a rate (number=rate*popSize)
|
||||
// or as an absolute integer (number=rate regardless of popsize).
|
||||
// the default value shoudl ALWAYS be true (eo_as_a_rate).
|
||||
//
|
||||
// this construct is mandatory because in some cases you might not know the
|
||||
// population size that will enter the replacement for instance - so you
|
||||
// cannot simply have a pre-computed (double) rate of 1/popSize
|
||||
#define eo_is_a_rate true
|
||||
#define eo_is_an_integer false
|
||||
|
||||
#endif
|
||||
104
eo/src/utils/eoDistance.h
Normal file
104
eo/src/utils/eoDistance.h
Normal file
|
|
@ -0,0 +1,104 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoDistance.h
|
||||
// (c) GeNeura Team, 1998, Marc Schoenauer 2001
|
||||
/*
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
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 _eoDistance_H
|
||||
#define _eoDistance_H
|
||||
|
||||
#include <eoFunctor.h>
|
||||
|
||||
/** @addtogroup Stats
|
||||
* @{
|
||||
* */
|
||||
|
||||
/**
|
||||
This is a generic class for distance functors:
|
||||
takes 2 things and returns a double
|
||||
*/
|
||||
template< class EOT >
|
||||
class eoDistance : public eoBF<const EOT &, const EOT &, double>
|
||||
{};
|
||||
|
||||
|
||||
/**
|
||||
This is a generic class for Euclidain distance (L2 norm) computation:
|
||||
assumes the 2 things are std::vectors of something that is double-castable
|
||||
*/
|
||||
template< class EOT >
|
||||
class eoQuadDistance : public eoDistance<EOT>
|
||||
{
|
||||
public:
|
||||
double operator()(const EOT & _v1, const EOT & _v2)
|
||||
{
|
||||
double sum=0.0;
|
||||
for (unsigned i=0; i<_v1.size(); i++)
|
||||
{
|
||||
double r = static_cast<double> (_v1[i]) - static_cast<double> (_v2[i]);
|
||||
sum += r*r;
|
||||
}
|
||||
return sqrt(sum);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
This is a generic class for L1 distance computation:
|
||||
assumes the 2 things are std::vectors of something
|
||||
that is double-castable
|
||||
For bitstrings, this is the Hamming distance
|
||||
*/
|
||||
template< class EOT >
|
||||
class eoHammingDistance : public eoDistance<EOT>
|
||||
{
|
||||
public:
|
||||
double operator()(const EOT & _v1, const EOT & _v2)
|
||||
{
|
||||
double sum=0.0;
|
||||
for (unsigned i=0; i<_v1.size(); i++)
|
||||
{
|
||||
double r = static_cast<double> (_v1[i]) - static_cast<double> (_v2[i]);
|
||||
sum += fabs(r);
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
};
|
||||
|
||||
/* this distance measures the difference in fitness
|
||||
* I am not sure it can be of any use, though ...
|
||||
* except for some testing
|
||||
*/
|
||||
template< class EOT >
|
||||
class eoFitnessDistance : public eoDistance<EOT>
|
||||
{
|
||||
public:
|
||||
double operator()(const EOT & _v1, const EOT & _v2)
|
||||
{
|
||||
double d = _v1.fitness() - _v2.fitness();
|
||||
return sqrt(d*d);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/** @} */
|
||||
|
||||
#endif
|
||||
144
eo/src/utils/eoFDCStat.h
Normal file
144
eo/src/utils/eoFDCStat.h
Normal file
|
|
@ -0,0 +1,144 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoFDCStat.h
|
||||
// (c) Marc Schoenauer, Maarten Keijzer and GeNeura Team, 2000, 2001
|
||||
/*
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
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
|
||||
mkeijzer@dhi.dk
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _eoFDCStat_h
|
||||
#define _eoFDCStat_h
|
||||
|
||||
#include <utils/eoStat.h>
|
||||
#include <utils/eoDistance.h>
|
||||
#include <utils/eoFileSnapshot.h>
|
||||
|
||||
/**
|
||||
The Fitness Distance Correlation computation.
|
||||
|
||||
Stores the values into eoValueParam<EOT,double>
|
||||
so they can be snapshot by some eoGnuplotSnapshot ...
|
||||
|
||||
@ingroup Stats
|
||||
*/
|
||||
template <class EOT>
|
||||
class eoFDCStat : public eoStat<EOT, double>
|
||||
{
|
||||
public:
|
||||
|
||||
using eoStat<EOT, double>::value;
|
||||
|
||||
/** Ctor without the optimum */
|
||||
eoFDCStat(eoDistance<EOT> & _dist, std::string _description = "FDC") :
|
||||
eoStat<EOT,double>(0, _description), dist(_dist), boolOpt(false) {}
|
||||
|
||||
/** Ctor with the optimum
|
||||
*/
|
||||
eoFDCStat(eoDistance<EOT> & _dist, EOT & _theBest,
|
||||
std::string _description = "FDC") :
|
||||
eoStat<EOT,double>(0, _description), dist(_dist),
|
||||
theBest(_theBest), boolOpt(true) {}
|
||||
|
||||
/** Compute the FDC - either from best in pop, or from absolute best
|
||||
* if it was passed in the constructor
|
||||
*/
|
||||
virtual void operator()(const eoPop<EOT>& _pop)
|
||||
{
|
||||
unsigned i;
|
||||
if (!boolOpt) // take the local best
|
||||
theBest = _pop.best_element();
|
||||
unsigned int pSize = _pop.size();
|
||||
distToBest.value().resize(pSize);
|
||||
fitnesses.value().resize(pSize);
|
||||
double sumFit = 0.0, sumDist = 0.0;
|
||||
for (i=0; i<pSize; i++)
|
||||
{
|
||||
sumDist += (distToBest.value()[i] = dist(_pop[i], theBest));
|
||||
sumFit += (fitnesses.value()[i] = _pop[i].fitness());
|
||||
}
|
||||
// now the FDC coefficient
|
||||
double avgDist = sumDist/pSize;
|
||||
double avgFit = sumFit/pSize;
|
||||
sumDist = sumFit = 0.0;
|
||||
double num = 0.0;
|
||||
for (i=0; i<pSize; i++)
|
||||
{
|
||||
double devDist = distToBest.value()[i] - avgDist ;
|
||||
double devFit = fitnesses.value()[i] - avgFit ;
|
||||
sumDist += devDist*devDist;
|
||||
sumFit += devFit * devFit;
|
||||
num += devDist * devFit ;
|
||||
}
|
||||
value() = num/(sqrt(sumDist)*sqrt(sumFit));
|
||||
}
|
||||
|
||||
/** accessors to the private eoValueParam<std::vector<double> >
|
||||
*/
|
||||
const eoValueParam<std::vector<double> > & theDist()
|
||||
{ return distToBest; }
|
||||
const eoValueParam<std::vector<double> > & theFit()
|
||||
{ return fitnesses; }
|
||||
|
||||
|
||||
private:
|
||||
eoDistance<EOT> & dist;
|
||||
EOT theBest;
|
||||
bool boolOpt; // whether the best is known or not
|
||||
eoValueParam<std::vector<double> > distToBest;
|
||||
eoValueParam<std::vector<double> > fitnesses;
|
||||
};
|
||||
|
||||
/** Specific class for FDCStat monitoring:
|
||||
* As I failed to have FDC stat as an eoStat, this is the trick
|
||||
* to put the 2 eoParam<std::vector<double> > into a monitor
|
||||
* This class does nothing else.
|
||||
|
||||
@ingroup Stats
|
||||
*/
|
||||
template <class EOT>
|
||||
class eoFDCFileSnapshot : public eoFileSnapshot // is an eoMonitor
|
||||
{
|
||||
public:
|
||||
/** Ctor: in addition to the parameters of the ctor of an eoFileSnapshot
|
||||
we need here an eoFDCStat. The 2 std::vectors (distances to optimum
|
||||
and fitnesses) are added to the monitor so they can be processed
|
||||
later to a file - and eventually by gnuplot
|
||||
*/
|
||||
eoFDCFileSnapshot(eoFDCStat<EOT> & _FDCstat,
|
||||
std::string _dirname = "tmpFDC", unsigned _frequency = 1,
|
||||
std::string _filename = "FDC", std::string _delim = " "):
|
||||
eoFileSnapshot(_dirname, _frequency, _filename, _delim),
|
||||
FDCstat(_FDCstat)
|
||||
{
|
||||
eoFileSnapshot::add(FDCstat.theDist());
|
||||
eoFileSnapshot::add(FDCstat.theFit());
|
||||
}
|
||||
|
||||
/** just to be sure the add method is not called further
|
||||
*/
|
||||
virtual void add(const eoParam& _param)
|
||||
{ throw std::runtime_error("eoFDCFileSnapshot::add(). Trying to add stats to an eoFDCFileSnapshot"); }
|
||||
|
||||
private:
|
||||
eoFDCStat<EOT> & FDCstat;
|
||||
};
|
||||
|
||||
#endif
|
||||
66
eo/src/utils/eoFeasibleRatioStat.h
Normal file
66
eo/src/utils/eoFeasibleRatioStat.h
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
/*
|
||||
|
||||
(c) 2010 Thales group
|
||||
|
||||
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; version 2
|
||||
of the License.
|
||||
|
||||
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: http://eodev.sourceforge.net
|
||||
|
||||
Authors:
|
||||
Johann Dréo <johann.dreo@thalesgroup.com>
|
||||
|
||||
*/
|
||||
|
||||
#ifndef _eoFeasibleRatioStat_h_
|
||||
#define _eoFeasibleRatioStat_h_
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
#include <eoDualFitness.h>
|
||||
#include <utils/eoLogger.h>
|
||||
|
||||
#include "eoStat.h"
|
||||
|
||||
/** Ratio of the number of individuals with a feasible dual fitness in the population (@see eoDualFitness)
|
||||
*
|
||||
* @ingroup Stats
|
||||
*/
|
||||
template<class EOT>
|
||||
class eoFeasibleRatioStat : public eoStat< EOT, double >
|
||||
{
|
||||
public:
|
||||
using eoStat<EOT, double>::value;
|
||||
|
||||
eoFeasibleRatioStat( std::string description = "FeasibleRatio" ) : eoStat<EOT,double>( 0.0, description ) {}
|
||||
|
||||
virtual void operator()( const eoPop<EOT> & pop )
|
||||
{
|
||||
#ifndef NDEBUG
|
||||
assert( pop.size() > 0 );
|
||||
|
||||
double count = static_cast<double>( std::count_if( pop.begin(), pop.end(), eoIsFeasible<EOT> ) );
|
||||
double size = static_cast<double>( pop.size() );
|
||||
double ratio = count/size;
|
||||
eo::log << eo::xdebug << "eoFeasibleRatioStat: " << count << " / " << size << " = " << ratio << std::endl;
|
||||
value() = ratio;
|
||||
#else
|
||||
value() = static_cast<double>( std::count_if( pop.begin(), pop.end(), eoIsFeasible<EOT> ) ) / static_cast<double>( pop.size() );
|
||||
#endif
|
||||
}
|
||||
|
||||
virtual std::string className(void) const { return "eoFeasibleRatioStat"; }
|
||||
};
|
||||
|
||||
#endif // _eoFeasibleRatioStat_h_
|
||||
89
eo/src/utils/eoFileMonitor.cpp
Normal file
89
eo/src/utils/eoFileMonitor.cpp
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
#ifdef _MSC_VER
|
||||
// to avoid long name warnings
|
||||
#pragma warning(disable:4786)
|
||||
#endif
|
||||
|
||||
#include <iostream>
|
||||
#include <fstream>
|
||||
#include <stdexcept>
|
||||
|
||||
#include <utils/eoFileMonitor.h>
|
||||
#include <utils/compatibility.h>
|
||||
#include <utils/eoParam.h>
|
||||
|
||||
using namespace std;
|
||||
|
||||
void eoFileMonitor::printHeader(std::ostream& os)
|
||||
{
|
||||
iterator it = vec.begin();
|
||||
|
||||
os << (*it)->longName();
|
||||
|
||||
++it;
|
||||
|
||||
for (; it != vec.end(); ++it)
|
||||
{
|
||||
// use the longName of the eoParam for the header
|
||||
os << delim.c_str() << (*it)->longName();
|
||||
}
|
||||
os << std::endl;
|
||||
}
|
||||
|
||||
void eoFileMonitor::printHeader()
|
||||
{
|
||||
// create file
|
||||
ofstream os(filename.c_str());
|
||||
|
||||
if (!os)
|
||||
{
|
||||
string str = "eoFileMonitor could not open: " + filename;
|
||||
throw runtime_error(str);
|
||||
}
|
||||
|
||||
printHeader(os);
|
||||
}
|
||||
|
||||
eoMonitor& eoFileMonitor::operator()(void)
|
||||
{
|
||||
ofstream os(filename.c_str(),
|
||||
overwrite ?
|
||||
ios_base::out|ios_base::trunc // truncate
|
||||
:
|
||||
ios_base::out|ios_base::app // append
|
||||
);
|
||||
|
||||
if (!os)
|
||||
{
|
||||
string str = "eoFileMonitor could not write to: " + filename;
|
||||
throw runtime_error(str);
|
||||
}
|
||||
|
||||
if (
|
||||
header // we want to write headers
|
||||
&& firstcall // we do not want to write headers twice
|
||||
&& !keep // if we append to an existing file, headers are useless
|
||||
&& !overwrite // we do not want to write headers if the file is to be overwriten
|
||||
) {
|
||||
printHeader();
|
||||
firstcall = false;
|
||||
}
|
||||
|
||||
return operator()(os);
|
||||
}
|
||||
|
||||
eoMonitor& eoFileMonitor::operator()(std::ostream& os)
|
||||
{
|
||||
|
||||
iterator it = vec.begin();
|
||||
|
||||
os << (*it)->getValue();
|
||||
|
||||
for(++it; it != vec.end(); ++it)
|
||||
{
|
||||
os << delim.c_str() << (*it)->getValue();
|
||||
}
|
||||
|
||||
os << std::endl;
|
||||
|
||||
return *this;
|
||||
}
|
||||
121
eo/src/utils/eoFileMonitor.h
Normal file
121
eo/src/utils/eoFileMonitor.h
Normal file
|
|
@ -0,0 +1,121 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoFileMonitor.h
|
||||
// (c) Marc Schoenauer, Maarten Keijzer and GeNeura Team, 2000
|
||||
/*
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
|
||||
Marc.Schoenauer@polytechnique.fr
|
||||
mkeijzer@dhi.dk
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef EO_eoFileMonitor_h
|
||||
#define EO_eoFileMonitor_h
|
||||
|
||||
#include <string>
|
||||
#include <fstream>
|
||||
#include <stdexcept>
|
||||
|
||||
#include "utils/eoMonitor.h"
|
||||
#include "eoObject.h"
|
||||
|
||||
|
||||
/** Prints statistics to file
|
||||
|
||||
Modified the default behavior, so that it erases existing files. Can
|
||||
be modified in the ctor.
|
||||
|
||||
@version MS 25/11/00
|
||||
@ingroup Monitors
|
||||
*/
|
||||
class eoFileMonitor : public eoMonitor
|
||||
{
|
||||
public :
|
||||
|
||||
/*! Constructor
|
||||
*
|
||||
* Try to create the file in writing mode, erasing it if asked.
|
||||
*
|
||||
* @param _filename complete filename to write to
|
||||
* @param _delim delimiter string to use between each item of the registered vector (e.g. of eoStats)
|
||||
* @param _keep_existing if true, overwrite any existing file with the same name prior to any output
|
||||
* @param _header print the header (with the descriptions of registered eoStats) at the beginning of the file (WARNING: true will discards header printing)
|
||||
* @param _overwrite if true, overwrite the existing file
|
||||
*/
|
||||
eoFileMonitor(
|
||||
std::string _filename,
|
||||
std::string _delim = " ",
|
||||
bool _keep_existing = false,
|
||||
bool _header = false,
|
||||
bool _overwrite = false
|
||||
)
|
||||
: filename(_filename),
|
||||
delim(_delim),
|
||||
keep(_keep_existing),
|
||||
header(_header),
|
||||
firstcall(true),
|
||||
overwrite(_overwrite)
|
||||
{
|
||||
if (!_keep_existing) {
|
||||
std::ofstream os (filename.c_str ());
|
||||
|
||||
if (!os) {
|
||||
std::string str = "Error, eoFileMonitor could not open: " + filename;
|
||||
throw std::runtime_error (str);
|
||||
}
|
||||
} // if ! keep
|
||||
}
|
||||
|
||||
//! Called first, try to open the file in append mode and write the header if asked
|
||||
virtual eoMonitor& operator()(void);
|
||||
|
||||
/*! Main call, normally called at each generation.
|
||||
Write the content of the registered vector into the file, each item being separated by delim
|
||||
*/
|
||||
virtual eoMonitor& operator()(std::ostream& os);
|
||||
|
||||
//! Try to open the file, and then call printHeader(file)
|
||||
void printHeader(void);
|
||||
|
||||
//! Print long names of the registered items, separated by delim.
|
||||
virtual void printHeader(std::ostream& os);
|
||||
|
||||
virtual std::string getFileName() { return filename;}
|
||||
|
||||
private :
|
||||
|
||||
//! complete filename to write to
|
||||
std::string filename;
|
||||
|
||||
//! delimiter to use between each write
|
||||
std::string delim;
|
||||
|
||||
//! should we append or create a new file
|
||||
bool keep;
|
||||
|
||||
//! printing header at begin of file?
|
||||
bool header;
|
||||
|
||||
//! flag to avoid calling twice operator()(void)
|
||||
bool firstcall;
|
||||
|
||||
//! erase the entire file prior to writing in it (mode eos_base::
|
||||
bool overwrite;
|
||||
};
|
||||
|
||||
#endif
|
||||
200
eo/src/utils/eoFileSnapshot.h
Normal file
200
eo/src/utils/eoFileSnapshot.h
Normal file
|
|
@ -0,0 +1,200 @@
|
|||
//-----------------------------------------------------------------------------
|
||||
// eoFileSnapshot.h
|
||||
// (c) Marc Schoenauer, Maarten Keijzer and GeNeura Team, 2001
|
||||
/*
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
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
|
||||
mkeijzer@dhi.dk
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _eoFileSnapshot_h
|
||||
#define _eoFileSnapshot_h
|
||||
|
||||
#include <cstdlib>
|
||||
#include <fstream>
|
||||
#include <string>
|
||||
|
||||
#include <utils/eoParam.h>
|
||||
#include <utils/eoMonitor.h>
|
||||
#include <eoObject.h>
|
||||
|
||||
|
||||
/**
|
||||
Prints snapshots of fitnesses to a (new) file every N generations
|
||||
|
||||
Assumes that the parameters that are passed to the monitor
|
||||
(method add in eoMonitor.h) are eoValueParam<std::vector<double> > of same size.
|
||||
|
||||
A dir is created and one file per snapshot is created there -
|
||||
so you can later generate a movie!
|
||||
|
||||
@todo The counter is handled internally, but this should be changed
|
||||
so that you can pass e.g. an evalcounter (minor)
|
||||
|
||||
I failed to templatize everything so that it can handle eoParam<std::vector<T> >
|
||||
for any type T, simply calling their getValue method ...
|
||||
|
||||
@ingroup Monitors
|
||||
*/
|
||||
class eoFileSnapshot : public eoMonitor
|
||||
{
|
||||
public :
|
||||
typedef std::vector<double> vDouble;
|
||||
typedef eoValueParam<std::vector<double> > vDoubleParam;
|
||||
|
||||
eoFileSnapshot(std::string _dirname, unsigned _frequency = 1, std::string _filename = "gen",
|
||||
std::string _delim = " ", unsigned _counter = 0, bool _rmFiles = true):
|
||||
dirname(_dirname), frequency(_frequency),
|
||||
filename(_filename), delim(_delim), counter(_counter), boolChanged(true)
|
||||
{
|
||||
std::string s = "test -d " + dirname;
|
||||
|
||||
int res = system(s.c_str());
|
||||
// test for (unlikely) errors
|
||||
if ( (res==-1) || (res==127) )
|
||||
throw std::runtime_error("Problem executing test of dir in eoFileSnapshot");
|
||||
// now make sure there is a dir without any genXXX file in it
|
||||
if (res) // no dir present
|
||||
{
|
||||
s = std::string("mkdir ")+dirname;
|
||||
}
|
||||
else if (!res && _rmFiles)
|
||||
{
|
||||
s = std::string("/bin/rm ")+dirname+ "/" + filename + "*";
|
||||
}
|
||||
else
|
||||
s = " ";
|
||||
|
||||
res=system(s.c_str());
|
||||
// all done
|
||||
}
|
||||
|
||||
/** accessor: has something changed (for gnuplot subclass)
|
||||
*/
|
||||
virtual bool hasChanged() {return boolChanged;}
|
||||
|
||||
/** accessor to the counter: needed by the gnuplot subclass
|
||||
*/
|
||||
unsigned getCounter() {return counter;}
|
||||
|
||||
/** accessor to the current filename: needed by the gnuplot subclass
|
||||
*/
|
||||
std::string getFileName() {return currentFileName;}
|
||||
|
||||
/** sets the current filename depending on the counter
|
||||
*/
|
||||
void setCurrentFileName()
|
||||
{
|
||||
std::ostringstream oscount;
|
||||
oscount << counter;
|
||||
currentFileName = dirname + "/" + filename + oscount.str();
|
||||
}
|
||||
|
||||
/** The operator(void): opens the std::ostream and calls the write method
|
||||
*/
|
||||
eoMonitor& operator()(void)
|
||||
{
|
||||
if (counter % frequency)
|
||||
{
|
||||
boolChanged = false; // subclass with gnuplot will do nothing
|
||||
counter++;
|
||||
return (*this);
|
||||
}
|
||||
counter++;
|
||||
boolChanged = true;
|
||||
setCurrentFileName();
|
||||
std::ofstream os(currentFileName.c_str());
|
||||
|
||||
if (!os)
|
||||
{
|
||||
std::string str = "eoFileSnapshot: Could not open " + currentFileName;
|
||||
throw std::runtime_error(str);
|
||||
}
|
||||
|
||||
return operator()(os);
|
||||
}
|
||||
|
||||
/** The operator(): write on an std::ostream
|
||||
*/
|
||||
eoMonitor& operator()(std::ostream& _os)
|
||||
{
|
||||
const eoValueParam<std::vector<double> > * ptParam =
|
||||
static_cast<const eoValueParam<std::vector<double> >* >(vec[0]);
|
||||
|
||||
const std::vector<double> v = ptParam->value();
|
||||
if (vec.size() == 1) // only one std::vector: -> add number in front
|
||||
{
|
||||
for (unsigned k=0; k<v.size(); k++)
|
||||
_os << k << " " << v[k] << "\n" ;
|
||||
}
|
||||
else // need to get all other std::vectors
|
||||
{
|
||||
std::vector<std::vector<double> > vv(vec.size());
|
||||
vv[0]=v;
|
||||
for (unsigned i=1; i<vec.size(); i++)
|
||||
{
|
||||
ptParam = static_cast<const eoValueParam<std::vector<double> >* >(vec[1]);
|
||||
vv[i] = ptParam->value();
|
||||
if (vv[i].size() != v.size())
|
||||
throw std::runtime_error("Dimension error in eoSnapshotMonitor");
|
||||
}
|
||||
for (unsigned k=0; k<v.size(); k++)
|
||||
{
|
||||
for (unsigned i=0; i<vec.size(); i++)
|
||||
_os << vv[i][k] << " " ;
|
||||
_os << "\n";
|
||||
}
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
virtual const std::string getDirName() // for eoGnuPlot
|
||||
{ return dirname;}
|
||||
virtual const std::string baseFileName() // the title for eoGnuPlot
|
||||
{ return filename;}
|
||||
|
||||
/// add checks whether it is a std::vector of doubles
|
||||
void add(const eoParam& _param)
|
||||
{
|
||||
if (!dynamic_cast<const eoValueParam<std::vector<double> >*>(&_param))
|
||||
{
|
||||
throw std::logic_error(std::string("eoFileSnapshot: I can only monitor std::vectors of doubles, sorry. The offending parameter name = ") + _param.longName());
|
||||
}
|
||||
eoMonitor::add(_param);
|
||||
}
|
||||
|
||||
private :
|
||||
std::string dirname;
|
||||
unsigned frequency;
|
||||
std::string filename;
|
||||
std::string delim;
|
||||
unsigned int counter;
|
||||
std::string currentFileName;
|
||||
bool boolChanged;
|
||||
};
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
// Local Variables:
|
||||
// coding: iso-8859-1
|
||||
// mode: C++
|
||||
// c-file-offsets: ((c . 0))
|
||||
// c-file-style: "Stroustrup"
|
||||
// fill-column: 80
|
||||
// End:
|
||||
80
eo/src/utils/eoFuncPtrStat.h
Normal file
80
eo/src/utils/eoFuncPtrStat.h
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
#ifndef eoFuncPtrStat_h
|
||||
#define eoFuncPtrStat_h
|
||||
|
||||
#include <eoFunctorStore.h>
|
||||
#include <utils/eoStat.h>
|
||||
|
||||
|
||||
|
||||
/** Wrapper to turn any stand-alone function and into an eoStat.
|
||||
*
|
||||
* The function should take an eoPop as argument.
|
||||
*
|
||||
* @ingroup Stats
|
||||
*/
|
||||
template <class EOT, class T>
|
||||
class eoFuncPtrStat : public eoStat<EOT, T>
|
||||
{
|
||||
public :
|
||||
typedef T (*func_t)(const eoPop<EOT>&);
|
||||
|
||||
|
||||
eoFuncPtrStat(func_t f, std::string _description = "func_ptr")
|
||||
: eoStat<EOT, T>(T(), _description), func(f)
|
||||
{}
|
||||
|
||||
using eoStat<EOT, T>::value;
|
||||
|
||||
void operator()(const eoPop<EOT>& pop) {
|
||||
value() = func(pop);
|
||||
}
|
||||
|
||||
private:
|
||||
func_t func;
|
||||
};
|
||||
|
||||
/**
|
||||
* @ingroup Stats
|
||||
*/
|
||||
template <class EOT, class T>
|
||||
eoFuncPtrStat<EOT, T>& makeFuncPtrStat( T (*func)(const eoPop<EOT>&), eoFunctorStore& store, std::string description = "func") {
|
||||
return store.storeFunctor(
|
||||
new eoFuncPtrStat<EOT, T>( func, description)
|
||||
);
|
||||
}
|
||||
|
||||
/** Wrapper to turn any stand-alone function and into an eoStat.
|
||||
*
|
||||
* The function should take an eoPop as argument.
|
||||
*
|
||||
* @ingroup Stats
|
||||
*/
|
||||
template <class EOT, class T>
|
||||
class eoFunctorStat : public eoStat<EOT, T>
|
||||
{
|
||||
public :
|
||||
eoFunctorStat(eoUF< const eoPop<EOT>&, T >& f, std::string _description = "functor")
|
||||
: eoStat<EOT, T>(T(), _description), func(f)
|
||||
{}
|
||||
|
||||
using eoStat<EOT, T>::value;
|
||||
|
||||
void operator()(const eoPop<EOT>& pop) {
|
||||
value() = func(pop);
|
||||
}
|
||||
|
||||
private:
|
||||
eoUF< const eoPop<EOT>&, T >& func;
|
||||
};
|
||||
|
||||
/**
|
||||
* @ingroup Stats
|
||||
*/
|
||||
template <class EOT, class T>
|
||||
eoFunctorStat<EOT, T>& makeFunctorStat( eoUF< const eoPop<EOT>&, T >& func, eoFunctorStore& store, std::string description = "func") {
|
||||
return store.storeFunctor(
|
||||
new eoFunctorStat<EOT, T>( func, description)
|
||||
);
|
||||
}
|
||||
|
||||
#endif
|
||||
46
eo/src/utils/eoGenCounter.h
Normal file
46
eo/src/utils/eoGenCounter.h
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
/*
|
||||
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
|
||||
|
||||
(c) Thales group 2011
|
||||
|
||||
Author: johann.dreo@thalesgroup.com
|
||||
*/
|
||||
|
||||
#ifndef _eoGenCounter_h
|
||||
#define _eoGenCounter_h
|
||||
|
||||
#include <string>
|
||||
#include <utils/eoStat.h>
|
||||
|
||||
/**
|
||||
An eoStat that simply gives the current generation index
|
||||
|
||||
@ingroup Stats
|
||||
*/
|
||||
class eoGenCounter : public eoUpdater, public eoValueParam<unsigned int>
|
||||
{
|
||||
public:
|
||||
eoGenCounter( unsigned int start = 0, std::string label = "Gen" ) : eoValueParam<unsigned int>(start, label), _nb(start) {}
|
||||
|
||||
virtual void operator()()
|
||||
{
|
||||
value() = _nb++;
|
||||
}
|
||||
|
||||
private:
|
||||
unsigned int _nb;
|
||||
};
|
||||
|
||||
#endif
|
||||
99
eo/src/utils/eoGnuplot.cpp
Normal file
99
eo/src/utils/eoGnuplot.cpp
Normal file
|
|
@ -0,0 +1,99 @@
|
|||
//-----------------------------------------------------------------------------
|
||||
// (c) Marc Schoenauer, 2001
|
||||
// Copyright (C) 2005 Jochen Küpper
|
||||
/*
|
||||
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: Marc.Schoenauer@polytechnique.fr
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifdef HAVE_CONFIG_H
|
||||
#include <config.h>
|
||||
#endif
|
||||
|
||||
#include <string.h>
|
||||
#include <sstream>
|
||||
#include <stdexcept>
|
||||
|
||||
#include "eoGnuplot.h"
|
||||
|
||||
|
||||
unsigned eoGnuplot::numWindow=0;
|
||||
|
||||
|
||||
|
||||
eoGnuplot::eoGnuplot(std::string _title, std::string _extra)
|
||||
: firstTime(true)
|
||||
{
|
||||
initGnuPlot(_title, _extra);
|
||||
}
|
||||
|
||||
|
||||
|
||||
eoGnuplot::~eoGnuplot()
|
||||
{
|
||||
#ifdef HAVE_GNUPLOT
|
||||
if( gpCom ) {
|
||||
PipeComSend( gpCom, "quit\n" );
|
||||
PipeComClose( gpCom );
|
||||
gpCom =NULL;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
|
||||
void eoGnuplot::gnuplotCommand(const char *_command)
|
||||
{
|
||||
#ifdef HAVE_GNUPLOT
|
||||
if(gpCom) {
|
||||
PipeComSend( gpCom, _command );
|
||||
PipeComSend( gpCom, "\n" );
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
|
||||
void eoGnuplot::initGnuPlot(std::string _title, std::string _extra)
|
||||
{
|
||||
#ifdef HAVE_GNUPLOT
|
||||
std::ostringstream os;
|
||||
os << "250x150-0+" << 170 * numWindow++;
|
||||
char *args[6];
|
||||
args[0] = strdup( GNUPLOT_PROGRAM );
|
||||
args[1] = strdup( "-geometry" );
|
||||
args[2] = strdup( os.str().c_str());
|
||||
args[3] = strdup( "-title" );
|
||||
args[4] = strdup( _title.c_str() );
|
||||
args[5] = 0;
|
||||
gpCom = PipeComOpenArgv( GNUPLOT_PROGRAM, args );
|
||||
if(! gpCom )
|
||||
throw std::runtime_error("Cannot spawn gnuplot\n");
|
||||
else {
|
||||
PipeComSend( gpCom, "set grid\n" );
|
||||
PipeComSend( gpCom, _extra.c_str() );
|
||||
PipeComSend( gpCom, "\n" );
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
|
||||
// Local Variables:
|
||||
// c-file-style: "Stroustrup"
|
||||
// fill-column: 80
|
||||
// End:
|
||||
101
eo/src/utils/eoGnuplot.h
Normal file
101
eo/src/utils/eoGnuplot.h
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
//-----------------------------------------------------------------------------
|
||||
// eoGnuplot1DMonitor.h
|
||||
// (c) Marc Schoenauer, 2001
|
||||
/*
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
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: Marc.Schoenauer@polytechnique.fr
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
#ifndef EO_eoGnuplot_H
|
||||
#define EO_eoGnuplot_H
|
||||
|
||||
#include <string>
|
||||
|
||||
#include "pipecom.h"
|
||||
|
||||
|
||||
/** Base class for calls to gnuplot
|
||||
|
||||
This class is the abstract class that will be used by further gnuplot
|
||||
calls to plots what is already written by some eoMonitor into a file
|
||||
|
||||
@author Marc Schoenauer
|
||||
@version 0.0 (2001)
|
||||
|
||||
@ingroup Monitors
|
||||
*/
|
||||
class eoGnuplot
|
||||
{
|
||||
public:
|
||||
|
||||
/** Open pipe to Gnuplot.
|
||||
|
||||
@param _title Title for gnuplot window.
|
||||
@param _extra Extra parameters to gnuplot (default to none: "").
|
||||
*/
|
||||
eoGnuplot(std::string _title, std::string _extra = std::string(""));
|
||||
|
||||
/** Destructor
|
||||
|
||||
Close the gnuplot windows if pipe was correctly opened
|
||||
*/
|
||||
virtual ~eoGnuplot();
|
||||
|
||||
/** Class name */
|
||||
virtual std::string className() const
|
||||
{ return "eoGnuplot"; }
|
||||
|
||||
/** Send command to gnuplot */
|
||||
void gnuplotCommand(const char * _command);
|
||||
|
||||
/** Send command to gnuplot
|
||||
|
||||
@overload
|
||||
*/
|
||||
void gnuplotCommand(std::string _command)
|
||||
{ gnuplotCommand(_command.c_str()); }
|
||||
|
||||
|
||||
protected:
|
||||
|
||||
/** Initialize gnuplot
|
||||
|
||||
@param _title Title for gnuplot window.
|
||||
@param _extra Extra parameters to gnuplot.
|
||||
*/
|
||||
void initGnuPlot(std::string _title, std::string _extra);
|
||||
|
||||
/** The stats might be unknown in Ctor */
|
||||
bool firstTime;
|
||||
|
||||
/** Communication with gnuplot OK */
|
||||
PCom *gpCom;
|
||||
|
||||
/** Internal counter for gnuplot windows */
|
||||
static unsigned numWindow;
|
||||
};
|
||||
|
||||
|
||||
#endif // EO_eoGnuplot_H
|
||||
|
||||
|
||||
|
||||
// Local Variables:
|
||||
// c-file-style: "Stroustrup"
|
||||
// comment-column: 35
|
||||
// fill-column: 80
|
||||
// mode: C++
|
||||
// End:
|
||||
85
eo/src/utils/eoGnuplot1DMonitor.cpp
Normal file
85
eo/src/utils/eoGnuplot1DMonitor.cpp
Normal file
|
|
@ -0,0 +1,85 @@
|
|||
//-----------------------------------------------------------------------------
|
||||
// eoGnuplot1DMonitor.h
|
||||
// (c) Marc Schoenauer, Maarten Keijzer and GeNeura Team, 2000
|
||||
/*
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
|
||||
Marc.Schoenauer@polytechnique.fr
|
||||
mkeijzer@dhi.dk
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
|
||||
#ifdef HAVE_CONFIG_H
|
||||
#include <config.h>
|
||||
#endif
|
||||
|
||||
#include <sstream>
|
||||
|
||||
#include "utils/eoGnuplot1DMonitor.h"
|
||||
#include "utils/eoParam.h"
|
||||
|
||||
|
||||
eoMonitor& eoGnuplot1DMonitor::operator() (void)
|
||||
{
|
||||
// update file using the eoFileMonitor
|
||||
eoFileMonitor::operator()();
|
||||
#ifdef HAVE_GNUPLOT
|
||||
// sends plot order to gnuplot
|
||||
// assumes successive plots will have same nb of columns!!!
|
||||
if (firstTime)
|
||||
{
|
||||
FirstPlot();
|
||||
firstTime = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
if( gpCom ) {
|
||||
PipeComSend( gpCom, "replot\n" );
|
||||
}
|
||||
}
|
||||
#endif
|
||||
return *this;
|
||||
}
|
||||
|
||||
|
||||
|
||||
void eoGnuplot1DMonitor::FirstPlot()
|
||||
{
|
||||
if (this->vec.size() < 2)
|
||||
{
|
||||
throw std::runtime_error("Must have some stats to plot!\n");
|
||||
}
|
||||
#ifdef HAVE_GNUPLOT
|
||||
std::ostringstream os;
|
||||
os << "plot";
|
||||
for (unsigned i=1; i<this->vec.size(); i++) {
|
||||
os << " '" << getFileName().c_str() <<
|
||||
"' using 1:" << i+1 << " title '" << (this->vec[i])->longName() << "' with lines" ;
|
||||
if (i<this->vec.size()-1)
|
||||
os << ", ";
|
||||
}
|
||||
os << '\n';
|
||||
PipeComSend( gpCom, os.str().c_str());
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
|
||||
// Local Variables:
|
||||
// c-file-style: "Stroustrup"
|
||||
// fill-column: 80
|
||||
// End:
|
||||
85
eo/src/utils/eoGnuplot1DMonitor.h
Normal file
85
eo/src/utils/eoGnuplot1DMonitor.h
Normal file
|
|
@ -0,0 +1,85 @@
|
|||
//-----------------------------------------------------------------------------
|
||||
// eoGnuplot1DMonitor.h
|
||||
// (c) Marc Schoenauer, Maarten Keijzer and GeNeura Team, 2000
|
||||
/*
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
|
||||
Marc.Schoenauer@polytechnique.fr
|
||||
mkeijzer@dhi.dk
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
#ifndef EO_eoGnuplot1DMonitor_H
|
||||
#define EO_eoGnuplot1DMonitor_H
|
||||
|
||||
#include <fstream>
|
||||
#include <string>
|
||||
|
||||
#include "eoObject.h"
|
||||
#include "utils/eoFileMonitor.h"
|
||||
#include "utils/eoGnuplot.h"
|
||||
#include "utils/pipecom.h"
|
||||
|
||||
/** Plot eoStat
|
||||
|
||||
@author Marc Schoenauer
|
||||
@version 0.0 (2000)
|
||||
|
||||
This class plots through gnuplot the eoStat given as argument
|
||||
|
||||
eoGnuplot1DMonitor plots stats through gnuplot
|
||||
|
||||
Assumes that the same file is appened every so and so, and replots it
|
||||
everytime
|
||||
|
||||
@ingroup Monitors
|
||||
*/
|
||||
class eoGnuplot1DMonitor : public eoFileMonitor, public eoGnuplot
|
||||
{
|
||||
public:
|
||||
|
||||
// this "using" directive generates a compiler internal error in GCC 4.0.0 ...
|
||||
// it's been removed, and the only call to vec was replaced by this->vec in eoGnuplot1DMonitor.cpp
|
||||
// using eoMonitor::vec;
|
||||
|
||||
/** Constructor */
|
||||
eoGnuplot1DMonitor(std::string _filename, bool _top=false) :
|
||||
eoFileMonitor(_filename, " "),
|
||||
eoGnuplot(_filename,(_top?"":"set key bottom"))
|
||||
{}
|
||||
|
||||
/** Destructor */
|
||||
virtual ~eoGnuplot1DMonitor(){}
|
||||
|
||||
virtual eoMonitor& operator()();
|
||||
|
||||
virtual void FirstPlot();
|
||||
|
||||
/** Class name */
|
||||
virtual std::string className() const
|
||||
{ return "eoGnuplot1DMonitor"; }
|
||||
};
|
||||
|
||||
|
||||
#endif // EO_eoGnuplot1DMonitor_H
|
||||
|
||||
|
||||
|
||||
// Local Variables:
|
||||
// c-file-style: "Stroustrup"
|
||||
// comment-column: 35
|
||||
// fill-column: 80
|
||||
// mode: C++
|
||||
// End:
|
||||
33
eo/src/utils/eoGnuplot1DSnapshot.cpp
Normal file
33
eo/src/utils/eoGnuplot1DSnapshot.cpp
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
#ifdef HAVE_CONFIG_H
|
||||
#include <config.h>
|
||||
#endif
|
||||
|
||||
#include "eoGnuplot1DSnapshot.h"
|
||||
|
||||
|
||||
|
||||
eoMonitor& eoGnuplot1DSnapshot::operator()()
|
||||
{
|
||||
// update file using the eoFileMonitor method
|
||||
eoFileSnapshot::operator()();
|
||||
#ifdef HAVE_GNUPLOT
|
||||
// sends plot order to gnuplot
|
||||
std::ostringstream os;
|
||||
os << "set title 'Gen. " << getCounter() << "'; plot '"
|
||||
// mk: had to use getFilename().c_str(),
|
||||
// because it seems the string(stream) lib is screwed in gcc3.2
|
||||
<< getFileName().c_str() << "' notitle with points ps " << pointSize
|
||||
<< std::endl;
|
||||
PipeComSend(gpCom, os.str().c_str());
|
||||
#endif
|
||||
return *this;
|
||||
}
|
||||
|
||||
|
||||
// Local Variables:
|
||||
// coding: iso-8859-1
|
||||
// mode: C++
|
||||
// c-file-offsets: ((c . 0))
|
||||
// c-file-style: "Stroustrup"
|
||||
// fill-column: 80
|
||||
// End:
|
||||
121
eo/src/utils/eoGnuplot1DSnapshot.h
Normal file
121
eo/src/utils/eoGnuplot1DSnapshot.h
Normal file
|
|
@ -0,0 +1,121 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoGnuplot1DSnapshot.h
|
||||
// (c) Marc Schoenauer, Maarten Keijzer and GeNeura Team, 2000
|
||||
/*
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
|
||||
Marc.Schoenauer@inria.fr
|
||||
mkeijzer@dhi.dk
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
|
||||
#ifndef EO_eoGnuplot1DSnapshot_H
|
||||
#define EO_eoGnuplot1DSnapshot_H
|
||||
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
|
||||
#include <eoObject.h>
|
||||
#include "eoRealVectorBounds.h"
|
||||
#include <utils/pipecom.h>
|
||||
#include <utils/eoFileSnapshot.h>
|
||||
#include <utils/eoGnuplot.h>
|
||||
|
||||
/** Plot stats through gnuplot
|
||||
|
||||
@author Marc Schoenauer 2000
|
||||
@version 0.0
|
||||
|
||||
This class plots through gnuplot the eoStat given as argument
|
||||
|
||||
Assumes that the same file is re-written every so and so, and plots it
|
||||
from scratch everytime it's called
|
||||
|
||||
@ingroup Monitors
|
||||
*/
|
||||
class eoGnuplot1DSnapshot: public eoFileSnapshot, public eoGnuplot
|
||||
{
|
||||
public:
|
||||
// Ctor
|
||||
eoGnuplot1DSnapshot(std::string _dirname, unsigned _frequency = 1,
|
||||
std::string _filename = "gen", std::string _delim = " ",
|
||||
unsigned _counter = 0, bool _rmFiles = true) :
|
||||
eoFileSnapshot(_dirname, _frequency, _filename, _delim, _counter, _rmFiles),
|
||||
eoGnuplot(_filename,"set data style points"),
|
||||
pointSize(5)
|
||||
{}
|
||||
|
||||
// Ctor
|
||||
eoGnuplot1DSnapshot(std::string _dirname, eoRealVectorBounds & _bounds,
|
||||
unsigned _frequency = 1, std::string _filename = "gen",
|
||||
std::string _delim = " ", unsigned _counter = 0, bool _rmFiles = true ) :
|
||||
eoFileSnapshot(_dirname, _frequency, _filename, _delim, _counter, _rmFiles),
|
||||
eoGnuplot(_filename,"set data style points"),
|
||||
pointSize(5)
|
||||
{
|
||||
handleBounds(_bounds);
|
||||
}
|
||||
// Ctor
|
||||
eoGnuplot1DSnapshot(eoFileSnapshot & _fSnapshot) :
|
||||
eoFileSnapshot(_fSnapshot),
|
||||
eoGnuplot(_fSnapshot.baseFileName(),"set data style points"),
|
||||
pointSize(5)
|
||||
{}
|
||||
|
||||
// Ctor with range
|
||||
eoGnuplot1DSnapshot(eoFileSnapshot & _fSnapshot, eoRealVectorBounds & _bounds) :
|
||||
eoFileSnapshot(_fSnapshot),
|
||||
eoGnuplot(_fSnapshot.baseFileName(),"set data style points"),
|
||||
pointSize(5)
|
||||
{
|
||||
handleBounds(_bounds);
|
||||
}
|
||||
|
||||
// Dtor
|
||||
virtual ~eoGnuplot1DSnapshot(){}
|
||||
|
||||
virtual eoMonitor& operator()();
|
||||
|
||||
/// Class name.
|
||||
virtual std::string className() const { return "eoGnuplot1DSnapshot"; }
|
||||
|
||||
virtual void handleBounds(eoRealVectorBounds & _bounds)
|
||||
{
|
||||
std::ostringstream os;
|
||||
os << "set autoscale\nset yrange [" ;
|
||||
if (_bounds.isMinBounded(0))
|
||||
os << _bounds.minimum(0);
|
||||
os << ":" ;
|
||||
if (_bounds.isMaxBounded(0))
|
||||
os << _bounds.maximum(0);
|
||||
os << "]\n";
|
||||
gnuplotCommand(os.str());
|
||||
}
|
||||
|
||||
void setPointSize(unsigned _pointSize)
|
||||
{ pointSize = _pointSize; }
|
||||
|
||||
protected:
|
||||
|
||||
unsigned pointSize;
|
||||
};
|
||||
|
||||
|
||||
#endif
|
||||
205
eo/src/utils/eoHowMany.h
Normal file
205
eo/src/utils/eoHowMany.h
Normal file
|
|
@ -0,0 +1,205 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoHowMany_h.h
|
||||
// Base class for choosing a number of guys to apply something from a popsize
|
||||
// (c) Marc Schoenauer, 2000
|
||||
// (c) Thales group, 2010 (Johann Dréo <johann.dreo@thalesgroup.com>)
|
||||
|
||||
/*
|
||||
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: http://eodev.sourceforge.net
|
||||
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef eoHowMany_h
|
||||
#define eoHowMany_h
|
||||
|
||||
#include <sstream>
|
||||
|
||||
#include <utils/eoLogger.h>
|
||||
|
||||
|
||||
/** A helper class, to determine a number of individuals from another one
|
||||
* Typically, is used in selection / replacement procedures, e.g.
|
||||
* the number of offspring from the number of parents, or
|
||||
* the number of survivors for an eoReduce functor, ...
|
||||
*
|
||||
* Such construct is very useful because in some cases you might not know the
|
||||
* population size that will enter the replacement. For instance, you
|
||||
* cannot simply have a pre-computed (double) rate of 1/popSize
|
||||
* if you want to select or kill just 1 guy. Using an eoHowMany
|
||||
* allows one to modify the population size without touching anything else.
|
||||
*
|
||||
* There are 4 possible way to compute the return value from the argument:
|
||||
* - an absolute POSITIVE integer --> return it (regardless of popsize)
|
||||
* - a POSITIVE rate --> return rate*popSize
|
||||
* - an absolute NEGATIVE integer --> return popsize-rate (if positive)
|
||||
* - a NEGATIVE rate in [-1,0] --> store and use 1-|rate| (positive)
|
||||
* Note that a negative rate should be have been necessary because a rate is
|
||||
* relative, but it is there for consistency reasons - and because it
|
||||
* is needed in <a href="classeo_g3_replacement_h-source.html">eoG3Replacement</a>
|
||||
*
|
||||
* It has 2 private members, a double and an integer to cover all cases
|
||||
*
|
||||
* Example use: in <a href="class_eogeneralbreeder.html">eoGeneralBreeder.h</a>
|
||||
* Example reading from parser: in
|
||||
* <a href="make_algo_scalar_h-source.html">do/make_algo_scalar.h line 141</a>
|
||||
|
||||
* MS 10/04/2002:
|
||||
* Added the possibility to have a negative number -
|
||||
* when treated as a number: returns then (size - count)
|
||||
* Should not modify anything when a positive number is passed in the ctor
|
||||
*
|
||||
* MS 20/06/2002:
|
||||
* Added the negative rate and the operator-() (for
|
||||
* eoG3Repalcement)
|
||||
*
|
||||
* It is an eoPersistent because we need to be able to use eoParamValue<eoHowMany>
|
||||
*
|
||||
* @ingroup Core
|
||||
*/
|
||||
class eoHowMany : public eoPersistent
|
||||
{
|
||||
public:
|
||||
/** Original Ctor from direct rate + bool
|
||||
@param _rate the rate, OR the integer to store, depending on 2nd arg.
|
||||
@param _interpret_as_rate to tell whether the rate actually is a rate
|
||||
*/
|
||||
eoHowMany(double _rate = 0.0, bool _interpret_as_rate = true):
|
||||
rate(_rate), count(0)
|
||||
{
|
||||
if (_interpret_as_rate)
|
||||
{
|
||||
if (_rate<0)
|
||||
{
|
||||
rate = 1.0+_rate;
|
||||
if (rate < 0) // was < -1
|
||||
throw std::logic_error("rate<-1 in eoHowMany!");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
rate = 0.0; // just in case, but shoud be unused
|
||||
count = int(_rate); // negative values are allowed here
|
||||
if (count != _rate)
|
||||
eo::log << eo::warnings << "Number was rounded in eoHowMany";
|
||||
}
|
||||
}
|
||||
|
||||
/** Ctor from an int - both from int and unsigned int are needed
|
||||
* to avoid ambiguity with the Ctor from a double */
|
||||
eoHowMany(int _count) : rate(0.0), count(_count) {}
|
||||
|
||||
/** Ctor from an unsigned int - both from int and unsigned int are needed
|
||||
* to avoid ambiguity with the Ctor from a double */
|
||||
eoHowMany(unsigned int _count) : rate(0.0), count(_count) {}
|
||||
|
||||
/// Virtual dtor. They are needed in virtual class hierarchies.
|
||||
virtual ~eoHowMany() {}
|
||||
|
||||
/** Does what it was designed for
|
||||
* - count==0 : return rate*_size
|
||||
* - else
|
||||
* - count>0 : return count (regardless of _size)
|
||||
* - count<0 : return _size-|count|
|
||||
*/
|
||||
unsigned int operator()(unsigned int _size)
|
||||
{
|
||||
if (count == 0)
|
||||
{
|
||||
unsigned int res = static_cast<unsigned int>( std::ceil( rate * _size ) );
|
||||
|
||||
if( res == 0 ) {
|
||||
eo::log << eo::warnings << "Call to a eoHowMany instance returns 0 (rate=" << rate << ", size=" << _size << ")" << std::endl;
|
||||
}
|
||||
|
||||
return res;
|
||||
}
|
||||
if (count < 0)
|
||||
{
|
||||
unsigned int combloc = -count;
|
||||
if (_size<combloc)
|
||||
throw std::runtime_error("Negative result in eoHowMany");
|
||||
return _size-combloc;
|
||||
}
|
||||
return unsigned(count);
|
||||
}
|
||||
|
||||
virtual void printOn(std::ostream& _os) const
|
||||
{
|
||||
if (count == 0)
|
||||
_os << 100*rate << "% ";
|
||||
else
|
||||
_os << count << " ";
|
||||
return;
|
||||
|
||||
}
|
||||
|
||||
virtual void readFrom(std::istream& _is)
|
||||
{
|
||||
std::string value;
|
||||
_is >> value;
|
||||
readFrom(value);
|
||||
return;
|
||||
}
|
||||
|
||||
void readFrom(std::string _value)
|
||||
{
|
||||
// check for %
|
||||
bool interpret_as_rate = false; // == no %
|
||||
size_t pos = _value.find('%');
|
||||
if (pos < _value.size()) // found a %
|
||||
{
|
||||
interpret_as_rate = true;
|
||||
_value.resize(pos); // get rid of %
|
||||
}
|
||||
|
||||
std::istringstream is(_value);
|
||||
is >> rate;
|
||||
// now store
|
||||
if (interpret_as_rate)
|
||||
{
|
||||
count = 0;
|
||||
rate /= 100.0;
|
||||
}
|
||||
else
|
||||
count = int(rate); // and rate will not be used
|
||||
|
||||
// minimal check
|
||||
if ( rate < 0.0 )
|
||||
throw std::runtime_error("Negative rate read in eoHowMany::readFrom");
|
||||
}
|
||||
|
||||
/** The unary - operator: reverses the computation */
|
||||
eoHowMany operator-()
|
||||
{
|
||||
if (!count) // only rate is used
|
||||
rate = 1.0-rate;
|
||||
else
|
||||
count = -count;
|
||||
return (*this);
|
||||
}
|
||||
|
||||
private :
|
||||
double rate;
|
||||
int count;
|
||||
};
|
||||
|
||||
|
||||
|
||||
#endif
|
||||
98
eo/src/utils/eoIntBounds.cpp
Normal file
98
eo/src/utils/eoIntBounds.cpp
Normal file
|
|
@ -0,0 +1,98 @@
|
|||
#ifdef _MSC_VER
|
||||
// to avoid long name warnings
|
||||
#pragma warning(disable:4786)
|
||||
#endif
|
||||
|
||||
#ifdef HAVE_CONFIG_H
|
||||
#include <config.h>
|
||||
#endif
|
||||
|
||||
#include <ctime>
|
||||
#include <sstream>
|
||||
|
||||
#include "eoIntBounds.h"
|
||||
|
||||
|
||||
// the global dummy bounds
|
||||
// (used for unbounded variables when bounds are required)
|
||||
eoIntNoBounds eoDummyIntNoBounds;
|
||||
|
||||
///////////// helper read functions defined in eoRealBounds.cpp
|
||||
extern bool remove_leading(std::string & _s, const std::string _delim);
|
||||
extern double read_double(std::string _s);
|
||||
extern long int read_int(std::string _s);
|
||||
|
||||
|
||||
/** the constructor for eoGeneralIntBound - from a string
|
||||
*/
|
||||
eoIntBounds* eoGeneralIntBounds::getBoundsFromString(std::string _value)
|
||||
{
|
||||
// now read
|
||||
std::string delim(",; ");
|
||||
std::string beginOrClose("[(])");
|
||||
if (!remove_leading(_value, delim)) // only delimiters were left
|
||||
throw std::runtime_error("Syntax error in eoGeneralIntBounds Ctor");
|
||||
|
||||
// look for opening char
|
||||
size_t posDeb = _value.find_first_of(beginOrClose); // allow ]a,b]
|
||||
if (posDeb >= _value.size()) // nothing left to read
|
||||
throw std::runtime_error("Syntax error in eoGeneralIntBounds Ctor");
|
||||
|
||||
// ending char: next {}() after posDeb
|
||||
size_t posFin = _value.find_first_of(beginOrClose,posDeb+1);
|
||||
if (posFin >= _value.size()) // not found
|
||||
throw std::runtime_error("Syntax error in eoGeneralIntBounds Ctor");
|
||||
|
||||
// the bounds
|
||||
std::string sBounds = _value.substr(posDeb+1, posFin-posDeb-1);
|
||||
// and remove from original string
|
||||
_value = _value.substr(posFin+1);
|
||||
|
||||
remove_leading(sBounds, delim);
|
||||
size_t posDelim = sBounds.find_first_of(delim);
|
||||
if (posDelim >= sBounds.size())
|
||||
throw std::runtime_error("Syntax error in eoGeneralIntBounds Ctor");
|
||||
|
||||
bool minBounded=false, maxBounded=false;
|
||||
long int minBound=0, maxBound=0;
|
||||
|
||||
// min bound
|
||||
std::string sMinBounds = sBounds.substr(0,posDelim);
|
||||
|
||||
if ( (sMinBounds != std::string("-inf")) &&
|
||||
(sMinBounds != std::string("-infinity"))
|
||||
)
|
||||
{
|
||||
minBounded = true;
|
||||
minBound = read_int(sMinBounds);
|
||||
}
|
||||
|
||||
// max bound
|
||||
size_t posEndDelim = sBounds.find_first_not_of(delim,posDelim);
|
||||
|
||||
std::string sMaxBounds = sBounds.substr(posEndDelim);
|
||||
|
||||
if ( (sMaxBounds != std::string("+inf")) &&
|
||||
(sMaxBounds != std::string("+infinity"))
|
||||
)
|
||||
{
|
||||
maxBounded = true;
|
||||
maxBound = read_int(sMaxBounds);
|
||||
}
|
||||
|
||||
// now create the embedded eoIntBounds object
|
||||
eoIntBounds * locBound;
|
||||
if (minBounded && maxBounded)
|
||||
{
|
||||
if (maxBound <= minBound)
|
||||
throw std::runtime_error("Syntax error in eoGeneralIntBounds Ctor");
|
||||
locBound = new eoIntInterval(minBound, maxBound);
|
||||
}
|
||||
else if (!minBounded && !maxBounded) // no bound at all
|
||||
locBound = new eoIntNoBounds;
|
||||
else if (!minBounded && maxBounded)
|
||||
locBound = new eoIntAboveBound(maxBound);
|
||||
else if (minBounded && !maxBounded)
|
||||
locBound = new eoIntBelowBound(minBound);
|
||||
return locBound;
|
||||
}
|
||||
729
eo/src/utils/eoIntBounds.h
Normal file
729
eo/src/utils/eoIntBounds.h
Normal file
|
|
@ -0,0 +1,729 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoIntBounds.h
|
||||
// (c) Marc Schoenauer 2001, Maarten Keijzer 2000, 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
|
||||
Marc.Schoenauer@polytechnique.fr
|
||||
mak@dhi.dk
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _eoIntBounds_h
|
||||
#define _eoIntBounds_h
|
||||
|
||||
#include <stdexcept> // std::exceptions!
|
||||
#include <utils/eoRNG.h>
|
||||
|
||||
/**
|
||||
\class eoIntBounds eoIntBounds.h es/eoIntBounds.h
|
||||
\ingroup Real
|
||||
\ingroup Bounds
|
||||
|
||||
Defines bound classes for real numbers.
|
||||
|
||||
Scalar type:
|
||||
------------
|
||||
Basic class is eoIntBounds, a pure virtual.
|
||||
|
||||
The following pure virtual methods are to be used in mutations:
|
||||
- void foldsInBounds(long int &) that folds any value that falls out of
|
||||
the bounds back into the bounds, by bouncing on the limit (if any)
|
||||
- bool isInBounds(long int) that simply says whether or not the argument
|
||||
is in the bounds
|
||||
- void truncate(long int &) that set the argument to the bound value it
|
||||
it exceeds it
|
||||
|
||||
So mutation can choose
|
||||
- iterate trying until they fall in bounds,
|
||||
- only try once and "restd::pair" by using the foldsInBounds method
|
||||
- only try once and restd::pair using the truncate method (will create a
|
||||
huge bias toward the bound if the soluiton is not far from the bounds)
|
||||
|
||||
There is also a uniform() method that generates a uniform value
|
||||
(if possible, i.e. if bounded) in the interval.
|
||||
|
||||
Derived class are
|
||||
eoIntInterval that holds a minimum and maximum value,
|
||||
eoIntNoBounds the "unbounded bounds" (-infinity, +infinity)
|
||||
eoIntBelowBound the half-bounded interval [min, +infinity)
|
||||
eoIntAboveBound the half-bounded interval (-infinity, max]
|
||||
|
||||
THis file also contains the declaration of *the* global object that
|
||||
is the unbounded bound
|
||||
*/
|
||||
class eoIntBounds : public eoPersistent
|
||||
{
|
||||
public:
|
||||
virtual ~eoIntBounds(){}
|
||||
|
||||
/** Self-Test: true if ***both*** a min and a max
|
||||
*/
|
||||
virtual bool isBounded(void) const = 0;
|
||||
|
||||
/** Self-Test: true if no min ***and*** no max
|
||||
* hence no further need to test/truncate/fold anything
|
||||
*/
|
||||
virtual bool hasNoBoundAtAll(void) const = 0;
|
||||
|
||||
/** Self-Test: bounded from below???
|
||||
*/
|
||||
virtual bool isMinBounded(void) const = 0;
|
||||
|
||||
/** Self-Test: bounded from above???
|
||||
*/
|
||||
virtual bool isMaxBounded(void) const = 0;
|
||||
|
||||
/** Test on a value: is it in bounds?
|
||||
*/
|
||||
virtual bool isInBounds(double) const = 0;
|
||||
|
||||
/** Put value back into bounds - by folding back and forth
|
||||
*/
|
||||
virtual void foldsInBounds(double &) const = 0;
|
||||
|
||||
/** foldsInBounds for ints:
|
||||
* call the method for double and convert back */
|
||||
virtual void foldsInBounds(long int & i) const
|
||||
{
|
||||
double r = double(i);
|
||||
foldsInBounds(r);
|
||||
i = (long int)(r);
|
||||
}
|
||||
|
||||
/** Put value back into bounds - by truncating to a boundary value
|
||||
*/
|
||||
virtual void truncate(double &) const = 0;
|
||||
|
||||
/** truncate for ints: call the method for double and convert back
|
||||
*/
|
||||
virtual void truncate(long int & i) const
|
||||
{
|
||||
double r = double(i);
|
||||
truncate(r);
|
||||
i = (long int)(r);
|
||||
}
|
||||
|
||||
/** get minimum value
|
||||
* std::exception if does not exist
|
||||
*/
|
||||
virtual long int minimum() const = 0 ;
|
||||
/** get maximum value
|
||||
* std::exception if does not exist
|
||||
*/
|
||||
virtual long int maximum() const = 0 ;
|
||||
/** get range
|
||||
* std::exception if unbounded
|
||||
*/
|
||||
virtual long int range() const = 0;
|
||||
|
||||
/** random generator of uniform numbers in bounds
|
||||
* uses same naming convention than eo::rng
|
||||
* std::exception if unbounded
|
||||
*/
|
||||
virtual double uniform(eoRng & _rng = eo::rng) const = 0;
|
||||
virtual long int random(eoRng & _rng = eo::rng) const = 0;
|
||||
|
||||
/** for memory managements - ugly */
|
||||
virtual eoIntBounds * dup() const = 0;
|
||||
};
|
||||
|
||||
/** A default class for unbounded variables
|
||||
*
|
||||
* @ingroup Real
|
||||
* @ingroup Bounds
|
||||
*/
|
||||
class eoIntNoBounds : public eoIntBounds
|
||||
{
|
||||
public:
|
||||
virtual ~eoIntNoBounds(){}
|
||||
|
||||
virtual bool isBounded(void) const {return false;}
|
||||
virtual bool hasNoBoundAtAll(void) const {return true;}
|
||||
virtual bool isMinBounded(void) const {return false;}
|
||||
virtual bool isMaxBounded(void) const {return false;}
|
||||
virtual void foldsInBounds(double &) const {return;}
|
||||
virtual void truncate(double &) const {return;}
|
||||
virtual bool isInBounds(double) const {return true;}
|
||||
|
||||
virtual long int minimum() const
|
||||
{
|
||||
throw std::logic_error("Trying to get minimum of unbounded eoIntBounds");
|
||||
}
|
||||
virtual long int maximum() const
|
||||
{
|
||||
throw std::logic_error("Trying to get maximum of unbounded eoIntBounds");
|
||||
}
|
||||
virtual long int range() const
|
||||
{
|
||||
throw std::logic_error("Trying to get range of unbounded eoIntBounds");
|
||||
}
|
||||
|
||||
virtual double uniform(eoRng & _rng = eo::rng) const
|
||||
{
|
||||
(void)_rng;
|
||||
|
||||
throw std::logic_error("Trying to generate uniform values in unbounded eoIntBounds");
|
||||
}
|
||||
|
||||
virtual long int random(eoRng & _rng = eo::rng) const
|
||||
{
|
||||
(void)_rng;
|
||||
|
||||
throw std::logic_error("Trying to generate uniform values in unbounded eoIntBounds");
|
||||
}
|
||||
|
||||
// methods from eoPersistent
|
||||
/**
|
||||
* Read object.
|
||||
* @param _is A std::istream.
|
||||
* but reading should not be done here, because of bound problems
|
||||
* see eoIntVectorBounds
|
||||
*/
|
||||
virtual void readFrom(std::istream& _is)
|
||||
{
|
||||
(void)_is;
|
||||
|
||||
throw std::runtime_error("Should not use eoIntBounds::readFrom");
|
||||
}
|
||||
|
||||
/**
|
||||
* Write object. It's called printOn since it prints the object on a stream.
|
||||
* @param _os A std::ostream.
|
||||
*/
|
||||
virtual void printOn(std::ostream& _os) const
|
||||
{
|
||||
_os << "[-inf,+inf]";
|
||||
}
|
||||
|
||||
/** for memory managements - ugly */
|
||||
virtual eoIntBounds * dup() const
|
||||
{
|
||||
return new eoIntNoBounds(*this);
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
/** one object for all - see eoIntBounds.cpp
|
||||
*
|
||||
* @ingroup Real
|
||||
* @ingroup Bounds
|
||||
*/
|
||||
extern eoIntNoBounds eoDummyIntNoBounds;
|
||||
|
||||
/**
|
||||
* fully bounded eoIntBound == interval
|
||||
*
|
||||
* @ingroup Real
|
||||
* @ingroup Bounds
|
||||
*/
|
||||
class eoIntInterval : public eoIntBounds
|
||||
{
|
||||
public :
|
||||
virtual ~eoIntInterval(){}
|
||||
|
||||
/**
|
||||
Simple bounds = minimum and maximum (allowed)
|
||||
*/
|
||||
eoIntInterval(long int _min=0, long int _max=1) :
|
||||
repMinimum(_min), repMaximum(_max), repRange(_max-_min)
|
||||
{
|
||||
if (repRange<=0)
|
||||
throw std::logic_error("Void range in eoIntBounds");
|
||||
}
|
||||
|
||||
// accessors
|
||||
virtual long int minimum() const { return repMinimum; }
|
||||
virtual long int maximum() const { return repMaximum; }
|
||||
virtual long int range() const { return repRange; }
|
||||
|
||||
// description
|
||||
virtual bool isBounded(void) const {return true;}
|
||||
virtual bool hasNoBoundAtAll(void) const {return false;}
|
||||
virtual bool isMinBounded(void) const {return true;}
|
||||
virtual bool isMaxBounded(void) const {return true;}
|
||||
|
||||
virtual double uniform(eoRng & _rng = eo::rng) const
|
||||
{
|
||||
return repMinimum + _rng.uniform(repRange);
|
||||
}
|
||||
|
||||
virtual long int random(eoRng & _rng = eo::rng) const
|
||||
{
|
||||
return repMinimum + _rng.random(repRange);
|
||||
}
|
||||
|
||||
// says if a given double is within the bounds
|
||||
virtual bool isInBounds(double _r) const
|
||||
{
|
||||
if (_r < repMinimum)
|
||||
return false;
|
||||
if (_r > repMaximum)
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
// folds a value into bounds
|
||||
virtual void foldsInBounds(double & _r) const
|
||||
{
|
||||
long iloc;
|
||||
double dlargloc = 2 * range() ;
|
||||
|
||||
if (fabs(_r) > 1.0E9) // iloc too large!
|
||||
{
|
||||
_r = uniform();
|
||||
return;
|
||||
}
|
||||
|
||||
if ( (_r > maximum()) )
|
||||
{
|
||||
iloc = (long) ( (_r-minimum()) / dlargloc ) ;
|
||||
_r -= dlargloc * iloc ;
|
||||
if ( _r > maximum() )
|
||||
_r = 2*maximum() - _r ;
|
||||
}
|
||||
|
||||
if (_r < minimum())
|
||||
{
|
||||
iloc = (long) ( (maximum()-_r) / dlargloc ) ;
|
||||
_r += dlargloc * iloc ;
|
||||
if (_r < minimum())
|
||||
_r = 2*minimum() - _r ;
|
||||
}
|
||||
}
|
||||
|
||||
// truncates to the bounds
|
||||
virtual void truncate(double & _r) const
|
||||
{
|
||||
if (_r < repMinimum)
|
||||
_r = repMinimum;
|
||||
else if (_r > repMaximum)
|
||||
_r = repMaximum;
|
||||
return;
|
||||
}
|
||||
|
||||
// methods from eoPersistent
|
||||
/**
|
||||
* Read object.
|
||||
* @param _is A std::istream.
|
||||
* but reading should not be done here, because of bound problems
|
||||
* see eoIntVectorBounds
|
||||
*/
|
||||
virtual void readFrom(std::istream& _is)
|
||||
{
|
||||
(void)_is;
|
||||
|
||||
throw std::runtime_error("Should not use eoIntInterval::readFrom");
|
||||
}
|
||||
|
||||
/**
|
||||
* Write object. It's called printOn since it prints the object on a stream.
|
||||
* @param _os A std::ostream.
|
||||
*/
|
||||
virtual void printOn(std::ostream& _os) const
|
||||
{
|
||||
_os << "[" << repMinimum << "," << repMaximum << "]";
|
||||
}
|
||||
|
||||
/** for memory managements - ugly */
|
||||
virtual eoIntBounds * dup() const
|
||||
{
|
||||
return new eoIntInterval(*this);
|
||||
}
|
||||
|
||||
private :
|
||||
long int repMinimum;
|
||||
long int repMaximum;
|
||||
long int repRange; // to minimize operations ???
|
||||
};
|
||||
|
||||
/**
|
||||
* an eoIntBound bounded from below only
|
||||
*
|
||||
* @ingroup Real
|
||||
* @ingroup Bounds
|
||||
*/
|
||||
class eoIntBelowBound : public eoIntBounds
|
||||
{
|
||||
public :
|
||||
virtual ~eoIntBelowBound(){}
|
||||
/**
|
||||
Simple bounds = minimum
|
||||
*/
|
||||
eoIntBelowBound(long int _min=0) :
|
||||
repMinimum(_min)
|
||||
{}
|
||||
|
||||
// accessors
|
||||
virtual long int minimum() const { return repMinimum; }
|
||||
|
||||
virtual long int maximum() const
|
||||
{
|
||||
throw std::logic_error("Trying to get maximum of eoIntBelowBound");
|
||||
}
|
||||
virtual long int range() const
|
||||
{
|
||||
throw std::logic_error("Trying to get range of eoIntBelowBound");
|
||||
}
|
||||
|
||||
virtual double uniform(eoRng & _rng = eo::rng) const
|
||||
{
|
||||
(void)_rng;
|
||||
|
||||
throw std::logic_error("Trying to generate uniform values in eoIntBelowBound");
|
||||
}
|
||||
|
||||
virtual long int random(eoRng & _rng = eo::rng) const
|
||||
{
|
||||
(void)_rng;
|
||||
|
||||
throw std::logic_error("Trying to generate uniform values in eoIntBelowBound");
|
||||
}
|
||||
|
||||
// description
|
||||
virtual bool isBounded(void) const {return false;}
|
||||
virtual bool hasNoBoundAtAll(void) const {return false;}
|
||||
virtual bool isMinBounded(void) const {return true;}
|
||||
virtual bool isMaxBounded(void) const {return false;}
|
||||
|
||||
// says if a given double is within the bounds
|
||||
virtual bool isInBounds(double _r) const
|
||||
{
|
||||
if (_r < repMinimum)
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
// folds a value into bounds
|
||||
virtual void foldsInBounds(double & _r) const
|
||||
{
|
||||
// easy as a pie: symmetry w.r.t. minimum
|
||||
if (_r < repMinimum) // nothing to do otherwise
|
||||
_r = 2*repMinimum - _r;
|
||||
return ;
|
||||
}
|
||||
|
||||
// truncates to the bounds
|
||||
virtual void truncate(double & _r) const
|
||||
{
|
||||
if (_r < repMinimum)
|
||||
_r = repMinimum;
|
||||
return;
|
||||
}
|
||||
|
||||
// methods from eoPersistent
|
||||
/**
|
||||
* Read object.
|
||||
* @param _is A std::istream.
|
||||
* but reading should not be done here, because of bound problems
|
||||
* see eoIntVectorBounds
|
||||
*/
|
||||
virtual void readFrom(std::istream& _is)
|
||||
{
|
||||
(void)_is;
|
||||
|
||||
throw std::runtime_error("Should not use eoIntBelowBound::readFrom");
|
||||
}
|
||||
|
||||
/**
|
||||
* Write object. It's called printOn since it prints the object on a stream.
|
||||
* @param _os A std::ostream.
|
||||
*/
|
||||
virtual void printOn(std::ostream& _os) const
|
||||
{
|
||||
_os << "[" << repMinimum << ",+inf]";
|
||||
}
|
||||
|
||||
/** for memory managements - ugly */
|
||||
virtual eoIntBounds * dup() const
|
||||
{
|
||||
return new eoIntBelowBound(*this);
|
||||
}
|
||||
|
||||
private :
|
||||
long int repMinimum;
|
||||
};
|
||||
|
||||
/**
|
||||
An eoIntBound bounded from above only
|
||||
*
|
||||
* @ingroup Real
|
||||
* @ingroup Bounds
|
||||
*/
|
||||
class eoIntAboveBound : public eoIntBounds
|
||||
{
|
||||
public :
|
||||
virtual ~eoIntAboveBound(){}
|
||||
|
||||
/**
|
||||
Simple bounds = minimum
|
||||
*/
|
||||
eoIntAboveBound(long int _max=0) :
|
||||
repMaximum(_max)
|
||||
{}
|
||||
|
||||
// accessors
|
||||
virtual long int maximum() const { return repMaximum; }
|
||||
|
||||
virtual long int minimum() const
|
||||
{
|
||||
throw std::logic_error("Trying to get minimum of eoIntAboveBound");
|
||||
}
|
||||
virtual long int range() const
|
||||
{
|
||||
throw std::logic_error("Trying to get range of eoIntAboveBound");
|
||||
}
|
||||
|
||||
virtual double uniform(eoRng & _rng = eo::rng) const
|
||||
{
|
||||
(void)_rng;
|
||||
|
||||
throw std::logic_error("Trying to generate uniform values in eoIntAboveBound");
|
||||
}
|
||||
|
||||
virtual long int random(eoRng & _rng = eo::rng) const
|
||||
{
|
||||
(void)_rng;
|
||||
|
||||
throw std::logic_error("Trying to generate uniform values in eoIntAboveBound");
|
||||
}
|
||||
|
||||
// description
|
||||
virtual bool isBounded(void) const {return false;}
|
||||
virtual bool hasNoBoundAtAll(void) const {return false;}
|
||||
virtual bool isMinBounded(void) const {return false;}
|
||||
virtual bool isMaxBounded(void) const {return true;}
|
||||
|
||||
// says if a given double is within the bounds
|
||||
virtual bool isInBounds(double _r) const
|
||||
{
|
||||
if (_r > repMaximum)
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
// folds a value into bounds
|
||||
virtual void foldsInBounds(double & _r) const
|
||||
{
|
||||
// easy as a pie: symmetry w.r.t. maximum
|
||||
if (_r > repMaximum) // nothing to do otherwise
|
||||
_r = 2*repMaximum - _r;
|
||||
return ;
|
||||
}
|
||||
|
||||
// truncates to the bounds
|
||||
virtual void truncate(double & _r) const
|
||||
{
|
||||
if (_r > repMaximum)
|
||||
_r = repMaximum;
|
||||
return;
|
||||
}
|
||||
|
||||
// methods from eoPersistent
|
||||
/**
|
||||
* Read object.
|
||||
* @param _is A std::istream.
|
||||
* but reading should not be done here, because of bound problems
|
||||
* see eoIntVectorBounds
|
||||
*/
|
||||
virtual void readFrom(std::istream& _is)
|
||||
{
|
||||
(void)_is;
|
||||
|
||||
throw std::runtime_error("Should not use eoIntAboveBound::readFrom");
|
||||
}
|
||||
|
||||
/**
|
||||
* Write object. It's called printOn since it prints the object on a stream.
|
||||
* @param _os A std::ostream.
|
||||
*/
|
||||
virtual void printOn(std::ostream& _os) const
|
||||
{
|
||||
_os << "[-inf," << repMaximum << "]";
|
||||
}
|
||||
|
||||
/** for memory managements - ugly */
|
||||
virtual eoIntBounds * dup() const
|
||||
{
|
||||
return new eoIntAboveBound(*this);
|
||||
}
|
||||
|
||||
private :
|
||||
long int repMaximum;
|
||||
};
|
||||
|
||||
//////////////////////// tentative for a general BOUND class that is constructed from a string
|
||||
|
||||
/** A class that encapsulate all possible eoIntBounds.
|
||||
* Mandatory in order to read through the parser
|
||||
*
|
||||
* @ingroup Real
|
||||
* @ingroup Bounds
|
||||
*/
|
||||
class eoGeneralIntBounds : public eoIntBounds
|
||||
{
|
||||
public:
|
||||
/** Ctor: from a string, chooses the type of bound */
|
||||
eoGeneralIntBounds(std::string _s = "[-infinity,+infinity]")
|
||||
{
|
||||
repBound = getBoundsFromString(_s);
|
||||
}
|
||||
|
||||
/** Need a Cpy Ctor because we are allocating memory */
|
||||
eoGeneralIntBounds(const eoGeneralIntBounds & _b) : eoIntBounds(_b)
|
||||
{
|
||||
// replicate the embedded bound (I'm pretty sure there is another
|
||||
// way to do that !!!
|
||||
|
||||
bool minBounded = _b.isMinBounded();
|
||||
bool maxBounded = _b.isMaxBounded();
|
||||
long int minimum, maximum;
|
||||
const eoIntBounds & bb = _b.theBounds();
|
||||
if (minBounded) minimum = bb.minimum();
|
||||
if (maxBounded) maximum = bb.maximum();
|
||||
|
||||
if (minBounded && maxBounded)
|
||||
repBound = new eoIntInterval(minimum, maximum);
|
||||
else if (!minBounded && !maxBounded) // no bound at all
|
||||
repBound = new eoIntNoBounds;
|
||||
else if (!minBounded && maxBounded)
|
||||
repBound = new eoIntAboveBound(maximum);
|
||||
else if (minBounded && !maxBounded)
|
||||
repBound = new eoIntBelowBound(minimum);
|
||||
}
|
||||
|
||||
eoGeneralIntBounds& operator=(const eoGeneralIntBounds& _b)
|
||||
{
|
||||
// replicate the embedded bound (I'm pretty sure there is another
|
||||
// way to do that !!!
|
||||
|
||||
bool minBounded = _b.isMinBounded();
|
||||
bool maxBounded = _b.isMaxBounded();
|
||||
long int minimum, maximum;
|
||||
const eoIntBounds & bb = _b.theBounds();
|
||||
if (minBounded) minimum = bb.minimum();
|
||||
if (maxBounded) maximum = bb.maximum();
|
||||
|
||||
// first delete the embedded bounds if necessary
|
||||
if (repBound)
|
||||
delete repBound;
|
||||
// now reallocate
|
||||
if (minBounded && maxBounded)
|
||||
repBound = new eoIntInterval(minimum, maximum);
|
||||
else if (!minBounded && !maxBounded) // no bound at all
|
||||
repBound = new eoIntNoBounds;
|
||||
else if (!minBounded && maxBounded)
|
||||
repBound = new eoIntAboveBound(maximum);
|
||||
else if (minBounded && !maxBounded)
|
||||
repBound = new eoIntBelowBound(minimum);
|
||||
return (*this);
|
||||
}
|
||||
|
||||
|
||||
/** Need a Dtor because we allocate an actual bound */
|
||||
~eoGeneralIntBounds()
|
||||
{
|
||||
delete repBound;
|
||||
}
|
||||
|
||||
///// and now all methods from the embedded bounds
|
||||
/** Self-Test: true if ***both*** a min and a max
|
||||
*/
|
||||
virtual bool isBounded(void) const {return repBound->isBounded();}
|
||||
|
||||
/** Self-Test: true if no min ***and*** no max
|
||||
* hence no further need to test/truncate/fold anything
|
||||
*/
|
||||
virtual bool hasNoBoundAtAll(void) const {return repBound->hasNoBoundAtAll();}
|
||||
|
||||
/** Self-Test: bounded from below???
|
||||
*/
|
||||
virtual bool isMinBounded(void) const {return repBound->isMinBounded();}
|
||||
|
||||
/** Self-Test: bounded from above???
|
||||
*/
|
||||
virtual bool isMaxBounded(void) const {return repBound->isMaxBounded();}
|
||||
|
||||
/** Test on a value: is it in bounds?
|
||||
*/
|
||||
virtual bool isInBounds(double _x) const {return repBound->isInBounds(_x);}
|
||||
|
||||
/** Put value back into bounds - by folding back and forth
|
||||
*/
|
||||
virtual void foldsInBounds(double & _x) const {return repBound->foldsInBounds(_x);}
|
||||
|
||||
/** Put value back into bounds - by truncating to a boundary value
|
||||
*/
|
||||
virtual void truncate(double & _x) const {return repBound->truncate(_x);}
|
||||
|
||||
/** get minimum value
|
||||
* std::exception if does not exist
|
||||
*/
|
||||
virtual long int minimum() const {return repBound->minimum();}
|
||||
/** get maximum value
|
||||
* std::exception if does not exist
|
||||
*/
|
||||
virtual long int maximum() const {return repBound->maximum();}
|
||||
/** get range
|
||||
* std::exception if unbounded
|
||||
*/
|
||||
virtual long int range() const {return repBound->range();}
|
||||
|
||||
/** random generator of uniform doubles in bounds
|
||||
* std::exception if unbounded
|
||||
*/
|
||||
virtual double uniform(eoRng & _rng = eo::rng) const {(void)_rng; return repBound->uniform();}
|
||||
|
||||
/** random generator of uniform ints in bounds
|
||||
* std::exception if unbounded
|
||||
*/
|
||||
virtual long int random(eoRng & _rng = eo::rng) const {(void)_rng; return repBound->random();}
|
||||
|
||||
/** for memory managements - ugly */
|
||||
virtual eoIntBounds * dup() const {return repBound->dup();}
|
||||
|
||||
/** for efficiency, it's better to use the embedded boud directly */
|
||||
const eoIntBounds & theBounds() const { return *repBound;}
|
||||
|
||||
/** don't forget the printOn method -
|
||||
* again that of the embedded bound
|
||||
*/
|
||||
virtual void printOn(std::ostream& _os) const
|
||||
{
|
||||
repBound->printOn(_os);
|
||||
}
|
||||
|
||||
/** no readFrom ??? Have to check that later */
|
||||
virtual void readFrom(std::istream& _is)
|
||||
{
|
||||
std::string s;
|
||||
_is >> s;
|
||||
if (repBound)
|
||||
delete repBound;
|
||||
repBound = getBoundsFromString(s);
|
||||
}
|
||||
|
||||
private:
|
||||
// reading from a string
|
||||
eoIntBounds * getBoundsFromString(std::string);
|
||||
|
||||
eoIntBounds * repBound;
|
||||
};
|
||||
|
||||
|
||||
#endif
|
||||
225
eo/src/utils/eoLogger.cpp
Normal file
225
eo/src/utils/eoLogger.cpp
Normal file
|
|
@ -0,0 +1,225 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
/*
|
||||
|
||||
(c) Thales group, 2010
|
||||
|
||||
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;
|
||||
version 2 of the license.
|
||||
|
||||
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: http://eodev.sourceforge.net
|
||||
|
||||
Authors:
|
||||
Johann Dréo <johann.dreo@thalesgroup.com>
|
||||
Caner Candan <caner.candan@thalesgroup.com>
|
||||
|
||||
*/
|
||||
|
||||
#ifdef _WIN32
|
||||
#include <io.h>
|
||||
#else // _WIN32
|
||||
#include <unistd.h>
|
||||
#endif // ! _WIN32
|
||||
|
||||
#include <fcntl.h>
|
||||
#include <cstdlib>
|
||||
#include <cstdio> // used to define EOF
|
||||
|
||||
#include <iostream>
|
||||
|
||||
#include "eoLogger.h"
|
||||
|
||||
void eoLogger::_init()
|
||||
{
|
||||
_standard_io_streams[&std::cout] = 1;
|
||||
_standard_io_streams[&std::clog] = 2;
|
||||
_standard_io_streams[&std::cerr] = 2;
|
||||
|
||||
// /!\ If you want to add a level dont forget to add it at the header file in the enumerator Levels
|
||||
|
||||
addLevel("quiet", eo::quiet);
|
||||
addLevel("errors", eo::errors);
|
||||
addLevel("warnings", eo::warnings);
|
||||
addLevel("progress", eo::progress);
|
||||
addLevel("logging", eo::logging);
|
||||
addLevel("debug", eo::debug);
|
||||
addLevel("xdebug", eo::xdebug);
|
||||
}
|
||||
|
||||
eoLogger::eoLogger() :
|
||||
std::ostream(&_obuf),
|
||||
|
||||
_verbose("quiet", "verbose", "Set the verbose level", 'v'),
|
||||
_printVerboseLevels(false, "print-verbose-levels", "Print verbose levels", 'l'),
|
||||
_output("", "output", "Redirect a standard output to a file", 'o'),
|
||||
|
||||
_selectedLevel(eo::progress),
|
||||
_contextLevel(eo::quiet),
|
||||
_fd(2),
|
||||
_obuf(_fd, _contextLevel, _selectedLevel)
|
||||
{
|
||||
_init();
|
||||
}
|
||||
|
||||
eoLogger::eoLogger(eo::file file) :
|
||||
std::ostream(&_obuf),
|
||||
|
||||
_verbose("quiet", "verbose", "Set the verbose level", 'v'),
|
||||
_printVerboseLevels(false, "print-verbose-levels", "Print verbose levels", 'l'),
|
||||
_output("", "output", "Redirect a standard output to a file", 'o'),
|
||||
|
||||
_selectedLevel(eo::progress),
|
||||
_contextLevel(eo::quiet),
|
||||
_fd(2),
|
||||
_obuf(_fd, _contextLevel, _selectedLevel)
|
||||
{
|
||||
_init();
|
||||
*this << file;
|
||||
}
|
||||
|
||||
eoLogger::~eoLogger()
|
||||
{
|
||||
if (_fd > 2) { ::close(_fd); }
|
||||
}
|
||||
|
||||
void eoLogger::_createParameters( eoParser& parser )
|
||||
{
|
||||
//------------------------------------------------------------------
|
||||
// we are saying to eoParser to create the parameters created above.
|
||||
//------------------------------------------------------------------
|
||||
|
||||
std::string section("Logger");
|
||||
parser.processParam(_verbose, section);
|
||||
parser.processParam(_printVerboseLevels, section);
|
||||
parser.processParam(_output, section);
|
||||
|
||||
//------------------------------------------------------------------
|
||||
|
||||
|
||||
//------------------------------------------------------------------
|
||||
// we're gonna redirect the log to the given filename if -o is used.
|
||||
//------------------------------------------------------------------
|
||||
|
||||
if ( ! _output.value().empty() )
|
||||
{
|
||||
eo::log << eo::file( _output.value() );
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------
|
||||
|
||||
|
||||
//------------------------------------------------------------------
|
||||
// we're gonna print the list of levels if -l parameter is used.
|
||||
//------------------------------------------------------------------
|
||||
|
||||
if ( _printVerboseLevels.value() )
|
||||
{
|
||||
eo::log.printLevels();
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------
|
||||
}
|
||||
|
||||
std::string eoLogger::className() const
|
||||
{
|
||||
return ("eoLogger");
|
||||
}
|
||||
|
||||
void eoLogger::addLevel(std::string name, eo::Levels level)
|
||||
{
|
||||
_levels[name] = level;
|
||||
_sortedLevels.push_back(name);
|
||||
}
|
||||
|
||||
void eoLogger::printLevels() const
|
||||
{
|
||||
std::cout << "Available verbose levels:" << std::endl;
|
||||
|
||||
for (std::vector<std::string>::const_iterator it = _sortedLevels.begin(), end = _sortedLevels.end();
|
||||
it != end; ++it)
|
||||
{
|
||||
std::cout << "\t" << *it << std::endl;
|
||||
}
|
||||
|
||||
::exit(0);
|
||||
}
|
||||
|
||||
eoLogger& operator<<(eoLogger& l, const eo::Levels lvl)
|
||||
{
|
||||
l._contextLevel = lvl;
|
||||
return l;
|
||||
}
|
||||
|
||||
eoLogger& operator<<(eoLogger& l, eo::file f)
|
||||
{
|
||||
l._fd = ::open(f._f.c_str(), O_WRONLY | O_APPEND | O_CREAT, 0644);
|
||||
return l;
|
||||
}
|
||||
|
||||
eoLogger& operator<<(eoLogger& l, eo::setlevel v)
|
||||
{
|
||||
l._selectedLevel = (v._lvl < 0 ? l._levels[v._v] : v._lvl);
|
||||
return l;
|
||||
}
|
||||
|
||||
eoLogger& operator<<(eoLogger& l, std::ostream& os)
|
||||
{
|
||||
if (l._standard_io_streams.find(&os) != l._standard_io_streams.end())
|
||||
{
|
||||
l._fd = l._standard_io_streams[&os];
|
||||
}
|
||||
return l;
|
||||
}
|
||||
|
||||
eoLogger::outbuf::outbuf(const int& fd,
|
||||
const eo::Levels& contexlvl,
|
||||
const eo::Levels& selectedlvl)
|
||||
: _fd(fd), _contextLevel(contexlvl), _selectedLevel(selectedlvl)
|
||||
{}
|
||||
|
||||
int eoLogger::outbuf::overflow(int_type c)
|
||||
{
|
||||
if (_selectedLevel >= _contextLevel)
|
||||
{
|
||||
if (_fd >= 0 && c != EOF)
|
||||
{
|
||||
::write(_fd, &c, 1);
|
||||
}
|
||||
}
|
||||
return c;
|
||||
}
|
||||
|
||||
namespace eo
|
||||
{
|
||||
file::file(const std::string f)
|
||||
: _f(f)
|
||||
{}
|
||||
|
||||
setlevel::setlevel(const std::string v)
|
||||
: _v(v), _lvl((Levels)-1)
|
||||
{}
|
||||
|
||||
setlevel::setlevel(const Levels lvl)
|
||||
: _v(std::string("")), _lvl(lvl)
|
||||
{}
|
||||
}
|
||||
|
||||
void make_verbose(eoParser& parser)
|
||||
{
|
||||
eo::log._createParameters( parser );
|
||||
|
||||
eo::log << eo::setlevel(eo::log._verbose.value());
|
||||
}
|
||||
|
||||
eoLogger eo::log;
|
||||
288
eo/src/utils/eoLogger.h
Normal file
288
eo/src/utils/eoLogger.h
Normal file
|
|
@ -0,0 +1,288 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
/*
|
||||
(c) Thales group, 2010
|
||||
|
||||
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;
|
||||
version 2 of the License.
|
||||
|
||||
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: http://eodev.sourceforge.net
|
||||
|
||||
Authors:
|
||||
Johann Dréo <johann.dreo@thalesgroup.com>
|
||||
Caner Candan <caner.candan@thalesgroup.com>
|
||||
|
||||
*/
|
||||
|
||||
/** @defgroup Logging Logging
|
||||
* @ingroup Utilities
|
||||
|
||||
Global logger for EO.
|
||||
|
||||
Here's an example explaning how to use eoLogger:
|
||||
\code
|
||||
#include <eo>
|
||||
|
||||
int main(int ac, char** av)
|
||||
{
|
||||
// We are declaring the usual eoParser class
|
||||
eoParser parser(ac, av);
|
||||
|
||||
// This call is important to allow -v parameter to change user level.
|
||||
make_verbose(parser);
|
||||
|
||||
// At this time we are switching to warning message and messages
|
||||
// which are going to follow it are going to be warnings message too.
|
||||
// These messages can be displayed only if the user level (sets with
|
||||
// eo::setlevel function) is set to eo::warnings.
|
||||
eo::log << eo::warnings;
|
||||
|
||||
// With the following eo::file function we are defining that
|
||||
// all future logs are going to this new file resource which is
|
||||
// test.txt
|
||||
eo::log << eo::file("test.txt") << "In FILE" << std::endl;
|
||||
|
||||
// Now we are changing again the resources destination to cout which
|
||||
// is the standard output.
|
||||
eo::log << std::cout << "In COUT" << std::endl;
|
||||
|
||||
// Here are 2 differents examples of how to set the errors user level
|
||||
// in using either a string or an identifier.
|
||||
eo::log << eo::setlevel("errors");
|
||||
eo::log << eo::setlevel(eo::errors);
|
||||
|
||||
// Now we are writting a message, that will be displayed only if we are above the "quiet" level
|
||||
eo::log << eo::quiet << "1) Must be in quiet mode to see that" << std::endl;
|
||||
|
||||
// And so on...
|
||||
eo::log << eo::setlevel(eo::warnings) << eo::warnings << "2) Must be in warnings mode to see that" << std::endl;
|
||||
|
||||
eo::log << eo::setlevel(eo::logging);
|
||||
|
||||
eo::log << eo::errors;
|
||||
eo::log << "3) Must be in errors mode to see that";
|
||||
eo::log << std::endl;
|
||||
|
||||
eo::log << eo::debug << 4 << ')'
|
||||
<< " Must be in debug mode to see that\n";
|
||||
|
||||
return 0;
|
||||
}
|
||||
\endcode
|
||||
|
||||
@{
|
||||
*/
|
||||
|
||||
#ifndef eoLogger_h
|
||||
#define eoLogger_h
|
||||
|
||||
#include <map>
|
||||
#include <vector>
|
||||
#include <string>
|
||||
#include <iosfwd>
|
||||
|
||||
#include "eoObject.h"
|
||||
#include "eoParser.h"
|
||||
|
||||
namespace eo
|
||||
{
|
||||
/**
|
||||
* Levels contents all the available levels in eoLogger
|
||||
*
|
||||
* /!\ If you want to add a level dont forget to add it at the implementation of the class eoLogger in the ctor
|
||||
*/
|
||||
enum Levels {quiet = 0,
|
||||
errors,
|
||||
warnings,
|
||||
progress,
|
||||
logging,
|
||||
debug,
|
||||
xdebug};
|
||||
|
||||
/**
|
||||
* file
|
||||
* this structure combined with the friend operator<< below is an easy way to select a file as output.
|
||||
*/
|
||||
struct file
|
||||
{
|
||||
file(const std::string f);
|
||||
const std::string _f;
|
||||
};
|
||||
|
||||
/**
|
||||
* setlevel
|
||||
* this structure combined with the friend operator<< below is an easy way to set a verbose level.
|
||||
*/
|
||||
struct setlevel
|
||||
{
|
||||
setlevel(const std::string v);
|
||||
setlevel(const Levels lvl);
|
||||
const std::string _v;
|
||||
const Levels _lvl;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* eoLogger
|
||||
* Class providing a verbose management through EO
|
||||
* Use of a global variable eo::log to easily use the logger like std::cout
|
||||
*/
|
||||
class eoLogger : public eoObject,
|
||||
public std::ostream
|
||||
{
|
||||
public:
|
||||
//! default ctor
|
||||
eoLogger();
|
||||
|
||||
//! overidded ctor in order to instanciate a logger with a file define in parameter
|
||||
eoLogger(eo::file file);
|
||||
|
||||
//! dtor
|
||||
~eoLogger();
|
||||
|
||||
//! common function for all eo objects
|
||||
virtual std::string className() const;
|
||||
|
||||
//! Print the available levels on the standard output
|
||||
//! enablable with the option -l
|
||||
void printLevels() const;
|
||||
|
||||
/*! Returns the selected levels, that is the one asked by the user
|
||||
*
|
||||
* Use this function if you want to be able to compare selected levels to a given one, like:
|
||||
* if( eo::log.getLevelSelected() >= eo::progress ) {...}
|
||||
*/
|
||||
inline eo::Levels getLevelSelected() const { return _selectedLevel; }
|
||||
|
||||
/*! Returns the current level of the context
|
||||
* the one given when you output message with the logger
|
||||
*/
|
||||
inline eo::Levels getLevelContext() const { return _contextLevel; }
|
||||
|
||||
protected:
|
||||
//! in order to add a level of verbosity
|
||||
void addLevel(std::string name, eo::Levels level);
|
||||
|
||||
private:
|
||||
//! used by the function make_verbose in order to add options to specify the verbose level
|
||||
void _createParameters( eoParser& );
|
||||
|
||||
//! used by the set of ctors to initiate some useful variables
|
||||
void _init();
|
||||
|
||||
private:
|
||||
/**
|
||||
* outbuf
|
||||
* this class inherits from std::streambuf which is used by eoLogger to write the buffer in an output stream
|
||||
*/
|
||||
class outbuf : public std::streambuf
|
||||
{
|
||||
public:
|
||||
outbuf(const int& fd, const eo::Levels& contexlvl, const eo::Levels& selectedlvl);
|
||||
protected:
|
||||
virtual int overflow(int_type c);
|
||||
private:
|
||||
const int& _fd;
|
||||
const eo::Levels& _contextLevel;
|
||||
const eo::Levels& _selectedLevel;
|
||||
};
|
||||
|
||||
private:
|
||||
/**
|
||||
* MapLevel is the type used by the map member _levels.
|
||||
*/
|
||||
typedef std::map<std::string, eo::Levels> MapLevel;
|
||||
|
||||
public:
|
||||
/**
|
||||
* operator<< used there to set a verbose mode.
|
||||
*/
|
||||
//! in order to use stream style to define the context verbose level where the following logs will be saved
|
||||
friend eoLogger& operator<<(eoLogger&, const eo::Levels);
|
||||
|
||||
/**
|
||||
* operator<< used there to set a filename through the class file.
|
||||
*/
|
||||
//! in order to use stream style to define a file to dump instead the standart output
|
||||
friend eoLogger& operator<<(eoLogger&, eo::file);
|
||||
|
||||
/**
|
||||
* operator<< used there to set a verbose level through the class setlevel.
|
||||
*/
|
||||
//! in order to use stream style to define manually the verbose level instead using options
|
||||
friend eoLogger& operator<<(eoLogger&, eo::setlevel);
|
||||
|
||||
/**
|
||||
* operator<< used there to be able to use std::cout to say that we wish to redirect back the buffer to a standard output.
|
||||
*/
|
||||
//! in order to use stream style to go back to a standart output defined by STL
|
||||
//! and to get retro-compatibility
|
||||
friend eoLogger& operator<<(eoLogger&, std::ostream&);
|
||||
|
||||
private:
|
||||
friend void make_verbose(eoParser&);
|
||||
|
||||
eoValueParam<std::string> _verbose;
|
||||
eoValueParam<bool> _printVerboseLevels;
|
||||
eoValueParam<std::string> _output;
|
||||
|
||||
/**
|
||||
* _selectedLevel is the member storing verbose level setted by the user thanks to operator()
|
||||
*/
|
||||
eo::Levels _selectedLevel;
|
||||
eo::Levels _contextLevel;
|
||||
|
||||
/**
|
||||
* _fd in storing the file descriptor at this place we can disable easily the buffer in
|
||||
* changing the value at -1. It is used by operator <<.
|
||||
*/
|
||||
int _fd;
|
||||
|
||||
/**
|
||||
* _obuf std::ostream mandates to use a buffer. _obuf is a outbuf inheriting of std::streambuf.
|
||||
*/
|
||||
outbuf _obuf;
|
||||
|
||||
/**
|
||||
* _levels contains all the existing level order by position
|
||||
*/
|
||||
MapLevel _levels;
|
||||
|
||||
/**
|
||||
* _levelsOrder is just a list to keep the order of levels
|
||||
*/
|
||||
std::vector<std::string> _sortedLevels;
|
||||
|
||||
/**
|
||||
* _standard_io_streams
|
||||
*/
|
||||
std::map< std::ostream*, int > _standard_io_streams;
|
||||
};
|
||||
/** @example t-eoLogger.cpp
|
||||
*/
|
||||
|
||||
//! make_verbose gets level of verbose and sets it in eoLogger
|
||||
void make_verbose(eoParser&);
|
||||
|
||||
namespace eo
|
||||
{
|
||||
/**
|
||||
* log is an external global variable defined to easily use a same way than std::cout to write a log.
|
||||
*/
|
||||
extern eoLogger log;
|
||||
}
|
||||
|
||||
/** @} */
|
||||
|
||||
#endif // !eoLogger_h
|
||||
91
eo/src/utils/eoMOFitnessStat.h
Normal file
91
eo/src/utils/eoMOFitnessStat.h
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoFitnessStat.h
|
||||
// (c) Marc Schoenauer, Maarten Keijzer and GeNeura Team, 2000, 2001
|
||||
/*
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
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
|
||||
mkeijzer@dhi.dk
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _eoFitnessStat_h
|
||||
#define _eoFitnessStat_h
|
||||
|
||||
#include <utils/eoStat.h>
|
||||
|
||||
/**
|
||||
The fitnesses of a whole population, as a vector
|
||||
*/
|
||||
template <class EOT, class FitT = typename EOT::Fitness>
|
||||
class eoFitnessStat : public eoSortedStat<EOT, std::vector<FitT> >
|
||||
{
|
||||
public :
|
||||
|
||||
using eoSortedStat<EOT, std::vector<FitT> >::value;
|
||||
|
||||
eoFitnessStat(std::string _description = "AllFitnesses") :
|
||||
eoSortedStat<EOT,std::vector<FitT> >(std::vector<FitT>(0), _description) {}
|
||||
|
||||
virtual void operator()(const std::vector<const EOT*>& _popPters)
|
||||
{
|
||||
value().resize(_popPters.size());
|
||||
for (unsigned i=0; i<_popPters.size(); i++)
|
||||
value()[i] = _popPters[i]->fitness();
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/** For multi-objective fitness, we need to translate a stat<vector<double> >
|
||||
into a vector<stat>, so each objective gets a seperate stat
|
||||
*/
|
||||
#ifdef _MSC_VER
|
||||
// The follownig is needed to avoid some bug in Visual Studio 6.0
|
||||
typedef double PartFitDefault;
|
||||
template <class EOT, class PartFitT = PartFitDefault>
|
||||
class eoMOFitnessStat : public eoSortedStat<EOT, std::vector<PartFitT> >
|
||||
#else
|
||||
template <class EOT, class PartFitT = double>
|
||||
class eoMOFitnessStat : public eoSortedStat<EOT, std::vector<PartFitT> >
|
||||
#endif
|
||||
|
||||
{
|
||||
public:
|
||||
|
||||
using eoSortedStat<EOT, std::vector<PartFitT> >::value;
|
||||
|
||||
/** Ctor: say what component you want
|
||||
*/
|
||||
eoMOFitnessStat(unsigned _objective, std::string _description = "MO-Fitness") :
|
||||
eoSortedStat<EOT, std::vector<PartFitT> >(std::vector<PartFitT>(0), _description),
|
||||
objective(_objective) {}
|
||||
|
||||
virtual void operator()(const std::vector<const EOT*>& _popPters)
|
||||
{
|
||||
value().resize(_popPters.size());
|
||||
|
||||
for (unsigned i=0; i<_popPters.size(); i++)
|
||||
{
|
||||
value()[i] = _popPters[i]->fitness()[objective];
|
||||
}
|
||||
}
|
||||
private:
|
||||
unsigned int objective; // The objective we're storing
|
||||
|
||||
};
|
||||
#endif
|
||||
80
eo/src/utils/eoMonitor.h
Normal file
80
eo/src/utils/eoMonitor.h
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
// (c) Marc Schoenauer, Maarten Keijzer and GeNeura Team, 2000
|
||||
/*
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
|
||||
Marc.Schoenauer@polytechnique.fr
|
||||
mak@dhi.dk
|
||||
*/
|
||||
|
||||
#ifndef _eoMonitor_h
|
||||
#define _eoMonitor_h
|
||||
|
||||
|
||||
#include <vector>
|
||||
#include <iostream>
|
||||
#include <eoFunctor.h>
|
||||
|
||||
/** @defgroup Monitors Monitoring
|
||||
*
|
||||
* Monitors take a set of value parameters (eoValueParam) objects and
|
||||
* output them on a given stream, file, pipe, etc.
|
||||
*
|
||||
* They can be called from within an eoCheckPoint, to print different values
|
||||
* of parameters or of eoStat at each generation.
|
||||
*
|
||||
* @see eoCheckPoint
|
||||
* @see eoStat
|
||||
* @ingroup Utilities
|
||||
*/
|
||||
|
||||
|
||||
class eoParam;
|
||||
template <class EOT> class eoCheckPoint;
|
||||
|
||||
/**
|
||||
The abstract monitor class is a std::vector of parameter pointers. Use
|
||||
either push_back a pointer or add a reference to a parameter.
|
||||
Derived classes will then implement the operator()(void) which
|
||||
will stream or pipe the current values of the parameters to wherever you
|
||||
want it streamed or piped to.
|
||||
|
||||
@ingroup Monitors
|
||||
*/
|
||||
class eoMonitor : public eoF<eoMonitor&>
|
||||
{
|
||||
public :
|
||||
|
||||
virtual void lastCall() {}
|
||||
|
||||
/**
|
||||
Adds a parameter to the monitor. It is virtual so you can do some type checking
|
||||
in derived classes if you must.
|
||||
*/
|
||||
virtual void add(const eoParam& _param) { vec.push_back(&_param); }
|
||||
|
||||
virtual std::string className(void) const { return "eoMonitor"; }
|
||||
|
||||
template <class EOT>
|
||||
eoMonitor& addTo(eoCheckPoint<EOT>& cp) { cp.add(*this); return *this; }
|
||||
|
||||
protected :
|
||||
typedef std::vector<const eoParam*>::iterator iterator;
|
||||
std::vector<const eoParam*> vec;
|
||||
};
|
||||
|
||||
#endif
|
||||
58
eo/src/utils/eoOStreamMonitor.cpp
Normal file
58
eo/src/utils/eoOStreamMonitor.cpp
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
#ifdef _MSC_VER
|
||||
// to avoid long name warnings
|
||||
#pragma warning(disable:4786)
|
||||
#endif
|
||||
|
||||
#include <iostream>
|
||||
#include <fstream>
|
||||
#include <stdexcept>
|
||||
#include <iomanip>
|
||||
#include <ios>
|
||||
|
||||
#include <utils/eoOStreamMonitor.h>
|
||||
#include <utils/compatibility.h>
|
||||
#include <utils/eoParam.h>
|
||||
#include <eoLogger.h>
|
||||
|
||||
//using namespace std;
|
||||
|
||||
eoMonitor& eoOStreamMonitor::operator()(void)
|
||||
{
|
||||
if (!out) {
|
||||
std::string str = "eoOStreamMonitor: Could not write to the ooutput stream";
|
||||
throw std::runtime_error(str);
|
||||
}
|
||||
|
||||
if (firsttime) {
|
||||
|
||||
eo::log << eo::debug << "First Generation" << std::endl;
|
||||
|
||||
for (iterator it = vec.begin (); it != vec.end (); ++it) {
|
||||
out << (*it)->longName ();
|
||||
out << delim << std::left << std::setfill(fill) << std::setw(width);
|
||||
}
|
||||
out << std::endl;
|
||||
|
||||
firsttime = false;
|
||||
} // if firstime
|
||||
|
||||
// ok, now the real saving. write out
|
||||
//! @todo old verbose formatting, do we still need it?
|
||||
/*
|
||||
for (iterator it = vec.begin (); it != vec.end (); ++it) {
|
||||
// name: value
|
||||
out << (*it)->longName () << ": " << (*it)->getValue () << std::endl;
|
||||
} // for it in vec
|
||||
*/
|
||||
|
||||
for (iterator it = vec.begin (); it != vec.end (); ++it) {
|
||||
// value only
|
||||
out << (*it)->getValue ();
|
||||
out << delim << std::left << std::setfill(fill) << std::setw(width);
|
||||
} // for it in vec
|
||||
|
||||
out << std::endl;
|
||||
eo::log << eo::debug << "End of Generation" << std::endl;
|
||||
|
||||
return *this;
|
||||
}
|
||||
72
eo/src/utils/eoOStreamMonitor.h
Normal file
72
eo/src/utils/eoOStreamMonitor.h
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
/*
|
||||
|
||||
(c) Marc Schoenauer, Maarten Keijzer and GeNeura Team, 2000
|
||||
(c) Thales group, 2010
|
||||
|
||||
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; version 2 of the license.
|
||||
|
||||
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: http://eodev.sourceforge.net
|
||||
|
||||
Authors:
|
||||
todos@geneura.ugr.es
|
||||
Marc.Schoenauer@polytechnique.fr
|
||||
mkeijzer@dhi.dk
|
||||
Johann Dréo <johann.dreo@thalesgroup.com>
|
||||
*/
|
||||
|
||||
#ifndef _eoOStreamMonitor_h_
|
||||
#define _eoOStreamMonitor_h_
|
||||
|
||||
#include <string>
|
||||
#include <iostream>
|
||||
|
||||
#include <utils/eoMonitor.h>
|
||||
#include <utils/eoLogger.h>
|
||||
#include <eoObject.h>
|
||||
|
||||
/**
|
||||
Prints statistics to a given ostream.
|
||||
|
||||
You can pass any instance of an ostream to the constructor, like, for example, std::clog.
|
||||
|
||||
@ingroup Monitors
|
||||
*/
|
||||
class eoOStreamMonitor : public eoMonitor
|
||||
{
|
||||
public :
|
||||
eoOStreamMonitor( std::ostream & _out, bool /*_verbose*/=true, std::string _delim = "\t", unsigned int _width=20, char _fill=' ' ) :
|
||||
out(_out), delim(_delim), width(_width), fill(_fill), firsttime(true)
|
||||
{
|
||||
#ifndef DEPRECATED_MESSAGES
|
||||
eo::log << eo::warnings << "WARNING: the use of the verbose parameter in eoOStreamMonitor constructor is deprecated and will be removed in the next release" << std::endl;
|
||||
#pragma message "WARNING: the use of the verbose parameter in eoOStreamMonitor constructor is deprecated and will be removed in the next release"
|
||||
#endif // !DEPRECATED_MESSAGES
|
||||
}
|
||||
|
||||
eoOStreamMonitor( std::ostream & _out, std::string _delim = "\t", unsigned int _width=20, char _fill=' ' ) :
|
||||
out(_out), delim(_delim), width(_width), fill(_fill), firsttime(true)
|
||||
{}
|
||||
|
||||
eoMonitor& operator()(void);
|
||||
|
||||
virtual std::string className(void) const { return "eoOStreamMonitor"; }
|
||||
|
||||
private :
|
||||
std::ostream & out;
|
||||
std::string delim;
|
||||
unsigned int width;
|
||||
char fill;
|
||||
bool firsttime;
|
||||
};
|
||||
|
||||
#endif // _eoOStreamMonitor_h_
|
||||
115
eo/src/utils/eoParallel.cpp
Normal file
115
eo/src/utils/eoParallel.cpp
Normal file
|
|
@ -0,0 +1,115 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
/*
|
||||
|
||||
(c) Thales group, 2010
|
||||
|
||||
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;
|
||||
version 2 of the license.
|
||||
|
||||
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: http://eodev.sourceforge.net
|
||||
|
||||
Authors:
|
||||
Caner Candan <caner.candan@thalesgroup.com>
|
||||
|
||||
*/
|
||||
|
||||
#include <omp.h>
|
||||
|
||||
#include "eoParallel.h"
|
||||
#include "eoLogger.h"
|
||||
|
||||
eoParallel::eoParallel() :
|
||||
_isEnabled( false, "parallelize-loop", "Enable memory shared parallelization into evaluation's loops", '\0' ),
|
||||
_isDynamic( false, "parallelize-dynamic", "Enable dynamic memory shared parallelization", '\0' ),
|
||||
_prefix( "results", "parallelize-prefix", "Here's the prefix filename where the results are going to be stored", '\0' ),
|
||||
_nthreads( 0, "parallelize-nthreads", "Define the number of threads you want to use, nthreads = 0 means you want to use all threads available", '\0' ),
|
||||
_enableResults( false, "parallelize-enable-results", "Enable the generation of results", '\0' ),
|
||||
_doMeasure( false, "parallelize-do-measure", "Do some measures during execution", '\0' ),
|
||||
_t_start(0)
|
||||
{
|
||||
}
|
||||
|
||||
eoParallel::~eoParallel()
|
||||
{
|
||||
#ifdef _OPENMP
|
||||
if ( doMeasure() )
|
||||
{
|
||||
double _t_end = omp_get_wtime();
|
||||
eoLogger log;
|
||||
log << eo::file("measure_" + prefix()) << _t_end - _t_start << std::endl;
|
||||
}
|
||||
#endif // !_OPENMP
|
||||
}
|
||||
|
||||
std::string eoParallel::className() const
|
||||
{
|
||||
return "eoParallel";
|
||||
}
|
||||
|
||||
std::string eoParallel::prefix() const
|
||||
{
|
||||
std::string value( _prefix.value() );
|
||||
|
||||
if ( _isEnabled.value() )
|
||||
{
|
||||
if ( _isDynamic.value() )
|
||||
{
|
||||
value += "_dynamic.out";
|
||||
}
|
||||
else
|
||||
{
|
||||
value += "_parallel.out";
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
value += "_sequential.out";
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
void eoParallel::_createParameters( eoParser& parser )
|
||||
{
|
||||
std::string section("Parallelization");
|
||||
parser.processParam( _isEnabled, section );
|
||||
parser.processParam( _isDynamic, section );
|
||||
parser.processParam( _prefix, section );
|
||||
parser.processParam( _nthreads, section );
|
||||
parser.processParam( _enableResults, section );
|
||||
parser.processParam( _doMeasure, section );
|
||||
}
|
||||
|
||||
void make_parallel(eoParser& parser)
|
||||
{
|
||||
eo::parallel._createParameters( parser );
|
||||
|
||||
#ifdef _OPENMP
|
||||
if ( eo::parallel.isEnabled() )
|
||||
{
|
||||
if ( eo::parallel.nthreads() > 0 )
|
||||
{
|
||||
omp_set_num_threads( eo::parallel.nthreads() );
|
||||
}
|
||||
}
|
||||
|
||||
if ( eo::parallel.doMeasure() )
|
||||
{
|
||||
eo::parallel._t_start = omp_get_wtime();
|
||||
}
|
||||
#endif // !_OPENMP
|
||||
}
|
||||
|
||||
eoParallel eo::parallel;
|
||||
88
eo/src/utils/eoParallel.h
Normal file
88
eo/src/utils/eoParallel.h
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
/*
|
||||
(c) Thales group, 2010
|
||||
|
||||
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;
|
||||
version 2 of the License.
|
||||
|
||||
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: http://eodev.sourceforge.net
|
||||
|
||||
Authors:
|
||||
Caner Candan <caner.candan@thalesgroup.com>
|
||||
|
||||
*/
|
||||
|
||||
/** @defgroup Parallel Parallel
|
||||
* @ingroup Utilities
|
||||
@{
|
||||
*/
|
||||
|
||||
#ifndef eoParallel_h
|
||||
#define eoParallel_h
|
||||
|
||||
#include "eoObject.h"
|
||||
#include "eoParser.h"
|
||||
|
||||
/**
|
||||
* eoParallel
|
||||
* Class providing parameters for parallelization
|
||||
* Use of a global variable eo::parallel to easily use the parallelization parameters anywhere
|
||||
*/
|
||||
class eoParallel : public eoObject
|
||||
{
|
||||
public:
|
||||
eoParallel();
|
||||
~eoParallel();
|
||||
|
||||
virtual std::string className() const;
|
||||
|
||||
inline bool isEnabled() const { return _isEnabled.value(); }
|
||||
inline bool isDynamic() const { return _isDynamic.value(); }
|
||||
|
||||
std::string prefix() const;
|
||||
|
||||
inline unsigned int nthreads() const { return _nthreads.value(); }
|
||||
|
||||
inline bool enableResults() const { return _enableResults.value(); }
|
||||
inline bool doMeasure() const { return _doMeasure.value(); }
|
||||
|
||||
friend void make_parallel(eoParser&);
|
||||
|
||||
private:
|
||||
void _createParameters( eoParser& );
|
||||
|
||||
private:
|
||||
eoValueParam<bool> _isEnabled;
|
||||
eoValueParam<bool> _isDynamic;
|
||||
eoValueParam<std::string> _prefix;
|
||||
eoValueParam<unsigned int> _nthreads;
|
||||
eoValueParam<bool> _enableResults;
|
||||
eoValueParam<bool> _doMeasure;
|
||||
double _t_start;
|
||||
};
|
||||
|
||||
void make_parallel(eoParser&);
|
||||
|
||||
namespace eo
|
||||
{
|
||||
/**
|
||||
* parallel is an external global variable defined in order to use where ever you want the parallel parameters
|
||||
*/
|
||||
extern eoParallel parallel;
|
||||
}
|
||||
|
||||
/** @} */
|
||||
|
||||
#endif // !eoParallel_h
|
||||
486
eo/src/utils/eoParam.h
Normal file
486
eo/src/utils/eoParam.h
Normal file
|
|
@ -0,0 +1,486 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoParam.h
|
||||
// (c) Marc Schoenauer, Maarten Keijzer and GeNeura Team, 2000
|
||||
/*
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
|
||||
Marc.Schoenauer@polytechnique.fr
|
||||
mkeijzer@dhi.dk
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef eoParam_h
|
||||
#define eoParam_h
|
||||
|
||||
#include <cmath>
|
||||
#include <iterator>
|
||||
#include <stdexcept>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <eoScalarFitness.h>
|
||||
|
||||
/** @defgroup Parameters Parameters management
|
||||
*
|
||||
* A parameter is basically an object that stores a value and that can read/print it from/on streams.
|
||||
*
|
||||
* It is mainly used for command-line options (see eoParser) and eoStat.
|
||||
*
|
||||
* @ingroup Utilities
|
||||
* @{
|
||||
*/
|
||||
|
||||
/**
|
||||
eoParam: Base class for monitoring and parsing parameters
|
||||
*/
|
||||
class eoParam
|
||||
{
|
||||
public:
|
||||
|
||||
/** Empty constructor - called from outside any parser */
|
||||
eoParam ()
|
||||
: repLongName(""), repDefault(""), repDescription(""),
|
||||
repShortHand(0), repRequired(false)
|
||||
{}
|
||||
|
||||
/** Construct a Param.
|
||||
*
|
||||
* @param _longName Long name of the argument
|
||||
* @param _default The default value
|
||||
* @param _description Description of the parameter. What is useful for.
|
||||
* @param _shortName Short name of the argument (Optional)
|
||||
* @param _required If it is a necessary parameter or not
|
||||
*/
|
||||
eoParam (std::string _longName, std::string _default,
|
||||
std::string _description, char _shortName = 0, bool _required = false)
|
||||
: repLongName(_longName), repDefault(_default),
|
||||
repDescription(_description ),
|
||||
repShortHand(_shortName), repRequired( _required)
|
||||
{}
|
||||
|
||||
/**
|
||||
* Virtual destructor is needed.
|
||||
*/
|
||||
virtual ~eoParam () {}
|
||||
|
||||
/**
|
||||
* Pure virtual function to get the value out.
|
||||
*/
|
||||
virtual std::string getValue () const = 0;
|
||||
|
||||
/**
|
||||
* Pure virtual function to set the value
|
||||
*/
|
||||
virtual void setValue(const std::string& _value) = 0 ;
|
||||
|
||||
/**
|
||||
* Returns the short name.
|
||||
*/
|
||||
char shortName() const { return repShortHand; };
|
||||
|
||||
/**
|
||||
* Returns the long name.
|
||||
*/
|
||||
const std::string& longName() const { return repLongName; };
|
||||
|
||||
/**
|
||||
* Returns the description of the argument
|
||||
*/
|
||||
const std::string& description() const { return repDescription; };
|
||||
|
||||
/**
|
||||
* Returns the default value of the argument
|
||||
*/
|
||||
const std::string& defValue() const { return repDefault; };
|
||||
|
||||
/**
|
||||
* Sets the default value of the argument,
|
||||
*/
|
||||
void defValue( const std::string& str ) { repDefault = str; };
|
||||
|
||||
/**
|
||||
* ALlows to change the name (see the prefix in eoParser.h)
|
||||
*/
|
||||
void setLongName(std::string _longName) { repLongName = _longName;}
|
||||
|
||||
/**
|
||||
* Returns if required or not.
|
||||
*/
|
||||
bool required() const { return repRequired; };
|
||||
|
||||
private:
|
||||
std::string repLongName;
|
||||
std::string repDefault;
|
||||
std::string repDescription;
|
||||
char repShortHand;
|
||||
bool repRequired;
|
||||
};
|
||||
|
||||
|
||||
|
||||
/**
|
||||
eoValueParam<ValueType>: templatized derivation of eoParam. Can be used to contain
|
||||
any scalar value type. It makes use of std::strstream to get and set values.
|
||||
|
||||
@todo This should be changed to std::stringstream when that class is available in g++.
|
||||
|
||||
Note also that there is a template specialization for std::pair<double, double> and
|
||||
for std::vector<double>. These stream their contents delimited with whitespace.
|
||||
*/
|
||||
template <class ValueType>
|
||||
class eoValueParam : public eoParam
|
||||
{
|
||||
public :
|
||||
|
||||
/** Construct a Param. */
|
||||
eoValueParam(void) : eoParam() {}
|
||||
|
||||
/** Construct a Param.
|
||||
*
|
||||
* @param _defaultValue The default value
|
||||
* @param _longName Long name of the argument
|
||||
* @param _description Description of the parameter. What is useful for.
|
||||
* @param _shortHand Short name of the argument (Optional)
|
||||
* @param _required If it is a necessary parameter or not
|
||||
*/
|
||||
eoValueParam(ValueType _defaultValue,
|
||||
std::string _longName,
|
||||
std::string _description = "No description",
|
||||
char _shortHand = 0,
|
||||
bool _required = false)
|
||||
: eoParam(_longName, "", _description, _shortHand, _required),
|
||||
repValue(_defaultValue)
|
||||
{
|
||||
eoParam::defValue(getValue());
|
||||
}
|
||||
|
||||
/** Get a reference on the parameter value
|
||||
|
||||
@return parameter value
|
||||
*/
|
||||
ValueType& value() { return repValue; }
|
||||
|
||||
/** Get a const reference on the parameter value
|
||||
|
||||
@overload
|
||||
|
||||
@return parameter value
|
||||
*/
|
||||
const ValueType& value() const { return repValue; }
|
||||
|
||||
|
||||
/** Change the parameter value
|
||||
*/
|
||||
void value( ValueType val )
|
||||
{
|
||||
// convert to string
|
||||
std::ostringstream os;
|
||||
os << val;
|
||||
|
||||
// convert to ValueType
|
||||
std::istringstream is( os.str() );
|
||||
is >> repValue;
|
||||
}
|
||||
|
||||
|
||||
/** Get the string representation of the value
|
||||
*/
|
||||
std::string getValue(void) const
|
||||
{
|
||||
std::ostringstream os;
|
||||
os << repValue;
|
||||
return os.str();
|
||||
}
|
||||
|
||||
|
||||
/** @brief Set the value according to the speciied string
|
||||
|
||||
For scalar types the textual represenation is typically quite
|
||||
straigtforward.
|
||||
|
||||
For vector<double> we expect a list of numbers, where the first is
|
||||
an unsigned integer taken as the length ot the vector and then
|
||||
successively the vector elements. Vector elements can be separated
|
||||
by ',', ';', or ' '. Note, however, that eoParser does not deal
|
||||
correctly with parameter values contianing spaces (' ').
|
||||
|
||||
@param _value Textual representation of the new value
|
||||
*/
|
||||
void setValue(const std::string& _value)
|
||||
{
|
||||
std::istringstream is(_value);
|
||||
is >> repValue;
|
||||
}
|
||||
|
||||
protected:
|
||||
|
||||
ValueType repValue;
|
||||
};
|
||||
|
||||
/*
|
||||
Specialization for std::string
|
||||
*/
|
||||
template <>
|
||||
inline std::string eoValueParam<std::string>::getValue() const
|
||||
{
|
||||
return repValue;
|
||||
}
|
||||
|
||||
|
||||
template <>
|
||||
inline void eoValueParam<bool>::setValue(const std::string& _value)
|
||||
{
|
||||
if (_value.empty())
|
||||
{
|
||||
repValue = true;
|
||||
return;
|
||||
}
|
||||
std::istringstream is(_value);
|
||||
is >> repValue;
|
||||
}
|
||||
|
||||
|
||||
/// Because MSVC does not support partial specialization, the std::pair is a double, not a T
|
||||
template <>
|
||||
inline std::string eoValueParam<std::pair<double, double> >::getValue(void) const
|
||||
{
|
||||
// use own buffer as MSVC's buffer leaks!
|
||||
std::ostringstream os;
|
||||
os << repValue.first << ' ' << repValue.second;
|
||||
return os.str();
|
||||
}
|
||||
|
||||
/// Because MSVC does not support partial specialization, the std::pair is a double, not a T
|
||||
template <>
|
||||
inline void eoValueParam<std::pair<double, double> >::setValue(const std::string& _value)
|
||||
{
|
||||
std::istringstream is(_value);
|
||||
is >> repValue.first;
|
||||
is >> repValue.second;
|
||||
}
|
||||
|
||||
// The std::vector<std::vector<double> >
|
||||
//////////////////////////////////
|
||||
/// Because MSVC does not support partial specialization, the std::vector is a std::vector of doubles, not a T
|
||||
template <>
|
||||
inline std::string eoValueParam<std::vector<std::vector<double> > >::getValue(void) const
|
||||
{
|
||||
std::ostringstream os;
|
||||
os << repValue.size() << ' ';
|
||||
for (unsigned i = 0; i < repValue.size(); ++i)
|
||||
{
|
||||
os << repValue[i].size() << ' ';
|
||||
std::copy(repValue[i].begin(), repValue[i].end(), std::ostream_iterator<double>(os, " "));
|
||||
}
|
||||
return os.str();
|
||||
}
|
||||
|
||||
/// Because MSVC does not support partial specialization, the std::vector is a std::vector of doubles, not a T
|
||||
template <>
|
||||
inline void eoValueParam<std::vector<std::vector<double> > >::setValue(const std::string& _value)
|
||||
{
|
||||
std::istringstream is(_value);
|
||||
unsigned i,j,sz;
|
||||
is >> sz;
|
||||
repValue.resize(sz);
|
||||
|
||||
for (i = 0; i < repValue.size(); ++i)
|
||||
{
|
||||
unsigned sz2;
|
||||
is >> sz2;
|
||||
repValue[i].resize(sz2);
|
||||
for (j = 0; j < sz2; ++j)
|
||||
{
|
||||
is >> repValue[i][j];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The std::vector<double>
|
||||
//////////////////////////////////
|
||||
/// Because MSVC does not support partial specialization, the std::vector is a double, not a T
|
||||
template <>
|
||||
inline std::string eoValueParam<std::vector<double> >::getValue(void) const
|
||||
{
|
||||
std::ostringstream os;
|
||||
os << repValue.size() << ' ';
|
||||
std::copy(repValue.begin(), repValue.end(), std::ostream_iterator<double>(os, " "));
|
||||
return os.str();
|
||||
}
|
||||
|
||||
/// Because MSVC does not support partial specialization, the std::vector is a double, not a T
|
||||
template <>
|
||||
inline void eoValueParam<std::vector<double> >::setValue(const std::string& _value)
|
||||
{
|
||||
static const std::string delimiter(",;");
|
||||
std::istringstream is(_value);
|
||||
unsigned sz;
|
||||
is >> sz;
|
||||
repValue.resize(sz);
|
||||
for(unsigned i=0; i<repValue.size(); ++i) {
|
||||
char c;
|
||||
do {
|
||||
is >> c;
|
||||
} while((std::string::npos != delimiter.find(c)) && (! is.eof()));
|
||||
is >> repValue[i];
|
||||
}
|
||||
}
|
||||
|
||||
// The std::vector<eoMinimizingFitness>
|
||||
//////////////////////////////////
|
||||
/// Because MSVC does not support partial specialization, the std::vector is a eoMinimizingFitness, not a T
|
||||
template <>
|
||||
inline std::string eoValueParam<std::vector<eoMinimizingFitness> >::getValue(void) const
|
||||
{
|
||||
std::ostringstream os;
|
||||
os << repValue.size() << ' ';
|
||||
std::copy(repValue.begin(), repValue.end(), std::ostream_iterator<eoMinimizingFitness>(os, " "));
|
||||
return os.str();
|
||||
}
|
||||
|
||||
/// Because MSVC does not support partial specialization, the std::vector is a eoMinimizingFitness, not a T
|
||||
// NOTE: g++ doesn support it either!!!
|
||||
template <>
|
||||
inline void eoValueParam<std::vector<eoMinimizingFitness> >::setValue(const std::string& _value)
|
||||
{
|
||||
std::istringstream is(_value);
|
||||
unsigned sz;
|
||||
is >> sz;
|
||||
repValue.resize(sz);
|
||||
std::copy(std::istream_iterator<eoMinimizingFitness>(is), std::istream_iterator<eoMinimizingFitness>(), repValue.begin());
|
||||
}
|
||||
|
||||
// The std::vector<const EOT*>
|
||||
//////////////////////////////////
|
||||
template <>
|
||||
inline std::string eoValueParam<std::vector<void*> >::getValue(void) const
|
||||
{
|
||||
throw std::runtime_error("I cannot getValue for a std::vector<EOT*>");
|
||||
return std::string("");
|
||||
}
|
||||
|
||||
template <>
|
||||
inline void eoValueParam<std::vector<void*> >::setValue(const std::string&)
|
||||
{
|
||||
throw std::runtime_error("I cannot setValue for a std::vector<EOT*>");
|
||||
return;
|
||||
}
|
||||
|
||||
/*template <class ContainerType>
|
||||
class eoContainerParam : public eoParam
|
||||
{
|
||||
public :
|
||||
eoContainerParam (ContainerType& value, std::string _shortName, std::string _longName,
|
||||
std::string _default,
|
||||
std::string _description,
|
||||
bool _required,
|
||||
bool _change )
|
||||
: value(_value), eoParam(_shortName, _longName, _description, _default, _required, _change)
|
||||
{}
|
||||
|
||||
|
||||
// void setValue(const std::string & _value)
|
||||
// {
|
||||
// std::istd::stringstream is(_value);
|
||||
// copy(std::istream_iterator<Container::value_type>(is), std::istream_iterator<Container::value_type>(), back_inserter(value));
|
||||
// }
|
||||
|
||||
private :
|
||||
ContainerType& value;
|
||||
};*/
|
||||
|
||||
/**
|
||||
* Another helper class for parsing parameters like
|
||||
* Keyword(arg1, arg2, ...)
|
||||
*
|
||||
* It is basically a std::pair<std::string,std::vector<std::string> >
|
||||
* first std::string is keyword
|
||||
* the std::vector<std::string> contains all arguments (as std::strings)
|
||||
* See make_algo.h
|
||||
*/
|
||||
|
||||
class eoParamParamType : public std::pair<std::string,std::vector<std::string> >
|
||||
{
|
||||
public:
|
||||
eoParamParamType(std::string _value)
|
||||
{
|
||||
readFrom(_value);
|
||||
}
|
||||
|
||||
std::ostream & printOn(std::ostream & _os) const
|
||||
{
|
||||
_os << first;
|
||||
unsigned narg = second.size();
|
||||
if (!narg)
|
||||
return _os;
|
||||
|
||||
// Here, we do have args
|
||||
_os << "(";
|
||||
if (narg == 1) // 1 arg only
|
||||
{
|
||||
_os << second[0] << ")" ;
|
||||
return _os;
|
||||
}
|
||||
// and here more than 1 arg
|
||||
for (unsigned i=0; i<narg-1; i++)
|
||||
_os << second[i] << "," ;
|
||||
_os << second[narg-1] << ")";
|
||||
return _os;
|
||||
}
|
||||
|
||||
std::istream & readFrom(std::istream & _is)
|
||||
{
|
||||
std::string value;
|
||||
_is >> value;
|
||||
readFrom(value);
|
||||
return _is;
|
||||
}
|
||||
|
||||
void readFrom(std::string & _value)
|
||||
{
|
||||
second.resize(0); // just in case
|
||||
size_t pos = _value.find('(');
|
||||
if (pos >= _value.size()) // no arguments
|
||||
{
|
||||
first = _value;
|
||||
return;
|
||||
}
|
||||
// so here we do have arguments
|
||||
std::string t = _value.substr(pos+1);// the arguments
|
||||
_value.resize(pos);
|
||||
first = _value; // done for the keyword (NOTE: may be empty std::string!)
|
||||
|
||||
// now all arguments
|
||||
std::string delim(" (),");
|
||||
while ( (pos=t.find_first_not_of(delim)) < t.size())
|
||||
{
|
||||
size_t posEnd = t.find_first_of(delim, pos);
|
||||
std::string u = t.substr(pos,posEnd);//(t, pos);
|
||||
/*u.resize(posEnd - pos);*/
|
||||
second.push_back(u);
|
||||
t = t.substr(posEnd+1);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// at the moment, the following are defined in eoParser.cpp
|
||||
std::ostream & operator<<(std::ostream & _os, const eoParamParamType & _rate);
|
||||
std::istream & operator>>(std::istream & _is, eoParamParamType & _rate);
|
||||
|
||||
/** @} */
|
||||
#endif
|
||||
451
eo/src/utils/eoParser.cpp
Normal file
451
eo/src/utils/eoParser.cpp
Normal file
|
|
@ -0,0 +1,451 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoParser.cpp
|
||||
// (c) Marc Schoenauer, Maarten Keijzer and GeNeura Team, 2000
|
||||
/*
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Contact: http://eodev.sourceforge.net
|
||||
Authors:
|
||||
todos@geneura.ugr.es, http://geneura.ugr.es
|
||||
Marc.Schoenauer@polytechnique.fr
|
||||
mkeijzer@dhi.dk
|
||||
Johann Dréo <johann.dreo@thalesgroup.com>
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifdef _MSC_VER
|
||||
#pragma warning(disable:4786)
|
||||
#endif
|
||||
|
||||
#include <stdexcept>
|
||||
#include <algorithm>
|
||||
#include <fstream>
|
||||
#include <iomanip>
|
||||
#include <cctype>
|
||||
|
||||
#include <utils/compatibility.h>
|
||||
#include <utils/eoParser.h>
|
||||
#include <utils/eoLogger.h>
|
||||
|
||||
|
||||
using namespace std;
|
||||
|
||||
std::ostream& printSectionHeader(std::ostream& os, std::string section)
|
||||
{
|
||||
if (section == "")
|
||||
section = "General";
|
||||
|
||||
// convert each character to upper case
|
||||
std::transform( section.begin(), section.end(), section.begin(), ::toupper);
|
||||
|
||||
// the formating with setfill would not permits to add this extra space as
|
||||
// one more call to stream operator, thus it is inserted here
|
||||
section += ' ';
|
||||
|
||||
// pretty print so as to print the section, followed by as many # as
|
||||
// necessary to fill the line until 80 characters
|
||||
os << std::endl
|
||||
<< "### "
|
||||
<< std::left
|
||||
<< std::setfill('#')
|
||||
<< std::setw(80) // TODO do not hard code the width of the line
|
||||
<< section
|
||||
<< std::endl;
|
||||
return os;
|
||||
}
|
||||
|
||||
eoParameterLoader::~eoParameterLoader()
|
||||
{
|
||||
for (unsigned i = 0; i < ownedParams.size(); ++i)
|
||||
{
|
||||
delete ownedParams[i];
|
||||
}
|
||||
}
|
||||
|
||||
eoParser::eoParser ( unsigned _argc, char **_argv , string _programDescription,
|
||||
string _lFileParamName, char _shortHand) :
|
||||
programName(_argv[0]),
|
||||
programDescription( _programDescription),
|
||||
needHelpMessage( false ),
|
||||
needHelp(false, "help", "Prints this message", 'h'),
|
||||
stopOnUnknownParam(true, "stopOnUnknownParam", "Stop if unkown param entered", '\0')
|
||||
{
|
||||
// need to process the param file first
|
||||
// if we want command-line to have highest priority
|
||||
unsigned i;
|
||||
for (i = 1; i < _argc; ++i)
|
||||
{
|
||||
if(_argv[i][0] == '@')
|
||||
{ // read response file
|
||||
char *pts = _argv[i]+1; // yes a char*, sorry :-)
|
||||
ifstream ifs (pts);
|
||||
ifs.peek(); // check if it exists
|
||||
if (!ifs)
|
||||
{
|
||||
string msg = string("Could not open response file: ") + pts;
|
||||
throw runtime_error(msg);
|
||||
}
|
||||
// read - will be overwritten by command-line
|
||||
readFrom(ifs);
|
||||
break; // stop reading command line args for '@'
|
||||
}
|
||||
}
|
||||
// now read arguments on command-line
|
||||
stringstream stream;
|
||||
for (i = 1; i < _argc; ++i)
|
||||
{
|
||||
stream << _argv[i] << '\n';
|
||||
}
|
||||
readFrom(stream);
|
||||
processParam(needHelp);
|
||||
processParam(stopOnUnknownParam);
|
||||
}
|
||||
|
||||
|
||||
std::string eoParser::get( const std::string & name) const
|
||||
{
|
||||
return getParamWithLongName( name )->getValue();
|
||||
}
|
||||
|
||||
|
||||
eoParam * eoParser::getParamWithLongName(const std::string& _name) const
|
||||
{
|
||||
typedef std::multimap<std::string, eoParam*> MultiMapType;
|
||||
typedef MultiMapType::const_iterator iter;
|
||||
std::string search(prefix+_name);
|
||||
for(iter p = params.begin(); p != params.end(); ++p)
|
||||
if(p->second->longName() == search)
|
||||
return p->second;
|
||||
return 0;
|
||||
}
|
||||
|
||||
eoParam * eoParser::getParam(const std::string& _name) const
|
||||
{
|
||||
eoParam * p = getParamWithLongName( _name );
|
||||
if( p == NULL ) {
|
||||
throw eoMissingParamException(_name );
|
||||
} else {
|
||||
return p;
|
||||
}
|
||||
}
|
||||
|
||||
void eoParser::processParam(eoParam& param, std::string section)
|
||||
{
|
||||
// this param enters the parser: add the prefix to the long name
|
||||
if (prefix != "")
|
||||
{
|
||||
param.setLongName(prefix+param.longName());
|
||||
section = prefix + section; // and to section
|
||||
}
|
||||
doRegisterParam(param); // plainly register it
|
||||
params.insert(make_pair(section, ¶m));
|
||||
}
|
||||
|
||||
void eoParser::doRegisterParam(eoParam& param)
|
||||
{
|
||||
if (param.required() && !isItThere(param))
|
||||
{
|
||||
string msg = "Required parameter: " + param.longName() + " missing";
|
||||
needHelpMessage = true;
|
||||
messages.push_back(msg);
|
||||
}
|
||||
pair<bool, string> value = getValue(param);
|
||||
if (value.first)
|
||||
{
|
||||
param.setValue(value.second);
|
||||
}
|
||||
}
|
||||
|
||||
pair<bool, string> eoParser::getValue(eoParam& _param) const
|
||||
{
|
||||
pair<bool, string> result(false, "");
|
||||
|
||||
if (_param.shortName() != 0)
|
||||
{
|
||||
map<char, string>::const_iterator it = shortNameMap.find(_param.shortName());
|
||||
if (it != shortNameMap.end())
|
||||
{
|
||||
result.second = it->second;
|
||||
result.first = true;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
map<string, string>::const_iterator it = longNameMap.find(_param.longName());
|
||||
if (it != longNameMap.end())
|
||||
{
|
||||
result.second = it->second;
|
||||
result.first = true;
|
||||
return result;
|
||||
}
|
||||
//! @todo check environment, just long names
|
||||
return result;
|
||||
}
|
||||
|
||||
void eoParser::updateParameters()
|
||||
{
|
||||
typedef MultiMapType::const_iterator It;
|
||||
|
||||
for (It p = params.begin(); p != params.end(); ++p)
|
||||
{
|
||||
doRegisterParam(*p->second);
|
||||
}
|
||||
}
|
||||
|
||||
void eoParser::readFrom(istream& is)
|
||||
{
|
||||
string str;
|
||||
// we must avoid processing \section{xxx} if xxx is NOT "Parser"
|
||||
bool processing = true;
|
||||
while (is >> str)
|
||||
{
|
||||
if (str.find(string("\\section{"))==0) // found section begin
|
||||
processing = (str.find(string("Parser"))<str.size());
|
||||
|
||||
if (processing) // right \section (or no \section at all)
|
||||
{
|
||||
if (str[0] == '#')
|
||||
{ // skip the rest of the line
|
||||
string tempStr;
|
||||
getline(is, tempStr);
|
||||
}
|
||||
if (str[0] == '-')
|
||||
{
|
||||
if (str.size() < 2)
|
||||
{
|
||||
eo::log << eo::warnings << "Missing parameter" << std::endl;
|
||||
needHelp.value() = true;
|
||||
return;
|
||||
}
|
||||
|
||||
if (str[1] == '-') // two consecutive dashes
|
||||
{
|
||||
string::iterator equalLocation = find(str.begin() + 2, str.end(), '=');
|
||||
string value;
|
||||
|
||||
if (equalLocation == str.end())
|
||||
{ //! @todo it should be the next string
|
||||
value = "";
|
||||
}
|
||||
else
|
||||
{
|
||||
value = string(equalLocation + 1, str.end());
|
||||
}
|
||||
|
||||
string name(str.begin() + 2, equalLocation);
|
||||
longNameMap[name] = value;
|
||||
}
|
||||
else // it should be a char
|
||||
{
|
||||
string value = "1"; // flags do not need a special
|
||||
|
||||
if (str.size() >= 2)
|
||||
{
|
||||
if (str[2] == '=')
|
||||
{
|
||||
if (str.size() >= 3)
|
||||
value = string(str.begin() + 3, str.end());
|
||||
}
|
||||
else
|
||||
{
|
||||
value = string(str.begin() + 2, str.end());
|
||||
}
|
||||
}
|
||||
|
||||
shortNameMap[str[1]] = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
updateParameters();
|
||||
}
|
||||
|
||||
void eoParser::printOn(ostream& os) const
|
||||
{
|
||||
typedef MultiMapType::const_iterator It;
|
||||
|
||||
It p = params.begin();
|
||||
|
||||
std::string section = p->first;
|
||||
|
||||
printSectionHeader(os, section);
|
||||
//print every param with its value
|
||||
for (; p != params.end(); ++p)
|
||||
{
|
||||
std::string newSection = p->first;
|
||||
|
||||
if (newSection != section)
|
||||
{
|
||||
section = newSection;
|
||||
printSectionHeader(os, section);
|
||||
}
|
||||
|
||||
eoParam* param = p->second;
|
||||
|
||||
if (!isItThere(*param)) // comment out the ones not set by the user
|
||||
os << "# ";
|
||||
|
||||
string str = "--" + param->longName() + "=" + param->getValue();
|
||||
|
||||
os.setf(ios_base::left, ios_base::adjustfield);
|
||||
os << setfill(' ') << setw(40) << str;
|
||||
|
||||
os << setw(0) << " # ";
|
||||
if (param->shortName())
|
||||
os << '-' << param->shortName() << " : ";
|
||||
os << param->description();
|
||||
|
||||
if (param->required())
|
||||
{
|
||||
os << " REQUIRED ";
|
||||
}
|
||||
|
||||
os << '\n';
|
||||
}
|
||||
}
|
||||
|
||||
void eoParser::printHelp(ostream& os)
|
||||
{
|
||||
if (needHelp.value() == false && !messages.empty())
|
||||
{
|
||||
std::copy(messages.begin(), messages.end(), ostream_iterator<string>(os, "\n"));
|
||||
messages.clear();
|
||||
return;
|
||||
}
|
||||
|
||||
// print program name and description
|
||||
os << this->programName <<": "<< programDescription << "\n\n";
|
||||
|
||||
// print the usage when calling the program from the command line
|
||||
os << "Usage: "<< programName<<" [Options]\n";
|
||||
// only short usage!
|
||||
os << "Options of the form \"-f[=Value]\" or \"--Name[=value]\"" << endl;
|
||||
|
||||
os << "Where:"<<endl;
|
||||
|
||||
typedef MultiMapType::const_iterator It;
|
||||
|
||||
It p = params.begin();
|
||||
|
||||
std::string section = p->first;
|
||||
|
||||
printSectionHeader(os, section);
|
||||
|
||||
//print every param with its value
|
||||
for (; p != params.end(); ++p)
|
||||
{
|
||||
std::string newSection = p->first;
|
||||
|
||||
if (newSection != section)
|
||||
{
|
||||
section = newSection;
|
||||
printSectionHeader(os, section);
|
||||
}
|
||||
|
||||
if (p->second->shortName())
|
||||
os << "-" << p->second->shortName() << ", ";
|
||||
|
||||
os << "--" <<p->second->longName() <<" :\t"
|
||||
<< p->second->description() ;
|
||||
|
||||
os << " (" << ( (p->second->required())?"required":"optional" );
|
||||
os <<", default: "<< p->second->defValue() << ')' << std::endl;
|
||||
} // for p
|
||||
|
||||
os << "\n@param_file \t defines a file where the parameters are stored\n";
|
||||
os << '\n';
|
||||
|
||||
}
|
||||
|
||||
bool eoParser::userNeedsHelp(void)
|
||||
{
|
||||
/*
|
||||
check whether there are long or short names entered
|
||||
without a corresponding parameter
|
||||
*/
|
||||
// first, check if we want to check that !
|
||||
if (stopOnUnknownParam.value())
|
||||
{
|
||||
// search for unknown long names
|
||||
for (LongNameMapType::const_iterator lIt = longNameMap.begin(); lIt != longNameMap.end(); ++lIt)
|
||||
{
|
||||
string entry = lIt->first;
|
||||
|
||||
MultiMapType::const_iterator it;
|
||||
|
||||
for (it = params.begin(); it != params.end(); ++it)
|
||||
{
|
||||
if (entry == it->second->longName())
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (it == params.end())
|
||||
{
|
||||
string msg = "Unknown parameter: --" + entry + " entered";
|
||||
needHelpMessage = true;
|
||||
messages.push_back(msg);
|
||||
}
|
||||
} // for lIt
|
||||
|
||||
// search for unknown short names
|
||||
for (ShortNameMapType::const_iterator sIt = shortNameMap.begin(); sIt != shortNameMap.end(); ++sIt)
|
||||
{
|
||||
char entry = sIt->first;
|
||||
|
||||
MultiMapType::const_iterator it;
|
||||
|
||||
for (it = params.begin(); it != params.end(); ++it)
|
||||
{
|
||||
if (entry == it->second->shortName())
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (it == params.end())
|
||||
{
|
||||
string entryString(1, entry);
|
||||
string msg = "Unknown parameter: -" + entryString + " entered";
|
||||
needHelpMessage = true;
|
||||
messages.push_back(msg);
|
||||
}
|
||||
} // for sIt
|
||||
|
||||
if( needHelpMessage ) {
|
||||
string msg = "Use -h or --help to get help about available parameters";
|
||||
messages.push_back( msg );
|
||||
}
|
||||
|
||||
} // if stopOnUnknownParam
|
||||
|
||||
return needHelp.value() || !messages.empty();
|
||||
}
|
||||
|
||||
///////////////// I put these here at the moment
|
||||
ostream & operator<<(ostream & _os, const eoParamParamType & _rate)
|
||||
{
|
||||
_rate.printOn(_os);
|
||||
return _os;
|
||||
}
|
||||
|
||||
istream & operator>>(istream & _is, eoParamParamType & _rate)
|
||||
{
|
||||
_rate.readFrom(_is);
|
||||
return _is;
|
||||
}
|
||||
343
eo/src/utils/eoParser.h
Normal file
343
eo/src/utils/eoParser.h
Normal file
|
|
@ -0,0 +1,343 @@
|
|||
/* (c) Marc Schoenauer, Maarten Keijzer, GeNeura Team, Thales group
|
||||
|
||||
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: http://eodev.sourceforge.net
|
||||
Authors:
|
||||
todos@geneura.ugr.es, http://geneura.ugr.es
|
||||
Marc.Schoenauer@polytechnique.fr
|
||||
mkeijzer@dhi.dk
|
||||
Johann Dréo <johann.dreo@thalesgroup.com>
|
||||
*/
|
||||
|
||||
|
||||
#ifndef EO_PARSER_H
|
||||
#define EO_PARSER_H
|
||||
|
||||
#include <map>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
|
||||
#include "eoParam.h"
|
||||
#include "eoObject.h"
|
||||
#include "eoPersistent.h"
|
||||
#include "eoExceptions.h"
|
||||
|
||||
/** Parameter saving and loading
|
||||
|
||||
eoParameterLoader is an abstract class that can be used as a base for your own
|
||||
parameter loading and saving. The command line parser eoParser is derived from
|
||||
this class.
|
||||
|
||||
@ingroup Parameters
|
||||
*/
|
||||
class eoParameterLoader
|
||||
{
|
||||
public :
|
||||
|
||||
/** Need a virtual destructor */
|
||||
virtual ~eoParameterLoader();
|
||||
|
||||
/** Register a parameter and set its value if it is known
|
||||
|
||||
@param param the parameter to process
|
||||
@param section the section where this parameter belongs
|
||||
*/
|
||||
virtual void processParam(eoParam& param, std::string section = "") = 0;
|
||||
|
||||
/**
|
||||
* checks if _param has been actually entered
|
||||
*/
|
||||
virtual bool isItThere(eoParam& _param) const = 0;
|
||||
|
||||
/**
|
||||
* Construct a Param and sets its value. The loader will own the memory thus created
|
||||
*
|
||||
* @param _defaultValue The default value
|
||||
* @param _longName Long name of the argument
|
||||
* @param _description Description of the parameter. What is useful for.
|
||||
* @param _shortHand Short name of the argument (Optional)
|
||||
* @param _section Name of the section where the parameter belongs
|
||||
* @param _required If it is a necessary parameter or not
|
||||
*/
|
||||
template <class ValueType>
|
||||
eoValueParam<ValueType>& createParam(ValueType _defaultValue,
|
||||
std::string _longName,
|
||||
std::string _description,
|
||||
char _shortHand = 0,
|
||||
std::string _section = "",
|
||||
bool _required = false)
|
||||
{
|
||||
eoValueParam<ValueType>* p = new eoValueParam<ValueType>(_defaultValue,
|
||||
_longName,
|
||||
_description,
|
||||
_shortHand,
|
||||
_required);
|
||||
ownedParams.push_back(p);
|
||||
processParam(*p, _section);
|
||||
return *p;
|
||||
}
|
||||
|
||||
|
||||
private :
|
||||
|
||||
std::vector<eoParam*> ownedParams;
|
||||
};
|
||||
|
||||
/**
|
||||
eoParser: command line parser and configuration file reader
|
||||
This class is persistent, so it can be stored and reloaded to restore
|
||||
parameter settings.
|
||||
|
||||
Parameters can be read from argv, strings or streams, and must be specified
|
||||
using the following convention: --name=value or -n=value
|
||||
|
||||
You should not use space as a separator between the parameter and its value.
|
||||
|
||||
@ingroup Parameters
|
||||
*/
|
||||
class eoParser : public eoParameterLoader, public eoObject, public eoPersistent
|
||||
{
|
||||
|
||||
public:
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
* a complete constructor that reads the command line an optionally reads
|
||||
* a configuration file.
|
||||
|
||||
*
|
||||
* myEo --param-file=param.rc will then load using the parameter file param.rc
|
||||
*
|
||||
* @param _argc command line arguments count
|
||||
* @param _argv command line parameters
|
||||
* @param _programDescription Description of the work the program does
|
||||
* @param _lFileParamName Name of the parameter specifying the configuration file (--param-file)
|
||||
* @param _shortHand Single charachter shorthand for specifying the configuration file
|
||||
*/
|
||||
eoParser ( unsigned _argc, char **_argv , std::string _programDescription = "",
|
||||
std::string _lFileParamName = "param-file", char _shortHand = 'p');
|
||||
|
||||
/**
|
||||
Processes the parameter and puts it in the appropriate section for readability
|
||||
*/
|
||||
void processParam(eoParam& param, std::string section = "");
|
||||
|
||||
/** Read from a stream
|
||||
* @param is the input stream
|
||||
*/
|
||||
void readFrom(std::istream& is);
|
||||
|
||||
/** Pint on a stream
|
||||
* @param os the output stream
|
||||
*/
|
||||
void printOn(std::ostream& os) const;
|
||||
|
||||
/// className for readibility
|
||||
std::string className(void) const { return "Parser"; }
|
||||
|
||||
/// true if the user made an error or asked for help
|
||||
bool userNeedsHelp(void);
|
||||
/**
|
||||
* Prints an automatic help in the specified output using the information
|
||||
* provided by parameters
|
||||
*/
|
||||
void printHelp(std::ostream& os);
|
||||
|
||||
std::string ProgramName() { return programName; }
|
||||
|
||||
/** Has param been entered by user?
|
||||
|
||||
Checks if _param has been actually entered by the user
|
||||
*/
|
||||
virtual bool isItThere(eoParam& _param) const
|
||||
{ return getValue(_param).first; }
|
||||
|
||||
|
||||
std::string get( const std::string & name) const;
|
||||
|
||||
|
||||
/**
|
||||
* get a handle on a param from its longName
|
||||
*
|
||||
* if not found, returns 0 (null pointer :-)
|
||||
*
|
||||
* Not very clean (requires hard-coding of the long name twice!)
|
||||
* but very useful in many occasions...
|
||||
*/
|
||||
eoParam * getParamWithLongName(const std::string& _name) const;
|
||||
|
||||
|
||||
/**
|
||||
* Get a handle on a param from its long name
|
||||
* If not found, raise an eoMissingParamException
|
||||
*/
|
||||
eoParam * getParam(const std::string& _name) const;
|
||||
|
||||
|
||||
/**
|
||||
* Get the value of a param from its long name
|
||||
* If not found, raise an eoMissingParamException
|
||||
*
|
||||
* Remember to specify the expected return type with a templated call:
|
||||
* unsigned int popSize = eoparser.value<unsigned int>("popSize");
|
||||
*
|
||||
* If the template type is not the good one, an eoWrongParamTypeException is raised.
|
||||
*/
|
||||
template<class ValueType>
|
||||
ValueType valueOf(const std::string& _name) const
|
||||
{
|
||||
eoParam* param = getParam(_name);
|
||||
|
||||
// Note: eoParam is the polymorphic base class of eoValueParam, thus we can do a dynamix cast
|
||||
eoValueParam<ValueType>* vparam = dynamic_cast< eoValueParam<ValueType>* >(param);
|
||||
|
||||
if( vparam == NULL ) {
|
||||
// if the dynamic cast has failed, chances are that ValueType
|
||||
// is not the same than the one used at declaration.
|
||||
throw eoWrongParamTypeException( _name );
|
||||
} else {
|
||||
return vparam->value();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/** Get or create parameter
|
||||
|
||||
It seems finally that the easiest use of the above method is
|
||||
through the following, whose interface is similar to that of the
|
||||
widely-used createParam.
|
||||
*/
|
||||
template <class ValueType>
|
||||
eoValueParam<ValueType>& getORcreateParam(ValueType _defaultValue,
|
||||
std::string _longName,
|
||||
std::string _description,
|
||||
char _shortHand = 0,
|
||||
std::string _section = "",
|
||||
bool _required = false)
|
||||
{
|
||||
eoParam* ptParam = getParamWithLongName(_longName);
|
||||
if (ptParam) {
|
||||
// found
|
||||
eoValueParam<ValueType>* ptTypedParam(
|
||||
dynamic_cast<eoValueParam<ValueType>*>(ptParam));
|
||||
return *ptTypedParam;
|
||||
} else {
|
||||
// not found -> create it
|
||||
return createParam(_defaultValue, _longName, _description,
|
||||
_shortHand, _section, _required);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/** Set parameter value or create parameter
|
||||
|
||||
This makes sure that the specified parameter has the given value.
|
||||
If the parameter does not exist yet, it is created.
|
||||
|
||||
This requires that operator<< is defined for ValueType.
|
||||
|
||||
|
||||
@param _defaultValue Default value.
|
||||
@param _longName Long name of the argument.
|
||||
@param _description Description of the parameter.
|
||||
@param _shortHand Short name of the argument (Optional)
|
||||
@param _section Name of the section where the parameter belongs.
|
||||
@param _required Is the parameter mandatory?
|
||||
@return Corresponding parameter.
|
||||
*/
|
||||
template <class ValueType>
|
||||
eoValueParam<ValueType>& setORcreateParam(ValueType _defaultValue,
|
||||
std::string _longName,
|
||||
std::string _description,
|
||||
char _shortHand = 0,
|
||||
std::string _section = "",
|
||||
bool _required = false)
|
||||
{
|
||||
eoValueParam<ValueType>& param = createParam(_defaultValue, _longName, _description,
|
||||
_shortHand, _section, _required);
|
||||
std::ostringstream os;
|
||||
os << _defaultValue;
|
||||
if(isItThere(param)) {
|
||||
param.setValue(os.str());
|
||||
} else {
|
||||
longNameMap[_longName] = os.str();
|
||||
shortNameMap[_shortHand] = os.str();
|
||||
}
|
||||
return param;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/** accessors to the stopOnUnknownParam value */
|
||||
void setStopOnUnknownParam(bool _b) {stopOnUnknownParam.value()=_b;}
|
||||
bool getStopOnUnknownParam() {return stopOnUnknownParam.value();}
|
||||
|
||||
/** Prefix handling */
|
||||
void setPrefix(const std:: string & _prefix) {prefix = _prefix;}
|
||||
|
||||
void resetPrefix() {prefix = "";}
|
||||
|
||||
std::string getPrefix() {return prefix;}
|
||||
|
||||
private:
|
||||
|
||||
void doRegisterParam(eoParam& param);
|
||||
|
||||
std::pair<bool, std::string> getValue(eoParam& _param) const;
|
||||
|
||||
void updateParameters();
|
||||
|
||||
typedef std::multimap<std::string, eoParam*> MultiMapType;
|
||||
|
||||
// used to store all parameters that are processed
|
||||
MultiMapType params;
|
||||
|
||||
std::string programName;
|
||||
std::string programDescription;
|
||||
|
||||
typedef std::map<char, std::string> ShortNameMapType;
|
||||
ShortNameMapType shortNameMap;
|
||||
|
||||
typedef std::map<std::string, std::string> LongNameMapType;
|
||||
LongNameMapType longNameMap;
|
||||
|
||||
// flag that marks if the user need to know that there was a problem
|
||||
// used to display the message about "-h" only once
|
||||
bool needHelpMessage;
|
||||
|
||||
eoValueParam<bool> needHelp;
|
||||
eoValueParam<bool> stopOnUnknownParam;
|
||||
|
||||
mutable std::vector<std::string> messages;
|
||||
|
||||
std::string prefix; // used for all created params - in processParam
|
||||
|
||||
};
|
||||
|
||||
|
||||
|
||||
#endif // EO_PARSER_H
|
||||
|
||||
|
||||
|
||||
// Local Variables:
|
||||
// coding: iso-8859-1
|
||||
// mode:C++
|
||||
// c-file-style: "Stroustrup"
|
||||
// comment-column: 35
|
||||
// fill-column: 80
|
||||
// End:
|
||||
36
eo/src/utils/eoParserLogger.h
Normal file
36
eo/src/utils/eoParserLogger.h
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
/*
|
||||
(c) Thales group, 2010
|
||||
|
||||
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;
|
||||
version 2 of the License.
|
||||
|
||||
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: http://eodev.sourceforge.net
|
||||
|
||||
Authors:
|
||||
Caner Candan <caner.candan@thalesgroup.com>
|
||||
|
||||
*/
|
||||
|
||||
#ifndef EO_PARSER_LOGGER_H
|
||||
#define EO_PARSER_LOGGER_H
|
||||
|
||||
#include "eoParser.h"
|
||||
|
||||
#warning "[eoParserLogger] is deprecated"
|
||||
|
||||
typedef eoParser eoParserLogger;
|
||||
|
||||
#endif // !EO_PARSER_LOGGER_H
|
||||
137
eo/src/utils/eoPopStat.h
Normal file
137
eo/src/utils/eoPopStat.h
Normal file
|
|
@ -0,0 +1,137 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoPopStat.h
|
||||
// (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2001
|
||||
/*
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
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
|
||||
mkeijzer@dhi.dk
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
/** WARNING: this file contains 2 classes:
|
||||
|
||||
eoPopString and eoSortedPopString
|
||||
|
||||
that transform the population into a std::string
|
||||
that can be used to dump to the screen
|
||||
*/
|
||||
|
||||
#ifndef _eoPopStat_h
|
||||
#define _eoPopStat_h
|
||||
|
||||
#include <utils/eoStat.h>
|
||||
|
||||
|
||||
/** Thanks to MS/VC++, eoParam mechanism is unable to handle std::vectors of stats.
|
||||
This snippet is a workaround:
|
||||
This class will "print" a whole population into a std::string - that you can later
|
||||
send to any stream
|
||||
This is the plain version - see eoPopString for the Sorted version
|
||||
|
||||
Note: this Stat should probably be used only within eoStdOutMonitor, and not
|
||||
inside an eoFileMonitor, as the eoState construct will work much better there.
|
||||
|
||||
@ingroup Stats
|
||||
*/
|
||||
template <class EOT>
|
||||
class eoPopStat : public eoStat<EOT, std::string>
|
||||
{
|
||||
public:
|
||||
|
||||
using eoStat<EOT, std::string>::value;
|
||||
|
||||
/** default Ctor, void std::string by default, as it appears
|
||||
on the description line once at beginning of evolution. and
|
||||
is meaningless there. _howMany defaults to 0, that is, the whole
|
||||
population*/
|
||||
eoPopStat(unsigned _howMany = 0, std::string _desc ="")
|
||||
: eoStat<EOT, std::string>("", _desc), combien( _howMany) {}
|
||||
|
||||
/** Fills the value() of the eoParam with the dump of the population.
|
||||
Adds a \n before so it does not get mixed up with the rest of the stats
|
||||
that are written by the monitor it is probably used from.
|
||||
*/
|
||||
void operator()(const eoPop<EOT>& _pop)
|
||||
{
|
||||
value() = "\n# ====== pop dump =====\n";
|
||||
unsigned howmany=combien?combien:_pop.size();
|
||||
for (unsigned i = 0; i < howmany; ++i)
|
||||
{
|
||||
std::ostringstream os;
|
||||
os << _pop[i] << std::endl;
|
||||
|
||||
// paranoid:
|
||||
value() += os.str();
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
unsigned combien;
|
||||
};
|
||||
|
||||
/** Thanks to MS/VC++, eoParam mechanism is unable to handle std::vectors of stats.
|
||||
This snippet is a workaround:
|
||||
This class will "print" a whole population into a std::string - that you can later
|
||||
send to any stream
|
||||
This is the Sorted version - see eoPopString for the plain version
|
||||
|
||||
Note: this Stat should probably be used only within eoStdOutMonitor, and not
|
||||
inside an eoFileMonitor, as the eoState construct will work much better there.
|
||||
|
||||
@ingroup Stats
|
||||
*/
|
||||
template <class EOT>
|
||||
class eoSortedPopStat : public eoSortedStat<EOT, std::string>
|
||||
{
|
||||
public:
|
||||
|
||||
using eoSortedStat<EOT, std::string>::value;
|
||||
|
||||
/** default Ctor, void std::string by default, as it appears on
|
||||
the description line once at beginning of evolution. and is
|
||||
meaningless there _howMany defaults to 0, that is, the whole
|
||||
population
|
||||
*/
|
||||
eoSortedPopStat(unsigned _howMany = 0, std::string _desc ="")
|
||||
: eoSortedStat<EOT, std::string>("", _desc) , combien( _howMany)
|
||||
{}
|
||||
|
||||
/** Fills the value() of the eoParam with the dump of the
|
||||
population. Adds a \n before so it does not get mixed up with
|
||||
the rest of the stats that are written by the monitor it is
|
||||
probably used from.
|
||||
*/
|
||||
void operator()(const std::vector<const EOT*>& _pop)
|
||||
{
|
||||
value() = ""; // empty
|
||||
unsigned howMany=combien?combien:_pop.size();
|
||||
for (unsigned i = 0; i < howMany; ++i)
|
||||
{
|
||||
std::ostringstream os;
|
||||
os << *_pop[i] << std::endl;
|
||||
|
||||
// paranoid:
|
||||
value() += os.str();
|
||||
}
|
||||
}
|
||||
private:
|
||||
unsigned combien;
|
||||
};
|
||||
|
||||
#endif
|
||||
18
eo/src/utils/eoRNG.cpp
Normal file
18
eo/src/utils/eoRNG.cpp
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
#ifdef _MSC_VER
|
||||
// to avoid long name warnings
|
||||
#pragma warning(disable:4786)
|
||||
#endif
|
||||
|
||||
#include <ctime>
|
||||
#include "eoRNG.h"
|
||||
|
||||
// initialize static constants
|
||||
const uint32_t eoRng::K(0x9908B0DFU);
|
||||
const int eoRng::M(397);
|
||||
const int eoRng::N(624);
|
||||
|
||||
namespace eo
|
||||
{
|
||||
// global random number generator object
|
||||
eoRng rng(static_cast<uint32_t>(time(0)));
|
||||
}
|
||||
598
eo/src/utils/eoRNG.h
Normal file
598
eo/src/utils/eoRNG.h
Normal file
|
|
@ -0,0 +1,598 @@
|
|||
/** 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: eodev-main@lists.sourceforge.net
|
||||
Old contact information: todos@geneura.ugr.es, http://geneura.ugr.es
|
||||
*/
|
||||
|
||||
#ifndef EO_RANDOM_NUMBER_GENERATOR
|
||||
#define EO_RANDOM_NUMBER_GENERATOR
|
||||
|
||||
/** @addtogroup Random
|
||||
* @{
|
||||
* */
|
||||
|
||||
# if (defined _MSC_VER)
|
||||
/** uint32_t is an unsigned integer type capable of holding 32 bits.
|
||||
|
||||
In the applicatione here exactly 32 are used.
|
||||
64 bits might be better on an Alpha or other 64 bit systems with GCC at high
|
||||
optimization levels so feel free to try your options and see what's best for
|
||||
you.
|
||||
*/
|
||||
typedef unsigned long uint32_t;
|
||||
#else
|
||||
#if (! defined __sun)
|
||||
// The C99-standard defines uint32_t to be declared in stdint.h, but some
|
||||
// systems don't have that and implement it in inttypes.h.
|
||||
#include <stdint.h>
|
||||
#else
|
||||
#include <inttypes.h>
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#include <cmath>
|
||||
#include <vector>
|
||||
#include "eoPersistent.h"
|
||||
#include "eoObject.h"
|
||||
|
||||
|
||||
/** Random Number Generator
|
||||
|
||||
@class eoRng eoRNG.h utils/eoRNG.h
|
||||
|
||||
eoRng is a persistent 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().
|
||||
|
||||
EO provides a global random number generator <tt>rng</tt> that is seeded by the
|
||||
current UNIX time at program start. Moreover some global convenience functions
|
||||
are provided that use the global random number generator: <tt>random</tt>,
|
||||
<tt>normal</tt>.
|
||||
|
||||
@warning If you want to repeatedly generated the same sequence of pseudo-random
|
||||
numbers, you should always reseed the generator at the beginning of your code.
|
||||
|
||||
|
||||
|
||||
<h1>Documentation in original file</h1>
|
||||
|
||||
This is the ``Mersenne Twister'' random number generator MT19937, which
|
||||
generates pseudorandom integers uniformly distributed in 0..(2^32 - 1) starting
|
||||
from any odd seed in 0..(2^32 - 1). This version is a recode by Shawn Cokus
|
||||
(Cokus@math.washington.edu) on March 8, 1998 of a version by Takuji Nishimura
|
||||
(who had suggestions from Topher Cooper and Marc Rieffel in July-August 1997).
|
||||
|
||||
Effectiveness of the recoding (on Goedel2.math.washington.edu, a DEC Alpha
|
||||
running OSF/1) using GCC -O3 as a compiler: before recoding: 51.6 sec. to
|
||||
generate 300 million random numbers; after recoding: 24.0 sec. for the same
|
||||
(i.e., 46.5% of original time), so speed is now about 12.5 million random number
|
||||
generations per second on this machine.
|
||||
|
||||
According to the URL <http://www.math.keio.ac.jp/~matumoto/emt.html> (and
|
||||
paraphrasing a bit in places), the Mersenne Twister is ``designed with
|
||||
consideration of the flaws of various existing generators,'' has a period of
|
||||
2^19937 - 1, gives a sequence that is 623-dimensionally equidistributed, and
|
||||
``has passed many std::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.
|
||||
|
||||
The code as Shawn received it included the following notice: <tt>Copyright (C)
|
||||
1997 Makoto Matsumoto and Takuji Nishimura. When you use this, send an e-mail to
|
||||
<matumoto@math.keio.ac.jp> with an appropriate reference to your work.</tt> It
|
||||
would be nice to Cc: <Cokus@math.washington.edu> and
|
||||
<eodev-main@lists.sourceforge.net> when you write.
|
||||
|
||||
|
||||
<h1>Portability</h1>
|
||||
|
||||
Note for people porting EO to other platforms: please make sure that the type
|
||||
uint32_t in the file eoRNG.h is exactly 32 bits long. It may in principle 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 :
|
||||
|
||||
/** Constructor
|
||||
|
||||
@param s Random seed; if you want another seed, use reseed.
|
||||
|
||||
@see reseed for details on usage of the seeding value.
|
||||
*/
|
||||
eoRng(uint32_t s)
|
||||
: state(0), next(0), left(-1), cached(false)
|
||||
{
|
||||
state = new uint32_t[N+1];
|
||||
initialize(2*s);
|
||||
}
|
||||
|
||||
/** Destructor */
|
||||
~eoRng()
|
||||
{
|
||||
delete [] state;
|
||||
}
|
||||
|
||||
/** Re-initializes the Random Number Generator.
|
||||
|
||||
WARNING: Jeroen Eggermont <jeggermo@liacs.nl> noticed that initialize does
|
||||
not differentiate between odd and even numbers, therefore the argument to
|
||||
reseed is now doubled before being passed on.
|
||||
|
||||
Manually divide the seed by 2 if you want to re-run old runs
|
||||
|
||||
@version MS. 5 Oct. 2001
|
||||
*/
|
||||
void reseed(uint32_t s)
|
||||
{
|
||||
initialize(2*s);
|
||||
}
|
||||
|
||||
/** Re-initializes the Random Number Generator
|
||||
|
||||
This is the traditional seeding procedure. This version is deprecated and
|
||||
only provided for compatibility with old code. In new projects you should
|
||||
use reseed.
|
||||
|
||||
@see reseed for details on usage of the seeding value.
|
||||
|
||||
@version old version (deprecated)
|
||||
*/
|
||||
void oldReseed(uint32_t s)
|
||||
{
|
||||
initialize(s);
|
||||
}
|
||||
|
||||
/** Random number from unifom distribution
|
||||
|
||||
@param m Define interval for random number to [0, m)
|
||||
@return random number in the range [0, m)
|
||||
*/
|
||||
double uniform(double m = 1.0)
|
||||
{ // random number between [0, m]
|
||||
return m * double(rand()) / double(1.0 + rand_max());
|
||||
}
|
||||
|
||||
/** Random number from unifom distribution
|
||||
|
||||
@param min Define minimum for interval in the range [min, max)
|
||||
@param max Define maximum for interval in the range [min, max)
|
||||
@return random number in the range [min, max)
|
||||
*/
|
||||
double uniform(double min, double max)
|
||||
{ // random number between [min, max]
|
||||
return min + uniform(max - min);
|
||||
}
|
||||
|
||||
/** Random integer number from unifom distribution
|
||||
|
||||
@param m Define interval for random number to [0, m)
|
||||
@return random integer in the range [0, m)
|
||||
*/
|
||||
uint32_t random(uint32_t m)
|
||||
{
|
||||
// C++ Standard (4.9 Floatingintegral conversions [conv.fpint])
|
||||
// defines floating point to integer conversion as truncation
|
||||
// ("rounding towards zero"): "An rvalue of a floating point type
|
||||
// can be converted to an rvalue of an integer type. The conversion
|
||||
// truncates; that is, the fractional part is discarded"
|
||||
return uint32_t(uniform() * double(m));
|
||||
}
|
||||
|
||||
/** Biased coin toss
|
||||
|
||||
This tosses a biased coin such that flip(x/100.0) will true x% of the time
|
||||
|
||||
@param bias The coins' bias (the \e x above)
|
||||
@return The result of the biased coin toss
|
||||
*/
|
||||
bool flip(double bias=0.5)
|
||||
{
|
||||
return uniform() < bias;
|
||||
}
|
||||
|
||||
/** Gaussian deviate
|
||||
|
||||
Zero mean Gaussian deviate with standard deviation 1.
|
||||
Note: Use the Marsaglia polar method.
|
||||
|
||||
@return Random Gaussian deviate
|
||||
*/
|
||||
double normal();
|
||||
|
||||
/** Gaussian deviate
|
||||
|
||||
Gaussian deviate with zero mean and specified standard deviation.
|
||||
|
||||
@param stdev Standard deviation for Gaussian distribution
|
||||
@return Random Gaussian deviate
|
||||
*/
|
||||
double normal(double stdev)
|
||||
{ return stdev * normal(); }
|
||||
|
||||
/** Gaussian deviate
|
||||
|
||||
Gaussian deviate with specified mean and standard deviation.
|
||||
|
||||
@param mean Mean for Gaussian distribution
|
||||
@param stdev Standard deviation for Gaussian distribution
|
||||
@return Random Gaussian deviate
|
||||
*/
|
||||
double normal(double mean, double stdev)
|
||||
{ return mean + normal(stdev); }
|
||||
|
||||
/** Random numbers using a negative exponential distribution
|
||||
|
||||
@param mean Mean value of distribution
|
||||
@return Random number from a negative exponential distribution
|
||||
*/
|
||||
double negexp(double mean)
|
||||
{
|
||||
return -mean*log(double(rand()) / rand_max());
|
||||
}
|
||||
|
||||
/**
|
||||
rand() returns a random number in the range [0, rand_max)
|
||||
*/
|
||||
uint32_t rand();
|
||||
|
||||
/**
|
||||
rand_max() the maximum returned by rand()
|
||||
*/
|
||||
uint32_t rand_max() const { return uint32_t(0xffffffff); }
|
||||
|
||||
/** Roulette wheel selection
|
||||
|
||||
roulette_wheel(vec, total = 0) does a roulette wheel selection
|
||||
on the input std::vector vec. If the total is not supplied, it is
|
||||
calculated. It returns an integer denoting the selected argument.
|
||||
*/
|
||||
template <typename TYPE>
|
||||
int roulette_wheel(const std::vector<TYPE>& vec, TYPE total = 0)
|
||||
{
|
||||
if (total == 0)
|
||||
{ // count
|
||||
for (unsigned i = 0; i < vec.size(); ++i)
|
||||
total += vec[i];
|
||||
}
|
||||
double fortune = uniform() * total;
|
||||
int i = 0;
|
||||
while (fortune >= 0)
|
||||
{
|
||||
fortune -= vec[i++];
|
||||
}
|
||||
return --i;
|
||||
}
|
||||
|
||||
|
||||
/** Randomly select element from vector.
|
||||
|
||||
@return Uniformly chosen element from the vector.
|
||||
*/
|
||||
template <typename TYPE>
|
||||
const TYPE& choice(const std::vector<TYPE>& vec)
|
||||
{ return vec[random(vec.size())]; }
|
||||
|
||||
|
||||
/** Randomly select element from vector.
|
||||
|
||||
@overload
|
||||
|
||||
Provide a version returning a non-const element reference.
|
||||
|
||||
@return Uniformly chosen element from the vector.
|
||||
|
||||
@warning Changing the return value does alter the vector.
|
||||
*/
|
||||
template <typename TYPE>
|
||||
TYPE& choice(std::vector<TYPE>& vec)
|
||||
{ return vec[random(vec.size())]; }
|
||||
|
||||
/** @brief Print RNG
|
||||
|
||||
@param _os Stream to print RNG on
|
||||
*/
|
||||
void printOn(std::ostream& _os) const
|
||||
{
|
||||
for (int i = 0; i < N; ++i)
|
||||
{
|
||||
_os << state[i] << ' ';
|
||||
}
|
||||
_os << int(next - state) << ' ';
|
||||
_os << left << ' ' << cached << ' ' << cacheValue;
|
||||
}
|
||||
|
||||
/** @brief Read RNG
|
||||
|
||||
@param _is Stream to read RNG from
|
||||
*/
|
||||
void readFrom(std::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;
|
||||
}
|
||||
|
||||
std::string className() const { return "Mersenne-Twister"; }
|
||||
|
||||
private:
|
||||
|
||||
uint32_t restart();
|
||||
|
||||
/* @brief Initialize state
|
||||
|
||||
We initialize state[0..(N-1)] via the generator
|
||||
|
||||
<tt>x_new = (69069 * x_old) mod 2^32</tt>
|
||||
|
||||
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.
|
||||
*/
|
||||
void initialize(uint32_t seed);
|
||||
|
||||
/** @brief Array for the state */
|
||||
uint32_t *state;
|
||||
|
||||
/** Pointer to next available random number */
|
||||
uint32_t *next;
|
||||
|
||||
/** Number of random numbers currently left */
|
||||
int left;
|
||||
|
||||
/** @brief Is there a valid cached value for the normal distribution? */
|
||||
bool cached;
|
||||
|
||||
/** @brief Cached value for normal distribution? */
|
||||
double cacheValue;
|
||||
|
||||
/** @brief Size of the state-vector */
|
||||
static const int N;
|
||||
|
||||
/** Internal constant */
|
||||
static const int M;
|
||||
|
||||
/** @brief Magic constant */
|
||||
static const uint32_t K;
|
||||
|
||||
|
||||
/** @brief Copy constructor
|
||||
|
||||
Private copy ctor and assignment operator to make sure that nobody
|
||||
accidentally copies the random number generator. If you want similar RNG's,
|
||||
make two RNG's and initialize them with the same seed.
|
||||
|
||||
As it cannot be called, we do not provide an implementation.
|
||||
*/
|
||||
eoRng(const eoRng&);
|
||||
|
||||
/** @brief Assignment operator
|
||||
|
||||
@see Copy constructor eoRng(const eoRng&).
|
||||
*/
|
||||
eoRng& operator=(const eoRng&);
|
||||
};
|
||||
/** @example t-eoRNG.cpp
|
||||
*/
|
||||
|
||||
|
||||
|
||||
namespace eo
|
||||
{
|
||||
/** The one and only global eoRng object */
|
||||
extern eoRng rng;
|
||||
}
|
||||
using eo::rng;
|
||||
|
||||
/** @} */
|
||||
|
||||
|
||||
|
||||
|
||||
// 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_t seed)
|
||||
{
|
||||
left = -1;
|
||||
|
||||
register uint32_t x = (seed | 1U) & 0xFFFFFFFFU, *s = state;
|
||||
register int j;
|
||||
|
||||
for(left=0, *s++=x, j=N; --j;
|
||||
*s++ = (x*=69069U) & 0xFFFFFFFFU) ;
|
||||
}
|
||||
|
||||
|
||||
|
||||
inline uint32_t eoRng::restart()
|
||||
{
|
||||
register uint32_t *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_t eoRng::rand()
|
||||
{
|
||||
if(--left < 0)
|
||||
return(restart());
|
||||
uint32_t y = *next++;
|
||||
y ^= (y >> 11);
|
||||
y ^= (y << 7) & 0x9D2C5680U;
|
||||
y ^= (y << 15) & 0xEFC60000U;
|
||||
return(y ^ (y >> 18));
|
||||
}
|
||||
|
||||
|
||||
|
||||
inline double eoRng::normal()
|
||||
{
|
||||
if (cached) {
|
||||
cached = false;
|
||||
return cacheValue;
|
||||
}
|
||||
double rSquare, 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);
|
||||
double factor = sqrt(-2.0 * log(rSquare) / rSquare);
|
||||
cacheValue = var1 * factor;
|
||||
cached = true;
|
||||
return (var2 * factor);
|
||||
}
|
||||
|
||||
|
||||
|
||||
namespace eo
|
||||
{
|
||||
/** @brief Random function
|
||||
|
||||
This is a convenience function for generating random numbers using the
|
||||
global eo::rng object.
|
||||
|
||||
Templatized random function, returns a random double in the range [min, max).
|
||||
It works with most basic types such as:
|
||||
- char
|
||||
- int (short, long, signed and unsigned)
|
||||
- float, double
|
||||
|
||||
@param min Minimum for distribution
|
||||
@param max Maximum for distribution
|
||||
|
||||
@see random(const T& max)
|
||||
*/
|
||||
template <typename T>
|
||||
inline T random(const T& min, const T& max) {
|
||||
return static_cast<T>(rng.uniform() * (max-min)) + min; }
|
||||
|
||||
/** @brief Random function
|
||||
|
||||
@overload
|
||||
|
||||
This is a convenience function for generating random numbers using the
|
||||
global eo::rng object.
|
||||
|
||||
Templatized random function, returns a random double in the range [0, max).
|
||||
It works with most basic types such as:
|
||||
- char
|
||||
- int (short, long, signed and unsigned)
|
||||
- float, double
|
||||
|
||||
@param max Maximum for distribution
|
||||
|
||||
@see random(const T& min, const T& max)
|
||||
*/
|
||||
template <typename T>
|
||||
inline T random(const T& max) {
|
||||
return static_cast<T>(rng.uniform() * max); }
|
||||
|
||||
/** Normal distribution
|
||||
|
||||
This is a convenience function for generating random numbers using the
|
||||
global eo::rng object.
|
||||
|
||||
@return ormally distributed random number
|
||||
*/
|
||||
inline double normal() { return rng.normal(); }
|
||||
}
|
||||
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
// Local Variables:
|
||||
// coding: iso-8859-1
|
||||
// mode: C++
|
||||
// c-file-offsets: ((c . 0))
|
||||
// c-file-style: "Stroustrup"
|
||||
// fill-column: 80
|
||||
// End:
|
||||
259
eo/src/utils/eoRealBounds.cpp
Normal file
259
eo/src/utils/eoRealBounds.cpp
Normal file
|
|
@ -0,0 +1,259 @@
|
|||
#ifdef _MSC_VER
|
||||
// to avoid long name warnings
|
||||
#pragma warning(disable:4786)
|
||||
#endif
|
||||
|
||||
#ifdef HAVE_CONFIG_H
|
||||
#include <config.h>
|
||||
#endif
|
||||
|
||||
#include <ctime>
|
||||
#include <sstream>
|
||||
|
||||
#include "eoRealBounds.h"
|
||||
#include "eoRealVectorBounds.h"
|
||||
|
||||
|
||||
// the global dummy bounds
|
||||
// (used for unbounded variables when bounds are required)
|
||||
eoRealNoBounds eoDummyRealNoBounds;
|
||||
eoRealVectorNoBounds eoDummyVectorNoBounds(0);
|
||||
|
||||
///////////// helper read functions - could be somewhere else
|
||||
|
||||
// removes leading delimiters - return false if nothing else left
|
||||
bool remove_leading(std::string & _s, const std::string _delim)
|
||||
{
|
||||
size_t posDebToken = _s.find_first_not_of(_delim);
|
||||
if (posDebToken >= _s.size())
|
||||
return false;
|
||||
_s = _s.substr(posDebToken);
|
||||
return true;
|
||||
}
|
||||
|
||||
double read_double(std::string _s)
|
||||
{
|
||||
std::istringstream is(_s);
|
||||
double r;
|
||||
is >> r;
|
||||
return r;
|
||||
}
|
||||
|
||||
long int read_int(std::string _s)
|
||||
{
|
||||
std::istringstream is(_s);
|
||||
long int i;
|
||||
is >> i;
|
||||
return i;
|
||||
}
|
||||
|
||||
// need to rewrite copy ctor and assignement operator because of ownedBounds
|
||||
eoRealVectorBounds::eoRealVectorBounds(const eoRealVectorBounds & _b):
|
||||
eoRealBaseVectorBounds(_b), eoPersistent()
|
||||
{
|
||||
factor = _b.factor;
|
||||
ownedBounds = _b.ownedBounds;
|
||||
// duplicate all pointers!
|
||||
if (ownedBounds.size()>0)
|
||||
for (unsigned i=0; i<ownedBounds.size(); i++)
|
||||
ownedBounds[i] = ownedBounds[i]->dup();
|
||||
}
|
||||
|
||||
|
||||
// the readFrom method of eoRealVectorNoBounds:
|
||||
// only calls the readFrom(string) - for param reading
|
||||
void eoRealVectorBounds::readFrom(std::istream& _is)
|
||||
{
|
||||
std::string value;
|
||||
_is >> value;
|
||||
readFrom(value);
|
||||
return;
|
||||
}
|
||||
|
||||
void eoRealVectorBounds::readFrom(std::string _value)
|
||||
{
|
||||
// keep track of old size - to adjust in the end
|
||||
unsigned oldSize = size();
|
||||
// clean-up before filling in
|
||||
if (ownedBounds.size()>0)
|
||||
for (unsigned i = 0; i < ownedBounds.size(); ++i)
|
||||
{
|
||||
delete ownedBounds[i];
|
||||
}
|
||||
ownedBounds.resize(0);
|
||||
factor.resize(0);
|
||||
resize(0);
|
||||
|
||||
// now read
|
||||
std::string delim(",; ");
|
||||
while (_value.size()>0)
|
||||
{
|
||||
if (!remove_leading(_value, delim)) // only delimiters were left
|
||||
break;
|
||||
// look for opening char
|
||||
size_t posDeb = _value.find_first_of("[(");
|
||||
if (posDeb >= _value.size()) // nothing left to read (though probably a syntax error there)
|
||||
{
|
||||
break;
|
||||
}
|
||||
// ending char
|
||||
std::string closeChar = (_value[posDeb] == '(' ? std::string(")") : std::string("]") );
|
||||
|
||||
size_t posFin = _value.find_first_of(std::string(closeChar));
|
||||
if (posFin >= _value.size())
|
||||
throw std::runtime_error("Syntax error when reading bounds");
|
||||
|
||||
// y a-t-il un nbre devant
|
||||
unsigned count = 1;
|
||||
if (posDeb > 0) // something before opening
|
||||
{
|
||||
std::string sCount = _value.substr(0, posDeb);
|
||||
count = read_int(sCount);
|
||||
if (count <= 0)
|
||||
throw std::runtime_error("Syntax error when reading bounds");
|
||||
}
|
||||
|
||||
// the bounds
|
||||
std::string sBounds = _value.substr(posDeb+1, posFin-posDeb-1);
|
||||
// and remove from original string
|
||||
_value = _value.substr(posFin+1);
|
||||
|
||||
remove_leading(sBounds, delim);
|
||||
size_t posDelim = sBounds.find_first_of(delim);
|
||||
if (posDelim >= sBounds.size())
|
||||
throw std::runtime_error("Syntax error when reading bounds");
|
||||
|
||||
bool minBounded=false, maxBounded=false;
|
||||
double minBound=0, maxBound=0;
|
||||
|
||||
// min bound
|
||||
std::string sMinBounds = sBounds.substr(0,posDelim);
|
||||
if (sMinBounds != std::string("-inf"))
|
||||
{
|
||||
minBounded = true;
|
||||
minBound = read_double(sMinBounds);
|
||||
}
|
||||
|
||||
// max bound
|
||||
size_t posEndDelim = sBounds.find_first_not_of(delim,posDelim);
|
||||
|
||||
std::string sMaxBounds = sBounds.substr(posEndDelim);
|
||||
if (sMaxBounds != std::string("+inf"))
|
||||
{
|
||||
maxBounded = true;
|
||||
maxBound = read_double(sMaxBounds);
|
||||
}
|
||||
|
||||
// now create the eoRealBounds objects
|
||||
eoRealBounds *ptBounds;
|
||||
if (minBounded && maxBounded)
|
||||
ptBounds = new eoRealInterval(minBound, maxBound);
|
||||
else if (!minBounded && !maxBounded) // no bound at all
|
||||
ptBounds = new eoRealNoBounds;
|
||||
else if (!minBounded && maxBounded)
|
||||
ptBounds = new eoRealAboveBound(maxBound);
|
||||
else if (minBounded && !maxBounded)
|
||||
ptBounds = new eoRealBelowBound(minBound);
|
||||
// store it for memory management
|
||||
ownedBounds.push_back(ptBounds);
|
||||
// push the count
|
||||
factor.push_back(count);
|
||||
// and add count of it to the actual bounds
|
||||
for (unsigned i=0; i<count; i++)
|
||||
push_back(ptBounds);
|
||||
}
|
||||
// now adjust the size to the initial value
|
||||
adjust_size(oldSize);
|
||||
}
|
||||
|
||||
/** Eventually increases the size by duplicating last bound */
|
||||
void eoRealVectorBounds::adjust_size(unsigned _dim)
|
||||
{
|
||||
if ( size() < _dim )
|
||||
{
|
||||
// duplicate last bound
|
||||
unsigned missing = _dim-size();
|
||||
eoRealBounds * ptBounds = back();
|
||||
for (unsigned i=0; i<missing; i++)
|
||||
push_back(ptBounds);
|
||||
// update last factor (warning: can be > 1 already!)
|
||||
factor[factor.size()-1] += missing;
|
||||
}
|
||||
}
|
||||
|
||||
/** the constructor for eoGeneralRealBound - from a string
|
||||
* very similar to the eoRealVectorBounds::readFrom above
|
||||
* but was written much later so the readFrom does not call this one
|
||||
* as it should do
|
||||
*/
|
||||
eoRealBounds* eoGeneralRealBounds::getBoundsFromString(std::string _value)
|
||||
{
|
||||
// now read
|
||||
std::string delim(",; ");
|
||||
std::string beginOrClose("[(])");
|
||||
if (!remove_leading(_value, delim)) // only delimiters were left
|
||||
throw std::runtime_error("Syntax error in eoGeneralRealBounds Ctor");
|
||||
|
||||
// look for opening char
|
||||
size_t posDeb = _value.find_first_of(beginOrClose); // allow ]a,b]
|
||||
if (posDeb >= _value.size()) // nothing left to read
|
||||
throw std::runtime_error("Syntax error in eoGeneralRealBounds Ctor");
|
||||
|
||||
// ending char: next {}() after posDeb
|
||||
size_t posFin = _value.find_first_of(beginOrClose,posDeb+1);
|
||||
if (posFin >= _value.size()) // not found
|
||||
throw std::runtime_error("Syntax error in eoGeneralRealBounds Ctor");
|
||||
|
||||
// the bounds
|
||||
std::string sBounds = _value.substr(posDeb+1, posFin-posDeb-1);
|
||||
// and remove from original string
|
||||
_value = _value.substr(posFin+1);
|
||||
|
||||
remove_leading(sBounds, delim);
|
||||
size_t posDelim = sBounds.find_first_of(delim);
|
||||
if (posDelim >= sBounds.size())
|
||||
throw std::runtime_error("Syntax error in eoGeneralRealBounds Ctor");
|
||||
|
||||
bool minBounded=false, maxBounded=false;
|
||||
double minBound=0, maxBound=0;
|
||||
|
||||
// min bound
|
||||
std::string sMinBounds = sBounds.substr(0,posDelim);
|
||||
|
||||
if ( (sMinBounds != std::string("-inf")) &&
|
||||
(sMinBounds != std::string("-infinity"))
|
||||
)
|
||||
{
|
||||
minBounded = true;
|
||||
minBound = read_double(sMinBounds);
|
||||
}
|
||||
|
||||
// max bound
|
||||
size_t posEndDelim = sBounds.find_first_not_of(delim,posDelim);
|
||||
|
||||
std::string sMaxBounds = sBounds.substr(posEndDelim);
|
||||
|
||||
if ( (sMaxBounds != std::string("+inf")) &&
|
||||
(sMaxBounds != std::string("+infinity"))
|
||||
)
|
||||
{
|
||||
maxBounded = true;
|
||||
maxBound = read_double(sMaxBounds);
|
||||
}
|
||||
|
||||
// now create the embedded eoRealBounds object
|
||||
eoRealBounds * locBound;
|
||||
if (minBounded && maxBounded)
|
||||
{
|
||||
if (maxBound <= minBound)
|
||||
throw std::runtime_error("Syntax error in eoGeneralRealBounds Ctor");
|
||||
locBound = new eoRealInterval(minBound, maxBound);
|
||||
}
|
||||
else if (!minBounded && !maxBounded) // no bound at all
|
||||
locBound = new eoRealNoBounds;
|
||||
else if (!minBounded && maxBounded)
|
||||
locBound = new eoRealAboveBound(maxBound);
|
||||
else if (minBounded && !maxBounded)
|
||||
locBound = new eoRealBelowBound(minBound);
|
||||
return locBound;
|
||||
}
|
||||
686
eo/src/utils/eoRealBounds.h
Normal file
686
eo/src/utils/eoRealBounds.h
Normal file
|
|
@ -0,0 +1,686 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoRealBounds.h
|
||||
// (c) Marc Schoenauer 2001, Maarten Keijzer 2000, 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
|
||||
Marc.Schoenauer@polytechnique.fr
|
||||
mak@dhi.dk
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _eoRealBounds_h
|
||||
#define _eoRealBounds_h
|
||||
|
||||
#include <stdexcept> // std::exceptions!
|
||||
#include <utils/eoRNG.h>
|
||||
|
||||
/**
|
||||
\defgroup Real Vector of reals
|
||||
|
||||
Set of classes related to continuous black-box optimization problems.
|
||||
|
||||
Here are several examples of test programs using eoReal, eoEsSimple, eoEsStdev or eoEsFull to build an Evoution Strategies algorithm:
|
||||
@include t-eoESAll.cpp
|
||||
@include t-eoESFull.cpp
|
||||
|
||||
@ingroup Representations
|
||||
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
\class eoRealBounds eoRealBounds.h es/eoRealBounds.h
|
||||
\ingroup Real
|
||||
|
||||
Defines bound classes for real numbers.
|
||||
|
||||
Scalar type:
|
||||
------------
|
||||
Basic class is eoRealBounds, a pure virtual.
|
||||
|
||||
The following pure virtual methods are to be used in mutations:
|
||||
- void foldsInBounds(double &) that folds any value that falls out of
|
||||
the bounds back into the bounds, by bouncing on the limit (if any)
|
||||
- bool isInBounds(double) that simply says whether or not the argument
|
||||
is in the bounds
|
||||
- void truncate(double &) that set the argument to the bound value it
|
||||
it exceeds it
|
||||
|
||||
So mutation can choose
|
||||
- iterate trying until they fall in bounds,
|
||||
- only try once and "restd::pair" by using the foldsInBounds method
|
||||
- only try once and restd::pair using the truncate method (will create a
|
||||
huge bias toward the bound if the soluiton is not far from the bounds)
|
||||
|
||||
There is also a uniform() method that generates a uniform value
|
||||
(if possible, i.e. if bounded) in the interval.
|
||||
|
||||
Derived class are
|
||||
eoRealInterval that holds a minimum and maximum value,
|
||||
eoRealNoBounds the "unbounded bounds" (-infinity, +infinity)
|
||||
eoRealBelowBound the half-bounded interval [min, +infinity)
|
||||
eoRealAboveBound the half-bounded interval (-infinity, max]
|
||||
|
||||
THis file also contains the declaration of *the* global object that
|
||||
is the unbounded bound
|
||||
|
||||
@ingroup Bounds
|
||||
*/
|
||||
class eoRealBounds : public eoPersistent
|
||||
{
|
||||
public:
|
||||
virtual ~eoRealBounds(){}
|
||||
|
||||
/** Self-Test: true if ***both*** a min and a max
|
||||
*/
|
||||
virtual bool isBounded(void) const = 0;
|
||||
|
||||
/** Self-Test: true if no min ***and*** no max
|
||||
* hence no further need to test/truncate/fold anything
|
||||
*/
|
||||
virtual bool hasNoBoundAtAll(void) const = 0;
|
||||
|
||||
/** Self-Test: bounded from below???
|
||||
*/
|
||||
virtual bool isMinBounded(void) const = 0;
|
||||
|
||||
/** Self-Test: bounded from above???
|
||||
*/
|
||||
virtual bool isMaxBounded(void) const = 0;
|
||||
|
||||
/** Test on a value: is it in bounds?
|
||||
*/
|
||||
virtual bool isInBounds(double) const = 0;
|
||||
|
||||
/** Put value back into bounds - by folding back and forth
|
||||
*/
|
||||
virtual void foldsInBounds(double &) const = 0;
|
||||
|
||||
/** Put value back into bounds - by truncating to a boundary value
|
||||
*/
|
||||
virtual void truncate(double &) const = 0;
|
||||
|
||||
/** get minimum value
|
||||
* std::exception if does not exist
|
||||
*/
|
||||
virtual double minimum() const = 0 ;
|
||||
/** get maximum value
|
||||
* std::exception if does not exist
|
||||
*/
|
||||
virtual double maximum() const = 0 ;
|
||||
/** get range
|
||||
* std::exception if unbounded
|
||||
*/
|
||||
virtual double range() const = 0;
|
||||
|
||||
/** random generator of uniform numbers in bounds
|
||||
* std::exception if unbounded
|
||||
*/
|
||||
virtual double uniform(eoRng & _rng = eo::rng) const = 0;
|
||||
|
||||
/** for memory managements - ugly */
|
||||
virtual eoRealBounds * dup() const = 0;
|
||||
};
|
||||
|
||||
/** A default class for unbounded variables
|
||||
|
||||
@ingroup Bounds
|
||||
*/
|
||||
class eoRealNoBounds : public eoRealBounds
|
||||
{
|
||||
public:
|
||||
virtual ~eoRealNoBounds(){}
|
||||
|
||||
virtual bool isBounded(void) const {return false;}
|
||||
virtual bool hasNoBoundAtAll(void) const {return true;}
|
||||
virtual bool isMinBounded(void) const {return false;}
|
||||
virtual bool isMaxBounded(void) const {return false;}
|
||||
virtual void foldsInBounds(double &) const {return;}
|
||||
virtual void truncate(double &) const {return;}
|
||||
virtual bool isInBounds(double) const {return true;}
|
||||
|
||||
virtual double minimum() const
|
||||
{
|
||||
throw std::logic_error("Trying to get minimum of unbounded eoRealBounds");
|
||||
}
|
||||
virtual double maximum() const
|
||||
{
|
||||
throw std::logic_error("Trying to get maximum of unbounded eoRealBounds");
|
||||
}
|
||||
virtual double range() const
|
||||
{
|
||||
throw std::logic_error("Trying to get range of unbounded eoRealBounds");
|
||||
}
|
||||
|
||||
virtual double uniform(eoRng & _rng = eo::rng) const
|
||||
{
|
||||
(void)_rng;
|
||||
|
||||
throw std::logic_error("Trying to generate uniform values in unbounded eoRealBounds");
|
||||
}
|
||||
|
||||
// methods from eoPersistent
|
||||
/**
|
||||
* Read object.
|
||||
* @param _is A std::istream.
|
||||
* but reading should not be done here, because of bound problems
|
||||
* see eoRealVectorBounds
|
||||
*/
|
||||
virtual void readFrom(std::istream& _is)
|
||||
{
|
||||
(void)_is;
|
||||
|
||||
throw std::runtime_error("Should not use eoRealBounds::readFrom");
|
||||
}
|
||||
|
||||
/**
|
||||
* Write object. It's called printOn since it prints the object on a stream.
|
||||
* @param _os A std::ostream.
|
||||
*/
|
||||
virtual void printOn(std::ostream& _os) const
|
||||
{
|
||||
_os << "[-inf,+inf]";
|
||||
}
|
||||
|
||||
/** for memory managements - ugly */
|
||||
virtual eoRealBounds * dup() const
|
||||
{
|
||||
return new eoRealNoBounds(*this);
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
/** one object for all - see eoRealBounds.cpp
|
||||
@ingroup Bounds
|
||||
*/
|
||||
extern eoRealNoBounds eoDummyRealNoBounds;
|
||||
|
||||
/**
|
||||
* fully bounded eoRealBound == interval
|
||||
|
||||
@ingroup Bounds
|
||||
*/
|
||||
class eoRealInterval : public eoRealBounds
|
||||
{
|
||||
public :
|
||||
virtual ~eoRealInterval(){}
|
||||
|
||||
/**
|
||||
Simple bounds = minimum and maximum (allowed)
|
||||
*/
|
||||
eoRealInterval(double _min=0, double _max=1) :
|
||||
repMinimum(_min), repMaximum(_max), repRange(_max-_min)
|
||||
{
|
||||
if (repRange<=0)
|
||||
throw std::logic_error("Void range in eoRealBounds");
|
||||
}
|
||||
|
||||
// accessors
|
||||
virtual double minimum() const { return repMinimum; }
|
||||
virtual double maximum() const { return repMaximum; }
|
||||
virtual double range() const { return repRange; }
|
||||
|
||||
// description
|
||||
virtual bool isBounded(void) const {return true;}
|
||||
virtual bool hasNoBoundAtAll(void) const {return false;}
|
||||
virtual bool isMinBounded(void) const {return true;}
|
||||
virtual bool isMaxBounded(void) const {return true;}
|
||||
|
||||
virtual double uniform(eoRng & _rng = eo::rng) const
|
||||
{
|
||||
return repMinimum + _rng.uniform(repRange);
|
||||
}
|
||||
|
||||
// says if a given double is within the bounds
|
||||
virtual bool isInBounds(double _r) const
|
||||
{
|
||||
if (_r < repMinimum)
|
||||
return false;
|
||||
if (_r > repMaximum)
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
// folds a value into bounds
|
||||
virtual void foldsInBounds(double & _r) const
|
||||
{
|
||||
long iloc;
|
||||
double dlargloc = 2 * range() ;
|
||||
|
||||
if (fabs(_r) > 1.0E9) // iloc too large!
|
||||
{
|
||||
_r = uniform();
|
||||
return;
|
||||
}
|
||||
|
||||
if ( (_r > maximum()) )
|
||||
{
|
||||
iloc = (long) ( (_r-minimum()) / dlargloc ) ;
|
||||
_r -= dlargloc * iloc ;
|
||||
if ( _r > maximum() )
|
||||
_r = 2*maximum() - _r ;
|
||||
}
|
||||
|
||||
if (_r < minimum())
|
||||
{
|
||||
iloc = (long) ( (maximum()-_r) / dlargloc ) ;
|
||||
_r += dlargloc * iloc ;
|
||||
if (_r < minimum())
|
||||
_r = 2*minimum() - _r ;
|
||||
}
|
||||
}
|
||||
|
||||
// truncates to the bounds
|
||||
virtual void truncate(double & _r) const
|
||||
{
|
||||
if (_r < repMinimum)
|
||||
_r = repMinimum;
|
||||
else if (_r > repMaximum)
|
||||
_r = repMaximum;
|
||||
return;
|
||||
}
|
||||
|
||||
// methods from eoPersistent
|
||||
/**
|
||||
* Read object.
|
||||
* @param _is A std::istream.
|
||||
* but reading should not be done here, because of bound problems
|
||||
* see eoRealVectorBounds
|
||||
*/
|
||||
virtual void readFrom(std::istream& _is)
|
||||
{
|
||||
(void)_is;
|
||||
|
||||
throw std::runtime_error("Should not use eoRealInterval::readFrom");
|
||||
}
|
||||
|
||||
/**
|
||||
* Write object. It's called printOn since it prints the object on a stream.
|
||||
* @param _os A std::ostream.
|
||||
*/
|
||||
virtual void printOn(std::ostream& _os) const
|
||||
{
|
||||
_os << "[" << repMinimum << "," << repMaximum << "]";
|
||||
}
|
||||
|
||||
/** for memory managements - ugly */
|
||||
virtual eoRealBounds * dup() const
|
||||
{
|
||||
return new eoRealInterval(*this);
|
||||
}
|
||||
|
||||
private :
|
||||
double repMinimum;
|
||||
double repMaximum;
|
||||
double repRange; // to minimize operations ???
|
||||
};
|
||||
|
||||
/**
|
||||
* an eoRealBound bounded from below only
|
||||
|
||||
@ingroup Bounds
|
||||
*/
|
||||
class eoRealBelowBound : public eoRealBounds
|
||||
{
|
||||
public :
|
||||
virtual ~eoRealBelowBound(){}
|
||||
/**
|
||||
Simple bounds = minimum
|
||||
*/
|
||||
eoRealBelowBound(double _min=0) :
|
||||
repMinimum(_min)
|
||||
{}
|
||||
|
||||
// accessors
|
||||
virtual double minimum() const { return repMinimum; }
|
||||
|
||||
virtual double maximum() const
|
||||
{
|
||||
throw std::logic_error("Trying to get maximum of eoRealBelowBound");
|
||||
}
|
||||
virtual double range() const
|
||||
{
|
||||
throw std::logic_error("Trying to get range of eoRealBelowBound");
|
||||
}
|
||||
|
||||
// random generators
|
||||
virtual double uniform(eoRng & _rng = eo::rng) const
|
||||
{
|
||||
(void)_rng;
|
||||
|
||||
throw std::logic_error("Trying to generate uniform values in eoRealBelowBound");
|
||||
}
|
||||
|
||||
// description
|
||||
virtual bool isBounded(void) const {return false;}
|
||||
virtual bool hasNoBoundAtAll(void) const {return false;}
|
||||
virtual bool isMinBounded(void) const {return true;}
|
||||
virtual bool isMaxBounded(void) const {return false;}
|
||||
|
||||
// says if a given double is within the bounds
|
||||
virtual bool isInBounds(double _r) const
|
||||
{
|
||||
if (_r < repMinimum)
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
// folds a value into bounds
|
||||
virtual void foldsInBounds(double & _r) const
|
||||
{
|
||||
// easy as a pie: symmetry w.r.t. minimum
|
||||
if (_r < repMinimum) // nothing to do otherwise
|
||||
_r = 2*repMinimum - _r;
|
||||
return ;
|
||||
}
|
||||
|
||||
// truncates to the bounds
|
||||
virtual void truncate(double & _r) const
|
||||
{
|
||||
if (_r < repMinimum)
|
||||
_r = repMinimum;
|
||||
return;
|
||||
}
|
||||
|
||||
// methods from eoPersistent
|
||||
/**
|
||||
* Read object.
|
||||
* @param _is A std::istream.
|
||||
* but reading should not be done here, because of bound problems
|
||||
* see eoRealVectorBounds
|
||||
*/
|
||||
virtual void readFrom(std::istream& _is)
|
||||
{
|
||||
(void)_is;
|
||||
|
||||
throw std::runtime_error("Should not use eoRealBelowBound::readFrom");
|
||||
}
|
||||
|
||||
/**
|
||||
* Write object. It's called printOn since it prints the object on a stream.
|
||||
* @param _os A std::ostream.
|
||||
*/
|
||||
virtual void printOn(std::ostream& _os) const
|
||||
{
|
||||
_os << "[" << repMinimum << ",+inf]";
|
||||
}
|
||||
|
||||
/** for memory managements - ugly */
|
||||
virtual eoRealBounds * dup() const
|
||||
{
|
||||
return new eoRealBelowBound(*this);
|
||||
}
|
||||
|
||||
private :
|
||||
double repMinimum;
|
||||
};
|
||||
|
||||
/**
|
||||
An eoRealBound bounded from above only
|
||||
*/
|
||||
class eoRealAboveBound : public eoRealBounds
|
||||
{
|
||||
public :
|
||||
virtual ~eoRealAboveBound(){}
|
||||
|
||||
/**
|
||||
Simple bounds = minimum
|
||||
*/
|
||||
eoRealAboveBound(double _max=0) :
|
||||
repMaximum(_max)
|
||||
{}
|
||||
|
||||
// accessors
|
||||
virtual double maximum() const { return repMaximum; }
|
||||
|
||||
virtual double minimum() const
|
||||
{
|
||||
throw std::logic_error("Trying to get minimum of eoRealAboveBound");
|
||||
}
|
||||
virtual double range() const
|
||||
{
|
||||
throw std::logic_error("Trying to get range of eoRealAboveBound");
|
||||
}
|
||||
|
||||
// random generators
|
||||
virtual double uniform(eoRng & _rng = eo::rng) const
|
||||
{
|
||||
(void)_rng;
|
||||
|
||||
throw std::logic_error("Trying to generate uniform values in eoRealAboveBound");
|
||||
}
|
||||
|
||||
// description
|
||||
virtual bool isBounded(void) const {return false;}
|
||||
virtual bool hasNoBoundAtAll(void) const {return false;}
|
||||
virtual bool isMinBounded(void) const {return false;}
|
||||
virtual bool isMaxBounded(void) const {return true;}
|
||||
|
||||
// says if a given double is within the bounds
|
||||
virtual bool isInBounds(double _r) const
|
||||
{
|
||||
if (_r > repMaximum)
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
// folds a value into bounds
|
||||
virtual void foldsInBounds(double & _r) const
|
||||
{
|
||||
// easy as a pie: symmetry w.r.t. maximum
|
||||
if (_r > repMaximum) // nothing to do otherwise
|
||||
_r = 2*repMaximum - _r;
|
||||
return ;
|
||||
}
|
||||
|
||||
// truncates to the bounds
|
||||
virtual void truncate(double & _r) const
|
||||
{
|
||||
if (_r > repMaximum)
|
||||
_r = repMaximum;
|
||||
return;
|
||||
}
|
||||
|
||||
// methods from eoPersistent
|
||||
/**
|
||||
* Read object.
|
||||
* @param _is A std::istream.
|
||||
* but reading should not be done here, because of bound problems
|
||||
* see eoRealVectorBounds
|
||||
*/
|
||||
virtual void readFrom(std::istream& _is)
|
||||
{
|
||||
(void)_is;
|
||||
|
||||
throw std::runtime_error("Should not use eoRealAboveBound::readFrom");
|
||||
}
|
||||
|
||||
/**
|
||||
* Write object. It's called printOn since it prints the object on a stream.
|
||||
* @param _os A std::ostream.
|
||||
*/
|
||||
virtual void printOn(std::ostream& _os) const
|
||||
{
|
||||
_os << "[-inf," << repMaximum << "]";
|
||||
}
|
||||
|
||||
/** for memory managements - ugly */
|
||||
virtual eoRealBounds * dup() const
|
||||
{
|
||||
return new eoRealAboveBound(*this);
|
||||
}
|
||||
|
||||
private :
|
||||
double repMaximum;
|
||||
};
|
||||
|
||||
//////////////////////// tentative for a general BOUND class that is constructed from a string
|
||||
|
||||
/** A class that encapsulate all possible eoIntBounds.
|
||||
* Mandatory in order to read through the parser
|
||||
|
||||
@ingroup Bounds
|
||||
*/
|
||||
class eoGeneralRealBounds : public eoRealBounds
|
||||
{
|
||||
public:
|
||||
/** Ctor: from a string, chooses the type of bound */
|
||||
eoGeneralRealBounds(std::string _s = "[-infinity,+infinity]")
|
||||
{
|
||||
repBound = getBoundsFromString(_s);
|
||||
}
|
||||
|
||||
/** Need a Cpy Ctor because we are allocating memory */
|
||||
eoGeneralRealBounds(const eoGeneralRealBounds & _b):eoRealBounds(_b)
|
||||
{
|
||||
// replicate the embedded bound (I'm pretty sure there is another
|
||||
// way to do that !!!
|
||||
|
||||
bool minBounded = _b.isMinBounded();
|
||||
bool maxBounded = _b.isMaxBounded();
|
||||
double minimum, maximum;
|
||||
const eoRealBounds & bb = _b.theBounds();
|
||||
if (minBounded) minimum = bb.minimum();
|
||||
if (maxBounded) maximum = bb.maximum();
|
||||
|
||||
if (minBounded && maxBounded)
|
||||
repBound = new eoRealInterval(minimum, maximum);
|
||||
else if (!minBounded && !maxBounded) // no bound at all
|
||||
repBound = new eoRealNoBounds;
|
||||
else if (!minBounded && maxBounded)
|
||||
repBound = new eoRealAboveBound(maximum);
|
||||
else if (minBounded && !maxBounded)
|
||||
repBound = new eoRealBelowBound(minimum);
|
||||
}
|
||||
|
||||
eoGeneralRealBounds& operator=(const eoGeneralRealBounds& _b)
|
||||
{
|
||||
// replicate the embedded bound (I'm pretty sure there is another
|
||||
// way to do that !!!
|
||||
|
||||
bool minBounded = _b.isMinBounded();
|
||||
bool maxBounded = _b.isMaxBounded();
|
||||
double minimum, maximum;
|
||||
const eoRealBounds & bb = _b.theBounds();
|
||||
if (minBounded) minimum = bb.minimum();
|
||||
if (maxBounded) maximum = bb.maximum();
|
||||
|
||||
// first delete the embedded bounds if necessary
|
||||
if (repBound)
|
||||
delete repBound;
|
||||
// now reallocate
|
||||
if (minBounded && maxBounded)
|
||||
repBound = new eoRealInterval(minimum, maximum);
|
||||
else if (!minBounded && !maxBounded) // no bound at all
|
||||
repBound = new eoRealNoBounds;
|
||||
else if (!minBounded && maxBounded)
|
||||
repBound = new eoRealAboveBound(maximum);
|
||||
else if (minBounded && !maxBounded)
|
||||
repBound = new eoRealBelowBound(minimum);
|
||||
return (*this);
|
||||
}
|
||||
|
||||
|
||||
/** Need a Dtor because we allocate an actual bound */
|
||||
~eoGeneralRealBounds()
|
||||
{
|
||||
delete repBound;
|
||||
}
|
||||
|
||||
///// and now all methods from the embedded bounds
|
||||
/** Self-Test: true if ***both*** a min and a max
|
||||
*/
|
||||
virtual bool isBounded(void) const {return repBound->isBounded();}
|
||||
|
||||
/** Self-Test: true if no min ***and*** no max
|
||||
* hence no further need to test/truncate/fold anything
|
||||
*/
|
||||
virtual bool hasNoBoundAtAll(void) const {return repBound->hasNoBoundAtAll();}
|
||||
|
||||
/** Self-Test: bounded from below???
|
||||
*/
|
||||
virtual bool isMinBounded(void) const {return repBound->isMinBounded();}
|
||||
|
||||
/** Self-Test: bounded from above???
|
||||
*/
|
||||
virtual bool isMaxBounded(void) const {return repBound->isMaxBounded();}
|
||||
|
||||
/** Test on a value: is it in bounds?
|
||||
*/
|
||||
virtual bool isInBounds(double _x) const {return repBound->isInBounds(_x);}
|
||||
|
||||
/** Put value back into bounds - by folding back and forth
|
||||
*/
|
||||
virtual void foldsInBounds(double & _x) const {return repBound->foldsInBounds(_x);}
|
||||
|
||||
/** Put value back into bounds - by truncating to a boundary value
|
||||
*/
|
||||
virtual void truncate(double & _x) const {return repBound->truncate(_x);}
|
||||
|
||||
/** get minimum value
|
||||
* std::exception if does not exist
|
||||
*/
|
||||
virtual double minimum() const {return repBound->minimum();}
|
||||
/** get maximum value
|
||||
* std::exception if does not exist
|
||||
*/
|
||||
virtual double maximum() const {return repBound->maximum();}
|
||||
/** get range
|
||||
* std::exception if unbounded
|
||||
*/
|
||||
virtual double range() const {return repBound->range();}
|
||||
|
||||
/** random generator of uniform numbers in bounds
|
||||
* std::exception if unbounded
|
||||
*/
|
||||
virtual double uniform(eoRng & _rng = eo::rng) const {(void)_rng; return repBound->uniform();}
|
||||
|
||||
/** for memory managements - ugly */
|
||||
virtual eoRealBounds * dup() const {return repBound->dup();}
|
||||
|
||||
/** for efficiency, it's better to use the embedded boud directly */
|
||||
const eoRealBounds & theBounds() const { return *repBound;}
|
||||
|
||||
/** don't forget the printOn method -
|
||||
* again that of the embedded bound
|
||||
*/
|
||||
virtual void printOn(std::ostream& _os) const
|
||||
{
|
||||
repBound->printOn(_os);
|
||||
}
|
||||
|
||||
/** no readFrom ??? Have to check that later */
|
||||
virtual void readFrom(std::istream& _is)
|
||||
{
|
||||
std::string s;
|
||||
_is >> s;
|
||||
if (repBound)
|
||||
delete repBound;
|
||||
repBound = getBoundsFromString(s);
|
||||
}
|
||||
|
||||
private:
|
||||
// reading from a string
|
||||
eoRealBounds * getBoundsFromString(std::string);
|
||||
|
||||
eoRealBounds * repBound;
|
||||
};
|
||||
|
||||
|
||||
#endif
|
||||
429
eo/src/utils/eoRealVectorBounds.h
Normal file
429
eo/src/utils/eoRealVectorBounds.h
Normal file
|
|
@ -0,0 +1,429 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoRealVectorBounds.h
|
||||
// (c) Marc Schoenauer 2001, Maarten Keijzer 2000, 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
|
||||
Marc.Schoenauer@polytechnique.fr
|
||||
mak@dhi.dk
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _eoRealVectorBounds_h
|
||||
#define _eoRealVectorBounds_h
|
||||
|
||||
#include <stdexcept> // std::exceptions!
|
||||
#include <utils/eoRNG.h>
|
||||
#include <utils/eoRealBounds.h>
|
||||
|
||||
/**
|
||||
Vector type for bounds (see eoRealBounds.h for scalar types)
|
||||
------------
|
||||
Class eoRealVectorBounds implements the std::vectorized version:
|
||||
it is basically a std::vector of eoRealBounds * and forwards all request
|
||||
to the elements of the std::vector.
|
||||
|
||||
This file also contains the global variables and eoDummyVectorNoBounds
|
||||
that are used as defaults in ctors (i.e. when no
|
||||
bounds are given, it is assumed unbounded values)
|
||||
|
||||
THe 2 main classes defined here are
|
||||
|
||||
eoRealBaseVectorBounds, base class that handles all useful functions
|
||||
eoRealVectorBounds which derives from the preceding *and* eoPersistent
|
||||
and also has a mechanism for memory handling of the pointers
|
||||
it has to allocate
|
||||
|
||||
@ingroup Bounds
|
||||
*/
|
||||
class eoRealBaseVectorBounds : public std::vector<eoRealBounds *>
|
||||
{
|
||||
public:
|
||||
// virtual desctructor (to avoid warning?)
|
||||
virtual ~eoRealBaseVectorBounds(){}
|
||||
|
||||
/** Default Ctor.
|
||||
*/
|
||||
eoRealBaseVectorBounds() : std::vector<eoRealBounds *>(0) {}
|
||||
|
||||
/** Ctor: same bounds for everybody, given as an eoRealBounds
|
||||
*/
|
||||
eoRealBaseVectorBounds(unsigned _dim, eoRealBounds & _bounds) :
|
||||
std::vector<eoRealBounds *>(_dim, &_bounds)
|
||||
{}
|
||||
|
||||
/** Ctor, particular case of dim-2
|
||||
*/
|
||||
eoRealBaseVectorBounds(eoRealBounds & _xbounds, eoRealBounds & _ybounds) :
|
||||
std::vector<eoRealBounds *>(0)
|
||||
{
|
||||
push_back( &_xbounds);
|
||||
push_back( &_ybounds);
|
||||
}
|
||||
|
||||
/** test: is i_th component bounded
|
||||
*/
|
||||
virtual bool isBounded(unsigned _i)
|
||||
{
|
||||
return (*this)[_i]->isBounded();
|
||||
}
|
||||
|
||||
/** test: bounded iff all are bounded
|
||||
*/
|
||||
virtual bool isBounded(void)
|
||||
{
|
||||
for (unsigned i=0; i<size(); i++)
|
||||
if (! (*this)[i]->isBounded())
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Self-test: true iff i_th component has no bounds at all
|
||||
*/
|
||||
virtual bool hasNoBoundAtAll(unsigned _i)
|
||||
{
|
||||
return (*this)[_i]->hasNoBoundAtAll();
|
||||
}
|
||||
|
||||
/** Self-test: true iff all components have no bound at all
|
||||
*/
|
||||
virtual bool hasNoBoundAtAll(void)
|
||||
{
|
||||
for (unsigned i=0; i<size(); i++)
|
||||
if (! (*this)[i]->hasNoBoundAtAll())
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
virtual bool isMinBounded(unsigned _i)
|
||||
{ return (*this)[_i]->isMinBounded();} ;
|
||||
|
||||
virtual bool isMaxBounded(unsigned _i)
|
||||
{ return (*this)[_i]->isMaxBounded();} ;
|
||||
|
||||
/** Folds a real value back into the bounds - i_th component
|
||||
*/
|
||||
virtual void foldsInBounds(unsigned _i, double & _r)
|
||||
{
|
||||
(*this)[_i]->foldsInBounds(_r);
|
||||
}
|
||||
|
||||
/** Folds all variables of a std::vector of real values into the bounds
|
||||
*/
|
||||
virtual void foldsInBounds(std::vector<double> & _v)
|
||||
{
|
||||
for (unsigned i=0; i<size(); i++)
|
||||
{
|
||||
(*this)[i]->foldsInBounds(_v[i]);
|
||||
}
|
||||
}
|
||||
|
||||
/** Truncates a real value to the bounds - i_th component
|
||||
*/
|
||||
virtual void truncate(unsigned _i, double & _r)
|
||||
{
|
||||
(*this)[_i]->truncate(_r);
|
||||
}
|
||||
|
||||
/** truncates all variables of a std::vector of real values to the bounds
|
||||
*/
|
||||
virtual void truncate(std::vector<double> & _v)
|
||||
{
|
||||
for (unsigned i=0; i<size(); i++)
|
||||
{
|
||||
(*this)[i]->truncate(_v[i]);
|
||||
}
|
||||
}
|
||||
|
||||
/** test: is i_th component within the bounds?
|
||||
*/
|
||||
virtual bool isInBounds(unsigned _i, double _r)
|
||||
{ return (*this)[_i]->isInBounds(_r); }
|
||||
|
||||
/** test: are ALL components within the bounds?
|
||||
*/
|
||||
virtual bool isInBounds(std::vector<double> _v)
|
||||
{
|
||||
for (unsigned i=0; i<size(); i++)
|
||||
if (! isInBounds(i, _v[i]))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Accessors: will raise an std::exception if these do not exist
|
||||
*/
|
||||
virtual double minimum(unsigned _i) {return (*this)[_i]->minimum();}
|
||||
virtual double maximum(unsigned _i) {return (*this)[_i]->maximum();}
|
||||
virtual double range(unsigned _i) {return (*this)[_i]->range();}
|
||||
|
||||
/** Computes the average range
|
||||
* An std::exception will be raised if one of the component is unbounded
|
||||
*/
|
||||
virtual double averageRange()
|
||||
{
|
||||
double r=0.0;
|
||||
for (unsigned i=0; i<size(); i++)
|
||||
r += range(i);
|
||||
return r/size();
|
||||
}
|
||||
|
||||
/** Generates a random number in i_th range
|
||||
* An std::exception will be raised if one of the component is unbounded
|
||||
*/
|
||||
virtual double uniform(unsigned _i, eoRng & _rng = eo::rng)
|
||||
{
|
||||
(void)_rng;
|
||||
|
||||
double r= (*this)[_i]->uniform();
|
||||
return r;
|
||||
}
|
||||
|
||||
/** fills a std::vector with uniformly chosen variables in bounds
|
||||
* An std::exception will be raised if one of the component is unbounded
|
||||
*/
|
||||
void uniform(std::vector<double> & _v, eoRng & _rng = eo::rng)
|
||||
{
|
||||
_v.resize(size());
|
||||
for (unsigned i=0; i<size(); i++)
|
||||
{
|
||||
_v[i] = uniform(i, _rng);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Write object. It's called printOn since it prints the object on a stream.
|
||||
* @param _os A std::ostream.
|
||||
*/
|
||||
virtual void printOn(std::ostream& _os) const
|
||||
{
|
||||
for (unsigned i=0; i<size(); i++)
|
||||
{
|
||||
operator[](i)->printOn(_os);
|
||||
_os << ";";
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
////////////////////////////////////////////////////////////////////
|
||||
/** Now a derived class, for parser reading
|
||||
* It holds some of the bounds (and destroy them when dying)
|
||||
|
||||
@ingroup Bounds
|
||||
*/
|
||||
class eoRealVectorBounds : public eoRealBaseVectorBounds, public eoPersistent
|
||||
{
|
||||
public:
|
||||
/** Default Ctor will call base class default ctor
|
||||
*/
|
||||
eoRealVectorBounds():eoRealBaseVectorBounds() {}
|
||||
|
||||
/** Ctor: same bounds for everybody, given as an eoRealBounds
|
||||
*/
|
||||
eoRealVectorBounds(unsigned _dim, eoRealBounds & _bounds) :
|
||||
eoRealBaseVectorBounds(_dim, _bounds), factor(1,_dim), ownedBounds(0)
|
||||
{}
|
||||
|
||||
/** Ctor, particular case of dim-2
|
||||
*/
|
||||
eoRealVectorBounds(eoRealBounds & _xbounds, eoRealBounds & _ybounds) :
|
||||
eoRealBaseVectorBounds(_xbounds, _ybounds), factor(2,1), ownedBounds(0)
|
||||
{}
|
||||
|
||||
/** Simple bounds = minimum and maximum (allowed)
|
||||
*/
|
||||
eoRealVectorBounds(unsigned _dim, double _min, double _max) :
|
||||
eoRealBaseVectorBounds(), factor(1, _dim), ownedBounds(0)
|
||||
{
|
||||
if (_max-_min<=0)
|
||||
throw std::logic_error("Void range in eoRealVectorBounds");
|
||||
eoRealBounds *ptBounds = new eoRealInterval(_min, _max);
|
||||
// handle memory once
|
||||
ownedBounds.push_back(ptBounds);
|
||||
// same bound for everyone
|
||||
for (unsigned int i=0; i<_dim; i++)
|
||||
push_back(ptBounds);
|
||||
}
|
||||
|
||||
/** Ctor: different bounds for different variables, std::vectors of double
|
||||
*/
|
||||
eoRealVectorBounds(std::vector<double> _min, std::vector<double> _max) :
|
||||
factor(_min.size(), 1), ownedBounds(0)
|
||||
{
|
||||
if (_max.size() != _min.size())
|
||||
throw std::logic_error("Dimensions don't match in eoRealVectorBounds");
|
||||
// the bounds
|
||||
eoRealBounds *ptBounds;
|
||||
for (unsigned i=0; i<_min.size(); i++)
|
||||
{
|
||||
ptBounds = new eoRealInterval(_min[i], _max[i]);
|
||||
ownedBounds.push_back(ptBounds);
|
||||
push_back(ptBounds);
|
||||
}
|
||||
}
|
||||
|
||||
/** Ctor from a std::string
|
||||
* and don't worry, the readFrom(std::string) starts by setting everything to 0!
|
||||
*/
|
||||
eoRealVectorBounds(std::string _s) : eoRealBaseVectorBounds()
|
||||
{
|
||||
readFrom(_s);
|
||||
}
|
||||
|
||||
/** Dtor: destroy all ownedBounds - BUG ???*/
|
||||
virtual ~eoRealVectorBounds()
|
||||
{
|
||||
// std::cout << "Dtor, avec size = " << ownedBounds.size() << std::endl;
|
||||
// for (unsigned i = 0; i < ownedBounds.size(); ++i)
|
||||
// {
|
||||
// delete ownedBounds[i];
|
||||
// }
|
||||
}
|
||||
|
||||
|
||||
// methods from eoPersistent
|
||||
/**
|
||||
* Read object from a stream
|
||||
* only calls the readFrom(std::string) - for param reading
|
||||
* @param _is A std::istream.
|
||||
*/
|
||||
virtual void readFrom(std::istream& _is) ;
|
||||
|
||||
/**
|
||||
* Read object from a std::string
|
||||
* @param _s A std::istream.
|
||||
*/
|
||||
virtual void readFrom(std::string _s) ;
|
||||
|
||||
/** overload printOn method to save space */
|
||||
virtual void printOn(std::ostream& _os) const
|
||||
{
|
||||
if (factor[0]>1)
|
||||
_os << factor[0] ;
|
||||
operator[](0)->printOn(_os);
|
||||
|
||||
// other bounds
|
||||
unsigned int index=factor[0];
|
||||
if (factor.size()>1)
|
||||
for (unsigned i=1; i<factor.size(); i++)
|
||||
{
|
||||
_os << ";";
|
||||
if (factor[i] > 1)
|
||||
_os << factor[i];
|
||||
operator[](index)->printOn(_os);
|
||||
index += factor[i];
|
||||
}
|
||||
}
|
||||
|
||||
/** Eventually increases the size by duplicating last bound */
|
||||
void adjust_size(unsigned _dim);
|
||||
|
||||
/** need to rewrite copy ctor and assignement operator
|
||||
* because of ownedBounds */
|
||||
eoRealVectorBounds(const eoRealVectorBounds &);
|
||||
|
||||
private:// WARNING: there is no reason for both std::vector below
|
||||
//to be synchronized in any manner
|
||||
std::vector<unsigned int> factor; // std::list of nb of "grouped" bounds
|
||||
std::vector<eoRealBounds *> ownedBounds;
|
||||
// keep this one private
|
||||
eoRealVectorBounds& operator=(const eoRealVectorBounds&);
|
||||
};
|
||||
|
||||
//////////////////////////////////////////////////////////////
|
||||
/** the dummy unbounded eoRealVectorBounds: usefull if you don't need bounds!
|
||||
* everything is inlined.
|
||||
* Warning: we do need this class, and not only a std::vector<eoRealNoBounds *>
|
||||
|
||||
@ingroup Bounds
|
||||
*/
|
||||
class eoRealVectorNoBounds: public eoRealVectorBounds
|
||||
{
|
||||
public:
|
||||
// virtual desctructor (to avoid warning?)
|
||||
virtual ~eoRealVectorNoBounds(){}
|
||||
|
||||
/**
|
||||
* Ctor: nothing to do, but beware of dimension: call base class ctor
|
||||
*/
|
||||
eoRealVectorNoBounds(unsigned _dim) :
|
||||
eoRealVectorBounds( (_dim?_dim:1), eoDummyRealNoBounds)
|
||||
{}
|
||||
|
||||
|
||||
virtual bool isBounded(unsigned) {return false;}
|
||||
virtual bool isBounded(void) {return false;}
|
||||
|
||||
virtual bool hasNoBoundAtAll(unsigned) {return true;}
|
||||
virtual bool hasNoBoundAtAll(void) {return true;}
|
||||
|
||||
virtual bool isMinBounded(unsigned) {return false;}
|
||||
virtual bool isMaxBounded(unsigned) {return false;}
|
||||
|
||||
virtual void foldsInBounds(unsigned, double &) {return;}
|
||||
virtual void foldsInBounds(std::vector<double> &) {return;}
|
||||
|
||||
virtual void truncate(unsigned, double &) {return;}
|
||||
virtual void truncate(std::vector<double> &) {return;}
|
||||
|
||||
virtual bool isInBounds(unsigned, double) {return true;}
|
||||
virtual bool isInBounds(std::vector<double>) {return true;}
|
||||
|
||||
// accessors
|
||||
virtual double minimum(unsigned)
|
||||
{
|
||||
throw std::logic_error("Trying to get minimum of eoRealVectorNoBounds");
|
||||
}
|
||||
virtual double maximum(unsigned)
|
||||
{
|
||||
throw std::logic_error("Trying to get maximum of eoRealVectorNoBounds");
|
||||
}
|
||||
virtual double range(unsigned)
|
||||
{
|
||||
throw std::logic_error("Trying to get range of eoRealVectorNoBounds");
|
||||
}
|
||||
|
||||
virtual double averageRange()
|
||||
{
|
||||
throw std::logic_error("Trying to get average range of eoRealVectorNoBounds");
|
||||
}
|
||||
|
||||
// random generators
|
||||
virtual double uniform(unsigned, eoRng & _rng = eo::rng)
|
||||
{
|
||||
(void)_rng;
|
||||
|
||||
throw std::logic_error("No uniform distribution on eoRealVectorNoBounds");
|
||||
}
|
||||
|
||||
// fills a std::vector with uniformly chosen variables in bounds
|
||||
void uniform(std::vector<double> &, eoRng & _rng = eo::rng)
|
||||
{
|
||||
(void)_rng;
|
||||
|
||||
throw std::logic_error("No uniform distribution on eoRealVectorNoBounds");
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
|
||||
|
||||
/** one object for all - see eoRealBounds.cpp
|
||||
@ingroup Bounds
|
||||
*/
|
||||
extern eoRealVectorNoBounds eoDummyVectorNoBounds;
|
||||
#endif
|
||||
161
eo/src/utils/eoRndGenerators.h
Normal file
161
eo/src/utils/eoRndGenerators.h
Normal file
|
|
@ -0,0 +1,161 @@
|
|||
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
-----------------------------------------------------------------------------
|
||||
eoRndGenerators.h
|
||||
|
||||
mimics the rnd_generator.h by putting the generators in the EO-hierarchy
|
||||
|
||||
(c) Maarten Keijzer (mak@dhi.dk) and GeNeura Team, 1999, 2000
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
|
||||
*/
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef eoRndGenerators_h
|
||||
#define eoRndGenerators_h
|
||||
|
||||
#include "eoRNG.h"
|
||||
#include <eoFunctor.h>
|
||||
#include <stdexcept>
|
||||
|
||||
/** @defgroup Random Random number generation
|
||||
*
|
||||
* @ingroup Utilities
|
||||
* @{
|
||||
*/
|
||||
|
||||
using eo::rng;
|
||||
|
||||
/**
|
||||
By popular demand re-introducing a base class for a family of
|
||||
random number generators. Derived members of this class are useful
|
||||
to initialize fixed/variable length genotypes that have an 'atomic' type
|
||||
in an indepent way (thus without employing any knowledge about the problem domain).
|
||||
|
||||
See derived classes eoUniformGenerator, eoBooleanGenerator, eoNormalGenerator and eoNegExpGenerator
|
||||
*/
|
||||
template <class T>
|
||||
class eoRndGenerator : public eoF<T>
|
||||
{
|
||||
typedef T AtomType;
|
||||
};
|
||||
|
||||
/**
|
||||
The class eoUniform can be used in the STL generate function
|
||||
to easily generate random floats and doubles. It can also
|
||||
be used for ints and unsigneds by virtue of the static_cast
|
||||
in the generator function.
|
||||
|
||||
Also present is a specialization for boolean, that will
|
||||
ignore the minima and maxima that are possibly set and will
|
||||
return an unbiased flip of a coin. For a biased flip, use the eoBoolean
|
||||
|
||||
either in [0, _max) if only 1 value (_max) is given
|
||||
(or none, as _max defaults to 1.0)
|
||||
or in [_min,_max) if 2 values are given (_min, _max)
|
||||
*/
|
||||
template <class T = double> class eoUniformGenerator : public eoRndGenerator<T>
|
||||
{
|
||||
// added new ctor with 2 params, and modified the data to minim and range
|
||||
// (was maxim only). MS 3/11/2000
|
||||
public :
|
||||
eoUniformGenerator(T _max = T(1.0), eoRng& _rng = rng) :
|
||||
minim(T(0.0)), range(_max), uniform(_rng) {}
|
||||
eoUniformGenerator(T _min, T _max, eoRng& _rng = rng) :
|
||||
minim(_min), range(_max-_min), uniform(_rng)
|
||||
{
|
||||
if (_min>_max)
|
||||
throw std::logic_error("Min is greater than Max in uniform_generator");
|
||||
}
|
||||
|
||||
/**
|
||||
Generates the number, uses a static_cast to get the right behaviour
|
||||
for ints and unsigneds
|
||||
*/
|
||||
T operator()(void) { return minim+static_cast<T>(uniform.uniform(range)); }
|
||||
/** @example t-eoUniform.cpp
|
||||
*/
|
||||
|
||||
private :
|
||||
T minim;
|
||||
T range;
|
||||
eoRng& uniform;
|
||||
};
|
||||
/** @example t-eoRandom.cpp
|
||||
*/
|
||||
|
||||
|
||||
/// Specialization for bool, does an unbiased coin flip
|
||||
template <>
|
||||
inline bool eoUniformGenerator<bool>::operator()(void)
|
||||
{
|
||||
return uniform.flip(0.5);
|
||||
}
|
||||
|
||||
/**
|
||||
The class eoBooleanGenerator can be used in the STL generate function
|
||||
to easily generate random booleans with a specified bias
|
||||
\ingroup bitstring
|
||||
*/
|
||||
class eoBooleanGenerator : public eoRndGenerator<bool>
|
||||
{
|
||||
public :
|
||||
eoBooleanGenerator(float _bias = 0.5, eoRng& _rng = rng) : bias(_bias), gen(_rng) {}
|
||||
|
||||
bool operator()(void) { return gen.flip(bias); }
|
||||
private :
|
||||
float bias;
|
||||
eoRng& gen;
|
||||
};
|
||||
|
||||
/**
|
||||
The class normal_generator can be used in the STL generate function
|
||||
to easily generate gaussian distributed floats and doubles. The user
|
||||
can supply a standard deviation which defaults to 1.
|
||||
*/
|
||||
template <class T = double> class eoNormalGenerator : public eoRndGenerator<T>
|
||||
{
|
||||
public :
|
||||
eoNormalGenerator(T _stdev = T(1.0), eoRng& _rng = rng) : stdev(_stdev), normal(_rng) {}
|
||||
|
||||
T operator()(void) { return (T) normal.normal(stdev); }
|
||||
|
||||
private :
|
||||
T stdev;
|
||||
eoRng& normal;
|
||||
};
|
||||
|
||||
/**
|
||||
The class negexp_generator can be used in the STL generate function
|
||||
to easily generate negative exponential distributed floats and doubles. The user
|
||||
can supply a mean.
|
||||
*/
|
||||
template <class T = double> class eoNegExpGenerator : public eoRndGenerator<T>
|
||||
{
|
||||
public :
|
||||
eoNegExpGenerator(T _mean = 1.0, eoRng& _rng = rng) : mean(_mean), negexp(_rng) {}
|
||||
|
||||
T operator()(void) { return (T) negexp.negexp(mean); }
|
||||
|
||||
private :
|
||||
T mean;
|
||||
eoRng& negexp;
|
||||
};
|
||||
|
||||
/** @} */
|
||||
#endif
|
||||
65
eo/src/utils/eoScalarFitnessStat.h
Normal file
65
eo/src/utils/eoScalarFitnessStat.h
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoScalarFitnessStat.h
|
||||
// (c) Marc Schoenauer, Maarten Keijzer and GeNeura Team, 2000, 2001
|
||||
/*
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
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
|
||||
mkeijzer@dhi.dk
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _eoScalarFitnessStat_h
|
||||
#define _eoScalarFitnessStat_h
|
||||
|
||||
#include <utils/eoRealVectorBounds.h>
|
||||
#include <utils/eoStat.h>
|
||||
|
||||
/**
|
||||
The fitnesses of a whole population, as a std::vector
|
||||
|
||||
@ingroup Stats
|
||||
*/
|
||||
template <class EOT, class FitT = typename EOT::Fitness>
|
||||
class eoScalarFitnessStat : public eoSortedStat<EOT, std::vector<double> >
|
||||
{
|
||||
public:
|
||||
|
||||
using eoSortedStat<EOT, std::vector<double> >::value;
|
||||
|
||||
eoScalarFitnessStat(std::string _description = "FitnessES",
|
||||
eoRealVectorBounds & _bounds = eoDummyVectorNoBounds)
|
||||
: eoSortedStat<EOT, std::vector<double> >(std::vector<double>(0), _description),
|
||||
range(*_bounds[0])
|
||||
{}
|
||||
|
||||
virtual void operator()(const std::vector<const EOT*>& _popPters)
|
||||
{
|
||||
value().resize(_popPters.size());
|
||||
for (unsigned i=0; i<_popPters.size(); i++)
|
||||
{
|
||||
value()[i] = _popPters[i]->fitness();
|
||||
range.truncate(value()[i]);
|
||||
}
|
||||
}
|
||||
|
||||
private :
|
||||
eoRealBounds & range;
|
||||
};
|
||||
|
||||
#endif
|
||||
36
eo/src/utils/eoSignal.cpp
Normal file
36
eo/src/utils/eoSignal.cpp
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
/**
|
||||
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: http://eodev.sourceforge.net
|
||||
|
||||
Autors: todos@geneura.ugr.es, http://geneura.ugr.es
|
||||
Marc.Schoenauer@polytechnique.fr
|
||||
mak@dhi.dk
|
||||
Caner.Candan@univ-angers.fr
|
||||
*/
|
||||
|
||||
#include <utils/eoSignal.h>
|
||||
|
||||
/**
|
||||
* @addtogroup Continuators
|
||||
* @{
|
||||
*/
|
||||
|
||||
// --- Global variables - but don't know what else to do - MS ---
|
||||
std::map< int, bool > signals_called;
|
||||
|
||||
/** @} */
|
||||
106
eo/src/utils/eoSignal.h
Normal file
106
eo/src/utils/eoSignal.h
Normal file
|
|
@ -0,0 +1,106 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
/**
|
||||
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: http://eodev.sourceforge.net
|
||||
|
||||
Authors: todos@geneura.ugr.es, http://geneura.ugr.es
|
||||
Marc.Schoenauer@polytechnique.fr
|
||||
mak@dhi.dk
|
||||
Caner.Candan@univ-angers.fr
|
||||
*/
|
||||
|
||||
#ifndef _eoSignal_h
|
||||
#define _eoSignal_h
|
||||
|
||||
#include <csignal>
|
||||
#include <utils/eoCheckPoint.h>
|
||||
#include <utils/eoLogger.h>
|
||||
|
||||
#include <map>
|
||||
#include <vector>
|
||||
|
||||
/**
|
||||
* @addtogroup Continuators
|
||||
* @{
|
||||
*/
|
||||
|
||||
extern std::map< int, bool > signals_called;
|
||||
|
||||
/** eoSignal inherits from eoCheckPoint including signals handling (see signal(7))
|
||||
*
|
||||
* @ingroup Utilities
|
||||
*/
|
||||
template <class EOT>
|
||||
class eoSignal : public eoCheckPoint<EOT>
|
||||
{
|
||||
public :
|
||||
|
||||
eoSignal( int sig = SIGINT ) : eoCheckPoint<EOT>( _dummyContinue ), _sig( sig )
|
||||
{
|
||||
::signals_called[_sig] = false;
|
||||
|
||||
#ifndef _WINDOWS
|
||||
#ifdef SIGQUIT
|
||||
::signal( _sig, handler );
|
||||
#endif // !SIGQUIT
|
||||
#endif // !_WINDOWS
|
||||
}
|
||||
|
||||
eoSignal( eoContinue<EOT>& _cont, int sig = SIGINT ) : eoCheckPoint<EOT>( _cont ), _sig( sig )
|
||||
{
|
||||
::signals_called[_sig] = false;
|
||||
|
||||
#ifndef _WINDOWS
|
||||
#ifdef SIGQUIT
|
||||
::signal( _sig, handler );
|
||||
#endif // !SIGQUIT
|
||||
#endif // !_WINDOWS
|
||||
}
|
||||
|
||||
bool operator()( const eoPop<EOT>& _pop )
|
||||
{
|
||||
bool& called = ::signals_called[_sig];
|
||||
if ( called )
|
||||
{
|
||||
eo::log << eo::logging << "Signal granted…" << std::endl ;
|
||||
called = false;
|
||||
return this->eoCheckPoint<EOT>::operator()( _pop );
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
virtual std::string className(void) const { return "eoSignal"; }
|
||||
|
||||
static void handler( int sig )
|
||||
{
|
||||
::signals_called[sig] = true;
|
||||
eo::log << eo::logging << "Signal wished…" << std::endl ;
|
||||
}
|
||||
|
||||
private:
|
||||
class DummyContinue : public eoContinue<EOT>
|
||||
{
|
||||
public:
|
||||
bool operator() ( const eoPop<EOT>& ) { return true; }
|
||||
} _dummyContinue;
|
||||
|
||||
int _sig;
|
||||
};
|
||||
|
||||
/** @} */
|
||||
|
||||
#endif // !_eoSignal_h
|
||||
495
eo/src/utils/eoStat.h
Normal file
495
eo/src/utils/eoStat.h
Normal file
|
|
@ -0,0 +1,495 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoStat.h
|
||||
// (c) Marc Schoenauer, Maarten Keijzer and GeNeura Team, 2000
|
||||
// (c) 2010 Thales group
|
||||
/*
|
||||
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: http://eodev.sourceforge.net
|
||||
|
||||
Authors:
|
||||
todos@geneura.ugr.es, http://geneura.ugr.es
|
||||
Marc.Schoenauer@polytechnique.fr
|
||||
mkeijzer@dhi.dk
|
||||
Johann Dréo <johann.dreo@thalesgroup.com>
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _eoStat_h
|
||||
#define _eoStat_h
|
||||
|
||||
#include <numeric> // accumulate
|
||||
|
||||
#include <eoFunctor.h>
|
||||
#include <utils/eoParam.h>
|
||||
#include <eoPop.h>
|
||||
#include <utils/eoMonitor.h>
|
||||
//#include <utils/eoCheckPoint.h>
|
||||
|
||||
/** @defgroup Stats Statistics computation
|
||||
*
|
||||
* Compute various statistics on a population.
|
||||
*
|
||||
* Objects of those classes are generally called by an eoCheckPoint
|
||||
* to compute statistics about the population at a given generation.
|
||||
* As they inherit from eoValueParam, they can be printed drectly,
|
||||
* for instance by an eoMonitor.
|
||||
*
|
||||
* @see eoCheckPoint
|
||||
* @see eoMonitor
|
||||
*
|
||||
* @ingroup Utilities
|
||||
* @{
|
||||
*/
|
||||
|
||||
/**
|
||||
Base class for all statistics that need to be calculated
|
||||
over the (unsorted) population
|
||||
(I guess it is not really necessary? MS.
|
||||
Depstd::ends, there might be reasons to have a stat that is not an eoValueParam,
|
||||
but maybe I'm just kidding myself, MK)
|
||||
*/
|
||||
template <class EOT>
|
||||
class eoStatBase : public eoUF<const eoPop<EOT>&, void>
|
||||
{
|
||||
public:
|
||||
virtual void lastCall(const eoPop<EOT>&) {}
|
||||
virtual std::string className(void) const { return "eoStatBase"; }
|
||||
};
|
||||
|
||||
|
||||
template <class EOT> class eoCheckPoint;
|
||||
|
||||
/**
|
||||
The actual class that will be used as base for all statistics
|
||||
that need to be calculated over the (unsorted) population
|
||||
It is an eoStatBase AND an eoValueParam so it can be used in Monitors.
|
||||
*/
|
||||
template <class EOT, class T>
|
||||
class eoStat : public eoValueParam<T>, public eoStatBase<EOT>
|
||||
{
|
||||
public:
|
||||
|
||||
eoStat(T _value, std::string _description)
|
||||
: eoValueParam<T>(_value, _description)
|
||||
{}
|
||||
|
||||
virtual std::string className(void) const
|
||||
{ return "eoStat"; }
|
||||
|
||||
|
||||
eoStat<EOT, T>& addTo(eoCheckPoint<EOT>& cp) { cp.add(*this); return *this; }
|
||||
eoStat<EOT, T>& addTo(eoMonitor& mon) { mon.add(*this); return *this; }
|
||||
};
|
||||
|
||||
|
||||
|
||||
/**
|
||||
Base class for statistics calculated over a sorted snapshot of the population
|
||||
*/
|
||||
template <class EOT>
|
||||
class eoSortedStatBase : public eoUF<const std::vector<const EOT*>&, void>
|
||||
{
|
||||
public:
|
||||
virtual void lastCall(const std::vector<const EOT*>&) {}
|
||||
virtual std::string className(void) const { return "eoSortedStatBase"; }
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
The actual class that will be used as base for all statistics
|
||||
that need to be calculated over the sorted population
|
||||
It's an eoSortedStatBase AND an eoValueParam so it can be used in Monitors.
|
||||
*/
|
||||
template <class EOT, class ParamType>
|
||||
class eoSortedStat : public eoSortedStatBase<EOT>, public eoValueParam<ParamType>
|
||||
{
|
||||
public :
|
||||
eoSortedStat(ParamType _value, std::string _desc) : eoValueParam<ParamType>(_value, _desc) {}
|
||||
virtual std::string className(void) const { return "eoSortedStat"; }
|
||||
|
||||
eoSortedStat<EOT, ParamType>& addTo(eoCheckPoint<EOT>& cp) { cp.add(*this); return *this; }
|
||||
eoSortedStat<EOT, ParamType>& addTo(eoMonitor& mon) { mon.add(*this); return *this; }
|
||||
};
|
||||
|
||||
/**
|
||||
Average fitness of a population. Fitness can be:
|
||||
- double
|
||||
- eoMinimizingFitness or eoMaximizingFitness
|
||||
The average of each objective is evaluated.
|
||||
|
||||
( For eoScalarFitnessAssembled user eoAssembledFitnessStat classes.)
|
||||
*/
|
||||
#if defined(_MSC_VER) && (_MSC_VER < 1300)
|
||||
template <class EOT> class eoAverageStat : public eoStat<EOT, EOT::Fitness>
|
||||
#else
|
||||
template <class EOT> class eoAverageStat : public eoStat<EOT, typename EOT::Fitness>
|
||||
#endif
|
||||
{
|
||||
public :
|
||||
|
||||
using eoStat<EOT, typename EOT::Fitness>::value;
|
||||
|
||||
typedef typename EOT::Fitness Fitness;
|
||||
|
||||
eoAverageStat(std::string _description = "Average Fitness")
|
||||
: eoStat<EOT, Fitness>(Fitness(), _description) {}
|
||||
|
||||
static Fitness sumFitness(double _sum, const EOT& _eot){
|
||||
_sum += _eot.fitness();
|
||||
return _sum;
|
||||
}
|
||||
|
||||
eoAverageStat(double _value, std::string _desc) : eoStat<EOT, double>(_value, _desc) {}
|
||||
|
||||
virtual void operator()(const eoPop<EOT>& _pop){
|
||||
doit(_pop, Fitness()); // specializations for scalar and std::vector
|
||||
}
|
||||
|
||||
virtual std::string className(void) const { return "eoAverageStat"; }
|
||||
|
||||
private :
|
||||
|
||||
// Default behavior
|
||||
template <class T>
|
||||
void doit(const eoPop<EOT>& _pop, T)
|
||||
{
|
||||
Fitness v = std::accumulate(_pop.begin(), _pop.end(), Fitness(0.0), eoAverageStat::sumFitness);
|
||||
|
||||
value() = v / _pop.size();
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
Average fitness + Std. dev. of a population, fitness needs to be scalar.
|
||||
*/
|
||||
template <class EOT>
|
||||
class eoSecondMomentStats : public eoStat<EOT, std::pair<double, double> >
|
||||
{
|
||||
public :
|
||||
|
||||
using eoStat<EOT, std::pair<double, double> >::value;
|
||||
|
||||
typedef typename EOT::Fitness fitness_type;
|
||||
|
||||
typedef std::pair<double, double> SquarePair;
|
||||
|
||||
eoSecondMomentStats(std::string _description = "Average & Stdev")
|
||||
: eoStat<EOT, SquarePair>(std::make_pair(0.0,0.0), _description)
|
||||
{}
|
||||
|
||||
static SquarePair sumOfSquares(SquarePair _sq, const EOT& _eo)
|
||||
{
|
||||
double fitness = _eo.fitness();
|
||||
|
||||
_sq.first += fitness;
|
||||
_sq.second += fitness * fitness;
|
||||
return _sq;
|
||||
}
|
||||
|
||||
virtual void operator()(const eoPop<EOT>& _pop)
|
||||
{
|
||||
SquarePair result = std::accumulate(_pop.begin(), _pop.end(), std::make_pair(0.0, 0.0), eoSecondMomentStats::sumOfSquares);
|
||||
|
||||
double n = _pop.size();
|
||||
value().first = result.first / n; // average
|
||||
value().second = sqrt( (result.second - n * value().first * value().first) / (n - 1.0)); // stdev
|
||||
}
|
||||
|
||||
virtual std::string className(void) const { return "eoSecondMomentStats"; }
|
||||
};
|
||||
|
||||
/**
|
||||
The n_th element fitness in the population (see eoBestFitnessStat)
|
||||
*/
|
||||
#if defined(_MSC_VER) && (_MSC_VER < 1300)
|
||||
template <class EOT>
|
||||
class eoNthElementFitnessStat : public eoSortedStat<EOT, EOT::Fitness >
|
||||
#else
|
||||
template <class EOT>
|
||||
class eoNthElementFitnessStat : public eoSortedStat<EOT, typename EOT::Fitness >
|
||||
#endif
|
||||
{
|
||||
public :
|
||||
using eoSortedStat<EOT, typename EOT::Fitness >::value;
|
||||
|
||||
typedef typename EOT::Fitness Fitness;
|
||||
|
||||
eoNthElementFitnessStat(unsigned _whichElement, std::string _description = "nth element fitness")
|
||||
: eoSortedStat<EOT, Fitness>(Fitness(), _description), whichElement(_whichElement) {}
|
||||
|
||||
virtual void operator()(const std::vector<const EOT*>& _pop)
|
||||
{
|
||||
if (whichElement > _pop.size())
|
||||
throw std::logic_error("fitness requested of element outside of pop");
|
||||
|
||||
doit(_pop, Fitness());
|
||||
}
|
||||
|
||||
virtual std::string className(void) const { return "eoNthElementFitnessStat"; }
|
||||
private :
|
||||
|
||||
struct CmpFitness
|
||||
{
|
||||
CmpFitness(unsigned _whichElement, bool _maxim) : whichElement(_whichElement), maxim(_maxim) {}
|
||||
|
||||
bool operator()(const EOT* a, const EOT* b)
|
||||
{
|
||||
if (maxim)
|
||||
return a->fitness()[whichElement] > b->fitness()[whichElement];
|
||||
|
||||
return a->fitness()[whichElement] < b->fitness()[whichElement];
|
||||
}
|
||||
|
||||
unsigned whichElement;
|
||||
bool maxim;
|
||||
};
|
||||
|
||||
// for everything else
|
||||
template <class T>
|
||||
void doit(const std::vector<const EOT*>& _pop, T)
|
||||
{
|
||||
value() = _pop[whichElement]->fitness();
|
||||
}
|
||||
|
||||
unsigned whichElement;
|
||||
};
|
||||
|
||||
/* Actually, you shouldn't need to sort the population to get the best fitness
|
||||
MS - 17/11/00
|
||||
|
||||
But then again, if another stat needs sorted fitness anyway, getting the best
|
||||
out would be very fast.
|
||||
MK - 09/01/03
|
||||
|
||||
template <class EOT>
|
||||
class eoBestFitnessStat : public eoStat<EOT, typename EOT::Fitness >
|
||||
{
|
||||
public :
|
||||
typedef typename EOT::Fitness Fitness;
|
||||
|
||||
eoBestFitnessStat(std::string _description = "Best Fitness") :
|
||||
eoStat<EOT, Fitness>(Fitness(), _description) {}
|
||||
|
||||
virtual void operator()(const eoPop<EOT>& _pop)
|
||||
{
|
||||
value() = _pop.nth_element_fitness(0);
|
||||
}
|
||||
|
||||
};
|
||||
*/
|
||||
|
||||
/**
|
||||
Best fitness of a population. Fitness can be:
|
||||
- double
|
||||
- eoMinimizingFitness or eoMaximizingFitness
|
||||
|
||||
( For eoScalarFitnessAssembled look at eoAssembledFitnessStat )
|
||||
*/
|
||||
|
||||
#if defined(_MSC_VER) && (_MSC_VER < 1300)
|
||||
template <class EOT>
|
||||
class eoBestFitnessStat : public eoStat<EOT, EOT::Fitness>
|
||||
#else
|
||||
template <class EOT>
|
||||
class eoBestFitnessStat : public eoStat<EOT, typename EOT::Fitness>
|
||||
#endif
|
||||
{
|
||||
public:
|
||||
|
||||
using eoStat<EOT, typename EOT::Fitness>::value;
|
||||
|
||||
typedef typename EOT::Fitness Fitness;
|
||||
|
||||
eoBestFitnessStat(std::string _description = "Best ")
|
||||
: eoStat<EOT, Fitness>(Fitness(), _description)
|
||||
{}
|
||||
|
||||
void operator()(const eoPop<EOT>& _pop) {
|
||||
doit(_pop, Fitness() ); // specializations for scalar and std::vector
|
||||
}
|
||||
|
||||
virtual std::string className(void) const { return "eoBestFitnessStat"; }
|
||||
|
||||
|
||||
private :
|
||||
|
||||
struct CmpFitness
|
||||
{
|
||||
CmpFitness(unsigned _which, bool _maxim) : which(_which), maxim(_maxim) {}
|
||||
|
||||
bool operator()(const EOT& a, const EOT& b)
|
||||
{
|
||||
if (maxim)
|
||||
return a.fitness()[which] < b.fitness()[which];
|
||||
|
||||
return a.fitness()[which] > b.fitness()[which];
|
||||
}
|
||||
|
||||
unsigned which;
|
||||
bool maxim;
|
||||
};
|
||||
|
||||
// default
|
||||
template<class T>
|
||||
void doit(const eoPop<EOT>& _pop, T)
|
||||
{ // find the largest elements
|
||||
value() = _pop.best_element().fitness();
|
||||
}
|
||||
|
||||
};
|
||||
/** @example t-eoSSGA.cpp
|
||||
*/
|
||||
|
||||
template <class EOT>
|
||||
class eoDistanceStat : public eoStat<EOT, double>
|
||||
{
|
||||
public:
|
||||
|
||||
using eoStat<EOT, double>::value;
|
||||
|
||||
eoDistanceStat(std::string _name = "distance")
|
||||
: eoStat<EOT, double>(0.0, _name)
|
||||
{}
|
||||
|
||||
template <class T>
|
||||
double distance(T a, T b)
|
||||
{
|
||||
T res = a-b;
|
||||
return res < 0? -res : res;
|
||||
}
|
||||
|
||||
double distance(bool a, bool b)
|
||||
{
|
||||
return (a==b)? 0 : 1;
|
||||
}
|
||||
|
||||
void operator()(const eoPop<EOT>& _pop)
|
||||
{
|
||||
double& v = value();
|
||||
v = 0.0;
|
||||
|
||||
for (unsigned i = 0; i < _pop.size(); ++i)
|
||||
{
|
||||
for (unsigned j = 0; j < _pop.size(); ++j)
|
||||
{
|
||||
for (unsigned k = 0; k < _pop[i].size(); ++k)
|
||||
{
|
||||
v += distance(_pop[i][k], _pop[j][k]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
double sz = _pop.size();
|
||||
v /= sz * sz * _pop[0].size();
|
||||
}
|
||||
virtual std::string className(void) const { return "eoDistanceStat"; }
|
||||
|
||||
};
|
||||
|
||||
|
||||
|
||||
/*
|
||||
template <class EOT>
|
||||
class eoStdevStat : public eoStat<EOT, double >
|
||||
{
|
||||
public :
|
||||
typedef typename eoSecondMomentStats<EOT>::SquarePair SquarePair;
|
||||
|
||||
eoStdevStat(std::string _description = "Stdev") : eoStat<EOT, double>(0.0, _description) {}
|
||||
|
||||
virtual void operator()(const eoPop<EOT>& _pop)
|
||||
{
|
||||
SquarePair result = std::accumulate(pop.begin(), pop.end(), std::make_pair(0.0, 0.0), eoSecondMomentStats::sumOfSquares);
|
||||
|
||||
double n = pop.size();
|
||||
value() = sqrt( (result.second - (result.first / n)) / (n - 1.0)); // stdev
|
||||
}
|
||||
};
|
||||
*/
|
||||
|
||||
|
||||
//! A robust measure of dispersion (also called midspread or middle fifty) that is the difference between the third and the first quartile.
|
||||
template<class EOT>
|
||||
class eoInterquartileRangeStat : public eoStat< EOT, typename EOT::Fitness >
|
||||
{
|
||||
public:
|
||||
using eoStat<EOT, typename EOT::Fitness>::value;
|
||||
|
||||
eoInterquartileRangeStat( typename EOT::Fitness start, std::string description = "IQR" ) : eoStat<EOT,typename EOT::Fitness>( start, description ) {}
|
||||
|
||||
virtual void operator()( const eoPop<EOT> & _pop )
|
||||
{
|
||||
if( _pop.size() == 0 ) {
|
||||
// how to implement value() = 0 ?
|
||||
|
||||
} else {
|
||||
eoPop<EOT> pop = _pop;
|
||||
|
||||
unsigned int quartile = pop.size()/4;
|
||||
std::nth_element( pop.begin(), pop.begin()+quartile*1, pop.end() );
|
||||
typename EOT::Fitness Q1 = pop[quartile].fitness();
|
||||
|
||||
std::nth_element( pop.begin(), pop.begin()+quartile*3, pop.end() );
|
||||
typename EOT::Fitness Q3 = pop[quartile*3].fitness();
|
||||
|
||||
value() = Q3 - Q1;
|
||||
}
|
||||
}
|
||||
|
||||
virtual std::string className(void) const { return "eoInterquartileRangeStat"; }
|
||||
};
|
||||
/** @example t-eoIQRStat.cpp
|
||||
*/
|
||||
|
||||
/** Compute the average size of indivudals over the population
|
||||
*
|
||||
* Obviously, will work only on representations that implement the (standard) "size()" method,
|
||||
* like any STL container.
|
||||
*/
|
||||
template<class EOT>
|
||||
class eoAverageSizeStat : public eoStat< EOT, double>
|
||||
{
|
||||
public:
|
||||
|
||||
using eoStat<EOT, double>::value;
|
||||
|
||||
eoAverageSizeStat( std::string description = "Av.Size" ) :
|
||||
eoStat<EOT,double>( 0.0, description ) {} // 0 by default
|
||||
|
||||
virtual void operator()( const eoPop<EOT> & pop )
|
||||
{
|
||||
size_t pop_size = pop.size();
|
||||
|
||||
std::vector<size_t> sizes;
|
||||
sizes.reserve(pop_size);
|
||||
|
||||
for( unsigned int i=0, s = pop_size; i<s; ++i ) {
|
||||
sizes.push_back( pop[i].size() );
|
||||
}
|
||||
|
||||
size_t sum = std::accumulate( sizes.begin(), sizes.end(), 0 );
|
||||
|
||||
value() = static_cast<double>(sum) / static_cast<double>(pop_size);
|
||||
}
|
||||
|
||||
virtual std::string className(void) const { return "eoAverageSizeStat"; }
|
||||
};
|
||||
|
||||
/** @} */
|
||||
#endif
|
||||
194
eo/src/utils/eoState.cpp
Normal file
194
eo/src/utils/eoState.cpp
Normal file
|
|
@ -0,0 +1,194 @@
|
|||
#ifdef _MSC_VER
|
||||
#pragma warning(disable:4786)
|
||||
#endif
|
||||
|
||||
#ifdef HAVE_CONFIG_H
|
||||
#include <config.h>
|
||||
#endif
|
||||
|
||||
#include <algorithm>
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
|
||||
#include "eoState.h"
|
||||
#include "eoObject.h"
|
||||
#include "eoPersistent.h"
|
||||
|
||||
using namespace std;
|
||||
|
||||
|
||||
|
||||
void removeComment(string& str, string comment)
|
||||
{
|
||||
string::size_type pos = str.find(comment);
|
||||
|
||||
if (pos != string::npos)
|
||||
{
|
||||
str.erase(pos, str.size());
|
||||
}
|
||||
}
|
||||
|
||||
bool is_section(const string& str, string& name)
|
||||
{
|
||||
string::size_type pos = str.find("\\section{");
|
||||
|
||||
if (pos == string::npos)
|
||||
return false;
|
||||
//else
|
||||
|
||||
string::size_type end = str.find("}");
|
||||
|
||||
if (end == string::npos)
|
||||
return false;
|
||||
// else
|
||||
|
||||
name = str.substr(pos + 9, end-9);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
eoState::~eoState(void)
|
||||
{
|
||||
for (unsigned i = 0; i < ownedObjects.size(); ++i)
|
||||
{
|
||||
delete ownedObjects[i];
|
||||
}
|
||||
}
|
||||
|
||||
void eoState::registerObject(eoPersistent& registrant)
|
||||
{
|
||||
string name = createObjectName(dynamic_cast<eoObject*>(®istrant));
|
||||
|
||||
pair<ObjectMap::iterator,bool> res = objectMap.insert(make_pair(name, ®istrant));
|
||||
|
||||
if (res.second == true)
|
||||
{
|
||||
creationOrder.push_back(res.first);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw logic_error("Interval error: object already present in the state");
|
||||
}
|
||||
}
|
||||
|
||||
void eoState::load(const string& _filename)
|
||||
{
|
||||
ifstream is (_filename.c_str());
|
||||
|
||||
if (!is)
|
||||
{
|
||||
string str = "Could not open file " + _filename;
|
||||
throw runtime_error(str);
|
||||
}
|
||||
|
||||
load(is);
|
||||
}
|
||||
|
||||
void eoState::load(std::istream& is)
|
||||
{
|
||||
string str;
|
||||
string name;
|
||||
|
||||
getline(is, str);
|
||||
|
||||
if (is.fail())
|
||||
{
|
||||
string str = "Error while reading stream";
|
||||
throw runtime_error(str);
|
||||
}
|
||||
|
||||
while(! is.eof())
|
||||
{ // parse section header
|
||||
if (is_section(str, name))
|
||||
{
|
||||
string fullString;
|
||||
ObjectMap::iterator it = objectMap.find(name);
|
||||
|
||||
if (it == objectMap.end())
|
||||
{ // ignore
|
||||
while (getline(is, str))
|
||||
{
|
||||
if (is_section(str, name))
|
||||
break;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
eoPersistent* object = it->second;
|
||||
|
||||
// now we have the object, get lines, remove comments etc.
|
||||
|
||||
string fullstring;
|
||||
|
||||
while (getline(is, str))
|
||||
{
|
||||
if (is.eof())
|
||||
throw runtime_error("No section in load file");
|
||||
if (is_section(str, name))
|
||||
break;
|
||||
|
||||
removeComment(str, getCommentString());
|
||||
fullstring += str + "\n";
|
||||
}
|
||||
istringstream the_stream(fullstring);
|
||||
object->readFrom(the_stream);
|
||||
}
|
||||
}
|
||||
else // if (is_section(str, name)) - what if file empty
|
||||
{
|
||||
getline(is, str); // try next line!
|
||||
// if (is.eof())
|
||||
// throw runtime_error("No section in load file");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
void eoState::save(const string& filename) const
|
||||
{ // saves in order of insertion
|
||||
ofstream os(filename.c_str());
|
||||
|
||||
if (!os)
|
||||
{
|
||||
string msg = "Could not open file: " + filename + " for writing!";
|
||||
throw runtime_error(msg);
|
||||
}
|
||||
|
||||
save(os);
|
||||
}
|
||||
|
||||
void eoState::save(std::ostream& os) const
|
||||
{ // saves in order of insertion
|
||||
for (vector<ObjectMap::iterator>::const_iterator it = creationOrder.begin(); it != creationOrder.end(); ++it)
|
||||
{
|
||||
os << "\\section{" << (*it)->first << "}\n";
|
||||
(*it)->second->printOn(os);
|
||||
os << '\n';
|
||||
}
|
||||
}
|
||||
|
||||
string eoState::createObjectName(eoObject* obj)
|
||||
{
|
||||
if (obj == 0)
|
||||
{
|
||||
ostringstream os;
|
||||
os << objectMap.size();
|
||||
return os.str();
|
||||
}
|
||||
// else
|
||||
|
||||
string name = obj->className();
|
||||
ObjectMap::const_iterator it = objectMap.find(name);
|
||||
|
||||
unsigned count = 1;
|
||||
while (it != objectMap.end())
|
||||
{
|
||||
ostringstream os;
|
||||
os << obj->className().c_str() << count++;
|
||||
name = os.str();
|
||||
it = objectMap.find(name);
|
||||
}
|
||||
|
||||
return name;
|
||||
}
|
||||
138
eo/src/utils/eoState.h
Normal file
138
eo/src/utils/eoState.h
Normal file
|
|
@ -0,0 +1,138 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoState.h
|
||||
// (c) Marc Schoenauer, Maarten Keijzer and GeNeura Team, 2000
|
||||
/*
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
|
||||
Marc.Schoenauer@polytechnique.fr
|
||||
mkeijzer@dhi.dk
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef eoState_h
|
||||
#define eoState_h
|
||||
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <map>
|
||||
#include <vector>
|
||||
|
||||
#include <eoFunctorStore.h>
|
||||
|
||||
class eoObject;
|
||||
class eoPersistent;
|
||||
|
||||
/**
|
||||
eoState can be used to register derivants of eoPersistent. It will
|
||||
then in turn implement the persistence framework through members load
|
||||
and save, that will call readFrom and printOn for the registrated objects.
|
||||
|
||||
It is derived from eoFunctorStore, so that it also serves as a place where
|
||||
all those nifty eo functors can be stored. This is useful in the case you
|
||||
want to use one of the make_* functions. These functions generally take as their
|
||||
last argument an eoFunctorStore (or a state) which is used to hold all dynamically
|
||||
generated data. Note however, that unlike with eoPersistent derived classes, eoFunctorBase
|
||||
derived classes are not saved or loaded. To govern the creation of functors,
|
||||
command-line parameters (which can be stored) are needed.
|
||||
|
||||
@ingroup Utilities
|
||||
*/
|
||||
class eoState : public eoFunctorStore
|
||||
{
|
||||
public :
|
||||
|
||||
eoState(void) {}
|
||||
|
||||
~eoState(void);
|
||||
|
||||
/**
|
||||
* Object registration function, note that it does not take ownership!
|
||||
*/
|
||||
void registerObject(eoPersistent& registrant);
|
||||
|
||||
/**
|
||||
* Copies the object (MUST be derived from eoPersistent)
|
||||
* and returns a reference to the owned object.
|
||||
* Note: it does not register the object, this must be done afterwards!
|
||||
*/
|
||||
template <class T>
|
||||
T& takeOwnership(const T& persistent)
|
||||
{
|
||||
// If the compiler budges here, T is not a subclass of eoPersistent
|
||||
ownedObjects.push_back(new T(persistent));
|
||||
return static_cast<T&>(*ownedObjects.back());
|
||||
}
|
||||
|
||||
/**
|
||||
* Loading error thrown when nothing seems to work.
|
||||
*/
|
||||
struct loading_error : public std::runtime_error
|
||||
{
|
||||
loading_error(std::string huh = "Error while loading") : std::runtime_error(huh) {}
|
||||
};
|
||||
|
||||
std::string getCommentString(void) const { return "#"; }
|
||||
|
||||
/**
|
||||
* Reads the file specified
|
||||
*
|
||||
* @param _filename the name of the file to load from
|
||||
*/
|
||||
void load(const std::string& _filename);
|
||||
|
||||
/**
|
||||
* Reads the file specified
|
||||
*
|
||||
* @param is the stream to load from
|
||||
*/
|
||||
void load(std::istream& is);
|
||||
|
||||
/**
|
||||
* Saves the state in file specified
|
||||
*
|
||||
* @param _filename the name of the file to save into
|
||||
*/
|
||||
void save(const std::string& _filename) const;
|
||||
|
||||
/**
|
||||
* Saves the state in file specified
|
||||
*
|
||||
* @param os the stream to save into
|
||||
*/
|
||||
void save(std::ostream& os) const;
|
||||
|
||||
private :
|
||||
std::string createObjectName(eoObject* obj);
|
||||
|
||||
// first is Persistent, second is the raw data associated with it.
|
||||
typedef std::map<std::string, eoPersistent*> ObjectMap;
|
||||
|
||||
ObjectMap objectMap;
|
||||
|
||||
std::vector<ObjectMap::iterator> creationOrder;
|
||||
std::vector<eoPersistent*> ownedObjects;
|
||||
|
||||
// private copy and assignment as eoState is supposed to be unique
|
||||
eoState(const eoState&);
|
||||
eoState& operator=(const eoState&);
|
||||
|
||||
};
|
||||
/** @example t-eoStateAndParser.cpp
|
||||
*/
|
||||
|
||||
#endif
|
||||
61
eo/src/utils/eoStdoutMonitor.h
Normal file
61
eo/src/utils/eoStdoutMonitor.h
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
/*
|
||||
(c) Marc Schoenauer, Maarten Keijzer and GeNeura Team, 2000
|
||||
(c) Thales group, 2010
|
||||
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: http://eodev.sourceforge.net
|
||||
|
||||
Authors:
|
||||
todos@geneura.ugr.es
|
||||
Marc.Schoenauer@polytechnique.fr
|
||||
mkeijzer@dhi.dk
|
||||
Johann Dréo <johann.dreo@thalesgroup.com>
|
||||
*/
|
||||
|
||||
#ifndef _eoStdoutMonitor_h
|
||||
#define _eoStdoutMonitor_h
|
||||
|
||||
#include <string>
|
||||
|
||||
#include <utils/eoOStreamMonitor.h>
|
||||
#include <eoObject.h>
|
||||
|
||||
/**
|
||||
Prints statistics to stdout
|
||||
|
||||
@ingroup Monitors
|
||||
*/
|
||||
class eoStdoutMonitor : public eoOStreamMonitor
|
||||
{
|
||||
public :
|
||||
eoStdoutMonitor(bool _verbose, std::string _delim = "\t", unsigned int _width=20, char _fill=' ' ) :
|
||||
eoOStreamMonitor( std::cout, _verbose, _delim, _width, _fill)
|
||||
{
|
||||
#ifndef DEPRECATED_MESSAGES
|
||||
eo::log << eo::warnings << "WARNING: the use of the verbose parameter in eoStdoutMonitor constructor is deprecated and will be removed in the next release" << std::endl;
|
||||
#endif // !DEPRECATED_MESSAGES
|
||||
}
|
||||
|
||||
eoStdoutMonitor(std::string _delim = "\t", unsigned int _width=20, char _fill=' ' ) :
|
||||
eoOStreamMonitor( std::cout, _delim, _width, _fill)
|
||||
{}
|
||||
|
||||
virtual std::string className(void) const { return "eoStdoutMonitor"; }
|
||||
};
|
||||
|
||||
#endif
|
||||
74
eo/src/utils/eoTimeCounter.h
Normal file
74
eo/src/utils/eoTimeCounter.h
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoTimeCounter.h
|
||||
// (c) Marc Schoenauer, Maarten Keijzer, and GeNeura Team, 2002
|
||||
/*
|
||||
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@inria.fr
|
||||
mkeijzer@dhi.dk
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _eoTimeCounter_h
|
||||
#define _eoTimeCounter_h
|
||||
|
||||
#include <time.h>
|
||||
#include <utils/eoStat.h>
|
||||
|
||||
|
||||
/**
|
||||
An eoStat that simply gives the user time since first generation
|
||||
It has to be tempatized by EOT because it must be an eoStat
|
||||
|
||||
@ingroup Stats
|
||||
*/
|
||||
class eoTimeCounter : public eoUpdater, public eoValueParam<double>
|
||||
{
|
||||
public:
|
||||
eoTimeCounter() : eoValueParam<double>(0.0, "Time") // : firstTime(true)
|
||||
{
|
||||
start = time(NULL);
|
||||
}
|
||||
|
||||
/** simply stores the time spent in process in its value() */
|
||||
virtual void operator()()
|
||||
{
|
||||
// ask for system time
|
||||
utime = clock();
|
||||
|
||||
// if (firstTime) /* first generation */
|
||||
// {
|
||||
// firstTime=false;
|
||||
// firstUtime = tmsStruct.tms_utime;
|
||||
// }
|
||||
// store elapsed user time
|
||||
// value(tmsStruct.tms_utime - firstUtime);
|
||||
// value()=double(utime)/CLOCKS_PER_SEC;
|
||||
double seconds_elapsed = time(NULL) - start;
|
||||
|
||||
value() = (seconds_elapsed > 2140) ? seconds_elapsed : double(utime)/CLOCKS_PER_SEC;
|
||||
}
|
||||
|
||||
private:
|
||||
// bool firstTime;
|
||||
// clock_t firstUtime;
|
||||
clock_t utime;
|
||||
time_t start;
|
||||
};
|
||||
|
||||
#endif
|
||||
88
eo/src/utils/eoTimedMonitor.h
Normal file
88
eo/src/utils/eoTimedMonitor.h
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoTimedMonitor.h
|
||||
// (c) Marc Schoenauer, Maarten Keijzer and GeNeura Team, 2005
|
||||
/*
|
||||
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
|
||||
mkeijzer@dhi.dk
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _eoTimedMonitor_h
|
||||
#define _eoTimedMonitor_h
|
||||
|
||||
#include <ctime>
|
||||
#include <string>
|
||||
|
||||
#include <utils/eoMonitor.h>
|
||||
#include <eoObject.h>
|
||||
|
||||
/**
|
||||
Holds a collection of monitors and only fires them when a time limit
|
||||
has been reached
|
||||
|
||||
@ingroup Monitors
|
||||
*/
|
||||
class eoTimedMonitor : public eoMonitor
|
||||
{
|
||||
public:
|
||||
|
||||
/** Constructor
|
||||
|
||||
No negative time can be specified, use 0 if you want it to fire "always".
|
||||
@param seconds_ Specify time limit (s).
|
||||
*/
|
||||
eoTimedMonitor(unsigned seconds_) : last_tick(0), seconds(seconds_) {}
|
||||
|
||||
eoMonitor& operator()(void) {
|
||||
bool monitor = false;
|
||||
if (last_tick == 0) {
|
||||
monitor = true;
|
||||
last_tick = clock();
|
||||
}
|
||||
|
||||
clock_t tick = clock();
|
||||
|
||||
if ( (unsigned)(tick-last_tick) >= seconds * CLOCKS_PER_SEC) {
|
||||
monitor = true;
|
||||
}
|
||||
|
||||
if (monitor) {
|
||||
for (unsigned i = 0; i < monitors.size(); ++i) {
|
||||
(*monitors[i])();
|
||||
}
|
||||
last_tick = clock();
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
void add(eoMonitor& mon) { monitors.push_back(&mon); }
|
||||
|
||||
virtual std::string className(void) const { return "eoTimedMonitor"; }
|
||||
|
||||
private:
|
||||
|
||||
clock_t last_tick;
|
||||
|
||||
unsigned seconds;
|
||||
|
||||
std::vector<eoMonitor*> monitors;
|
||||
};
|
||||
|
||||
#endif
|
||||
161
eo/src/utils/eoUniformInit.h
Normal file
161
eo/src/utils/eoUniformInit.h
Normal file
|
|
@ -0,0 +1,161 @@
|
|||
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
-----------------------------------------------------------------------------
|
||||
eoUniformInit.h
|
||||
|
||||
(c) Maarten Keijzer, GeNeura Team, Marc Schoenauer, 1999 - 2002
|
||||
|
||||
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@inria.fr
|
||||
*/
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
/** Copied from the eoRndGenerators to have objects deriving from eoInit
|
||||
* As the whole initialization mechanism in EO is based on eoInit rather than
|
||||
* eoRndGenerators, we might as well have these directly written without
|
||||
* overhead
|
||||
|
||||
@class eoUniformInit uniform initialization for doubles, floats, ints, ...
|
||||
@class eoBooleanInit biased init for booleans
|
||||
@class eoNormalInit normal intialization for doubles and floats
|
||||
@class eoNegExpInit negative exponential distributions "
|
||||
*/
|
||||
|
||||
#ifndef eoUniformInit_h
|
||||
#define eoUniformInit_h
|
||||
|
||||
#include "eoRNG.h"
|
||||
#include "eoInit.h"
|
||||
#include "eoRealBounds.h"
|
||||
#include <stdexcept>
|
||||
|
||||
|
||||
/** @addtogroup Initializators
|
||||
* @{
|
||||
*/
|
||||
|
||||
using eo::rng;
|
||||
|
||||
/**
|
||||
The class eoUniformInit can be used in the STL apply function
|
||||
to easily randomize floats and doubles. It can also
|
||||
be used for ints and unsigneds by virtue of the static_cast
|
||||
|
||||
Also present is a specialization for boolean, that will
|
||||
ignore the minima and maxima that are possibly set and will
|
||||
return an unbiased flip of a coin. For a biased flip, use the eoBoolean
|
||||
|
||||
either in [0, _max) if only 1 value (_max) is given
|
||||
(or none, as _max defaults to 1.0)
|
||||
or in [_min,_max) if 2 values are given (_min, _max)
|
||||
|
||||
*/
|
||||
template <class T = double> class eoUniformInit : public eoInit<T>
|
||||
{
|
||||
public :
|
||||
/** Ctor with only a max bound */
|
||||
eoUniformInit(T _max = T(1.0), eoRng& _rng = rng) :
|
||||
minim(T(0.0)), range(_max), uniform(_rng)
|
||||
{}
|
||||
|
||||
/** Ctor with an eoRealBound */
|
||||
eoUniformInit(eoRealBounds & _bound, eoRng& _rng = rng) :
|
||||
minim(_bound.minimum()), range(_bound.range()), uniform(_rng)
|
||||
{}
|
||||
|
||||
/** Ctor with explicit min and max */
|
||||
eoUniformInit(T _min, T _max, eoRng& _rng = rng) :
|
||||
minim(_min), range(_max-_min), uniform(_rng)
|
||||
{
|
||||
if (_min>_max)
|
||||
throw std::logic_error("Min is greater than Max in uniform_generator");
|
||||
}
|
||||
|
||||
/**
|
||||
Generates the number, uses a static_cast to get the right behaviour
|
||||
for ints and unsigneds
|
||||
*/
|
||||
void operator()(T & _t)
|
||||
{
|
||||
_t = minim+static_cast<T>(uniform.uniform(range));
|
||||
}
|
||||
|
||||
private :
|
||||
T minim;
|
||||
T range;
|
||||
eoRng& uniform;
|
||||
};
|
||||
|
||||
|
||||
/** Specialization for bool, does an unbiased coin flip */
|
||||
template <>
|
||||
inline void eoUniformInit<bool>::operator()(bool & _b)
|
||||
{
|
||||
_b = uniform.flip(0.5);
|
||||
}
|
||||
|
||||
/**
|
||||
The class eoBooleanInit can be used in the STL apply function
|
||||
to easily generate random booleans with a specified bias
|
||||
*/
|
||||
class eoBooleanInit : public eoInit<bool>
|
||||
{
|
||||
public :
|
||||
eoBooleanInit(float _bias = 0.5, eoRng& _rng = rng) : bias(_bias), gen(_rng) {}
|
||||
|
||||
void operator()(bool & _b) { _b = gen.flip(bias); }
|
||||
private :
|
||||
float bias;
|
||||
eoRng& gen;
|
||||
};
|
||||
|
||||
/**
|
||||
The class normal_generator can be used in the STL generate function
|
||||
to easily generate gaussian distributed floats and doubles. The user
|
||||
can supply a standard deviation which defaults to 1.
|
||||
*/
|
||||
template <class T = double> class eoNormalInit : public eoInit<T>
|
||||
{
|
||||
public :
|
||||
eoNormalInit(T _stdev = T(1.0), eoRng& _rng = rng) : stdev(_stdev), normal(_rng) {}
|
||||
|
||||
void operator()(T & _t) { _t = (T) normal.normal(stdev); }
|
||||
|
||||
private :
|
||||
T stdev;
|
||||
eoRng& normal;
|
||||
};
|
||||
|
||||
/**
|
||||
The class negexp_generator can be used in the STL generate function
|
||||
to easily generate negative exponential distributed floats and doubles. The user
|
||||
can supply a mean.
|
||||
*/
|
||||
template <class T = double> class eoNegExpInit : public eoInit<T>
|
||||
{
|
||||
public :
|
||||
eoNegExpInit(T _mean = 1.0, eoRng& _rng = rng) : mean(_mean), negexp(_rng) {}
|
||||
|
||||
void operator()(T & _t) { _t = (T) negexp.negexp(mean); }
|
||||
|
||||
private :
|
||||
T mean;
|
||||
eoRng& negexp;
|
||||
};
|
||||
|
||||
/** @} */
|
||||
#endif
|
||||
119
eo/src/utils/eoUpdatable.h
Normal file
119
eo/src/utils/eoUpdatable.h
Normal file
|
|
@ -0,0 +1,119 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoUpdatable.h
|
||||
// (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2000
|
||||
/*
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
|
||||
Marc.Schoenauer@polytechnique.fr
|
||||
mkeijzer@dhi.dk
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _eoUpdatable_h
|
||||
#define _eoUpdatable_h
|
||||
|
||||
#include <utils/eoUpdater.h>
|
||||
|
||||
/**
|
||||
eoUpdatable is a generic class for adding updatation to an existing class
|
||||
Just says it has an update() method
|
||||
|
||||
@ingroup Utilities
|
||||
*/
|
||||
class eoUpdatable
|
||||
{
|
||||
public:
|
||||
|
||||
/** @brief Virtual destructor */
|
||||
virtual ~eoUpdatable() {};
|
||||
|
||||
virtual void update() = 0;
|
||||
};
|
||||
|
||||
|
||||
|
||||
/**
|
||||
A base class to actually update an eoUpdatable object
|
||||
|
||||
@ingroup Utilities
|
||||
*/
|
||||
class eoDynUpdater : public eoUpdater
|
||||
{public :
|
||||
eoDynUpdater(eoUpdatable & _toUpdate) : toUpdate(_toUpdate) {};
|
||||
|
||||
virtual void operator()()
|
||||
{
|
||||
toUpdate.update();
|
||||
}
|
||||
|
||||
private:
|
||||
eoUpdatable& toUpdate;
|
||||
};
|
||||
|
||||
/**
|
||||
An eoUpdater to update an eoUpdatable object every given time interval
|
||||
|
||||
@ingroup Utilities
|
||||
*/
|
||||
class eoTimedDynUpdate : public eoDynUpdater
|
||||
{
|
||||
public :
|
||||
eoTimedDynUpdate(eoUpdatable & _toUpdate, time_t _interval) :
|
||||
eoDynUpdater(_toUpdate),
|
||||
interval(_interval), last_time(time(0)), first_time(time(0)) {}
|
||||
|
||||
void operator()(void)
|
||||
{
|
||||
time_t now = time(0);
|
||||
|
||||
if (now >= last_time + interval)
|
||||
{
|
||||
last_time = now;
|
||||
eoDynUpdater::operator() ();
|
||||
}
|
||||
}
|
||||
private :
|
||||
const time_t interval;
|
||||
time_t last_time;
|
||||
const time_t first_time;
|
||||
};
|
||||
|
||||
/**
|
||||
An eoUpdater to update an eoUpdatable object every given tic
|
||||
|
||||
@ingroup Utilities
|
||||
*/
|
||||
class eoCountedDynUpdate : public eoDynUpdater
|
||||
{
|
||||
public :
|
||||
eoCountedDynUpdate(eoUpdatable & _toUpdate, unsigned _interval)
|
||||
: eoDynUpdater(_toUpdate), interval(_interval), counter(0) {}
|
||||
|
||||
void operator()(void)
|
||||
{
|
||||
if (++counter % interval == 0)
|
||||
{
|
||||
eoDynUpdater::operator() ();
|
||||
}
|
||||
}
|
||||
private :
|
||||
const unsigned interval;
|
||||
unsigned counter;
|
||||
};
|
||||
|
||||
#endif
|
||||
46
eo/src/utils/eoUpdater.cpp
Normal file
46
eo/src/utils/eoUpdater.cpp
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
#ifdef _MSC_VER
|
||||
#pragma warning(disable:4786)
|
||||
#endif
|
||||
|
||||
#ifdef HAVE_CONFIG_H
|
||||
#include <config.h>
|
||||
#endif
|
||||
|
||||
#include <sstream>
|
||||
|
||||
#include <utils/eoState.h>
|
||||
#include <utils/eoUpdater.h>
|
||||
|
||||
using namespace std;
|
||||
|
||||
void eoTimedStateSaver::operator()(void)
|
||||
{
|
||||
time_t now = time(0);
|
||||
|
||||
if (now >= last_time + interval)
|
||||
{
|
||||
last_time = now;
|
||||
ostringstream os;
|
||||
os << prefix << (now - first_time) << '.' << extension;
|
||||
state.save(os.str());
|
||||
}
|
||||
}
|
||||
|
||||
void eoCountedStateSaver::doItNow(void)
|
||||
{
|
||||
ostringstream os;
|
||||
os << prefix << counter << '.' << extension;
|
||||
state.save(os.str());
|
||||
}
|
||||
|
||||
void eoCountedStateSaver::operator()(void)
|
||||
{
|
||||
if (++counter % interval == 0)
|
||||
doItNow();
|
||||
}
|
||||
|
||||
void eoCountedStateSaver::lastCall(void)
|
||||
{
|
||||
if (saveOnLastCall)
|
||||
doItNow();
|
||||
}
|
||||
172
eo/src/utils/eoUpdater.h
Normal file
172
eo/src/utils/eoUpdater.h
Normal file
|
|
@ -0,0 +1,172 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoUpdater.h
|
||||
// (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2000
|
||||
/*
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
|
||||
Marc.Schoenauer@polytechnique.fr
|
||||
mkeijzer@dhi.dk
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _eoUpdater_h
|
||||
#define _eoUpdater_h
|
||||
|
||||
#include <string>
|
||||
#include <eoFunctor.h>
|
||||
#include <utils/eoState.h>
|
||||
#include <utils/eoParam.h>
|
||||
|
||||
template <class EOT> class eoCheckPoint;
|
||||
|
||||
/**
|
||||
eoUpdater is a generic procudere for updating whatever you want.
|
||||
Yet again an empty name
|
||||
|
||||
@ingroup Utilities
|
||||
*/
|
||||
class eoUpdater : public eoF<void>
|
||||
{
|
||||
public:
|
||||
virtual void lastCall() {}
|
||||
virtual std::string className(void) const { return "eoUpdater"; }
|
||||
|
||||
template <class EOT>
|
||||
eoUpdater& addTo(eoCheckPoint<EOT>& cp) { cp.add(*this); return *this; }
|
||||
};
|
||||
|
||||
/**
|
||||
an eoUpdater that simply increments a counter
|
||||
|
||||
@ingroup Utilities
|
||||
*/
|
||||
template <class T>
|
||||
class eoIncrementor : public eoUpdater
|
||||
{public :
|
||||
/** Default Ctor - requires a reference to the thing to increment */
|
||||
eoIncrementor(T& _counter, T _stepsize = 1) : counter(_counter), stepsize(_stepsize) {}
|
||||
|
||||
/** Simply increments */
|
||||
virtual void operator()()
|
||||
{
|
||||
counter += stepsize;
|
||||
}
|
||||
|
||||
virtual std::string className(void) const { return "eoIncrementor"; }
|
||||
private:
|
||||
T& counter;
|
||||
T stepsize;
|
||||
};
|
||||
|
||||
/** an eoUpdater that is an eoValueParam (and thus OWNS its counter)
|
||||
* Mandatory for generation counter in make_checkpoint
|
||||
|
||||
@ingroup Utilities
|
||||
*/
|
||||
template <class T>
|
||||
class eoIncrementorParam : public eoUpdater, public eoValueParam<T>
|
||||
{
|
||||
public:
|
||||
|
||||
using eoValueParam<T>::value;
|
||||
|
||||
/** Default Ctor : a name and optionally an increment*/
|
||||
eoIncrementorParam( std::string _name, T _stepsize = 1) :
|
||||
eoValueParam<T>(T(0), _name), stepsize(_stepsize) {}
|
||||
|
||||
/** Ctor with a name and non-zero initial value
|
||||
* and mandatory stepSize to remove ambiguity
|
||||
*/
|
||||
eoIncrementorParam( std::string _name, T _countValue, T _stepsize) :
|
||||
eoValueParam<T>(_countValue, _name), stepsize(_stepsize) {}
|
||||
|
||||
/** Simply increments */
|
||||
virtual void operator()()
|
||||
{
|
||||
value() += stepsize;
|
||||
}
|
||||
|
||||
virtual std::string className(void) const { return "eoIncrementorParam"; }
|
||||
|
||||
private:
|
||||
T stepsize;
|
||||
};
|
||||
|
||||
#include <time.h>
|
||||
|
||||
/**
|
||||
an eoUpdater that saves a state every given time interval
|
||||
|
||||
@ingroup Utilities
|
||||
*/
|
||||
class eoTimedStateSaver : public eoUpdater
|
||||
{
|
||||
public :
|
||||
eoTimedStateSaver(time_t _interval, const eoState& _state, std::string _prefix = "state", std::string _extension = "sav") : state(_state),
|
||||
interval(_interval), last_time(time(0)), first_time(time(0)),
|
||||
prefix(_prefix), extension(_extension) {}
|
||||
|
||||
void operator()(void);
|
||||
|
||||
virtual std::string className(void) const { return "eoTimedStateSaver"; }
|
||||
private :
|
||||
const eoState& state;
|
||||
|
||||
const time_t interval;
|
||||
time_t last_time;
|
||||
const time_t first_time;
|
||||
const std::string prefix;
|
||||
const std::string extension;
|
||||
};
|
||||
|
||||
/**
|
||||
an eoUpdater that saves a state every given generations
|
||||
|
||||
@ingroup Utilities
|
||||
*/
|
||||
class eoCountedStateSaver : public eoUpdater
|
||||
{
|
||||
public :
|
||||
eoCountedStateSaver(unsigned _interval, const eoState& _state, std::string _prefix, bool _saveOnLastCall, std::string _extension = "sav", unsigned _counter = 0)
|
||||
: state(_state), interval(_interval), counter(_counter),
|
||||
saveOnLastCall(_saveOnLastCall),
|
||||
prefix(_prefix), extension(_extension) {}
|
||||
|
||||
eoCountedStateSaver(unsigned _interval, const eoState& _state, std::string _prefix = "state", std::string _extension = "sav", unsigned _counter = 0)
|
||||
: state(_state), interval(_interval), counter(_counter),
|
||||
saveOnLastCall(true),
|
||||
prefix(_prefix), extension(_extension) {}
|
||||
|
||||
virtual void lastCall(void);
|
||||
void operator()(void);
|
||||
|
||||
virtual std::string className(void) const { return "eoCountedStateSaver"; }
|
||||
private :
|
||||
void doItNow(void);
|
||||
|
||||
const eoState& state;
|
||||
const unsigned interval;
|
||||
unsigned counter;
|
||||
bool saveOnLastCall;
|
||||
|
||||
const std::string prefix;
|
||||
const std::string extension;
|
||||
};
|
||||
|
||||
|
||||
#endif
|
||||
120
eo/src/utils/make_help.cpp
Normal file
120
eo/src/utils/make_help.cpp
Normal file
|
|
@ -0,0 +1,120 @@
|
|||
//-----------------------------------------------------------------------------
|
||||
// make_help.h
|
||||
// (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2001
|
||||
/*
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
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
|
||||
mkeijzer@dhi.dk
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
#ifdef _MSC_VER
|
||||
// to avoid long name warnings
|
||||
#pragma warning(disable:4786)
|
||||
#endif
|
||||
|
||||
#include <cstdlib>
|
||||
#include <fstream>
|
||||
#include <stdexcept>
|
||||
|
||||
#include <utils/eoParser.h>
|
||||
|
||||
using namespace std;
|
||||
|
||||
/** Generation of the status file, and output of the help message if needed
|
||||
*
|
||||
* MUST be called after ALL parameters have been read in order to list them
|
||||
*
|
||||
* Warning: this is a plain .cpp file and shoudl NOT be included anywhere,
|
||||
* but compiled separately and stored in a library.
|
||||
*
|
||||
* It is declared in all make_xxx.h files in representation-dependent dirs
|
||||
* but it is NOT representation-dependent itself - that's why it's in utils
|
||||
*/
|
||||
void make_help(eoParser & _parser)
|
||||
{
|
||||
// name of the "status" file where all actual parameter values will be saved
|
||||
string str_status = _parser.ProgramName() + ".status"; // default value
|
||||
eoValueParam<string>& statusParam = _parser.createParam(str_status, "status","Status file",'\0', "Persistence" );
|
||||
|
||||
// dump status file BEFORE help, so the user gets a chance to use it:
|
||||
// it's probably the case where she/he needs it most!!!
|
||||
// Only help parameter will not be in status file - but who cares???
|
||||
if (statusParam.value() != "")
|
||||
{
|
||||
ofstream os(statusParam.value().c_str());
|
||||
os << _parser; // and you can use that file as parameter file
|
||||
}
|
||||
// do the following AFTER ALL PARAMETERS HAVE BEEN PROCESSED
|
||||
// i.e. in case you need parameters somewhere else, postpone these
|
||||
if (_parser.userNeedsHelp())
|
||||
{
|
||||
_parser.printHelp(cout);
|
||||
cout << "You can use an edited copy of file " << statusParam.value()
|
||||
<< " as parameter file" << endl;
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
/** test a dir.
|
||||
* Creates it if does not exist
|
||||
* If exists, throws an exception or erase everything there,
|
||||
* depending on last parameter
|
||||
*
|
||||
* Always return true (for code easy writing on the other side :-)
|
||||
*/
|
||||
bool testDirRes(std::string _dirName, bool _erase=true)
|
||||
{
|
||||
string s = "test -d " + _dirName;
|
||||
int res = system(s.c_str());
|
||||
// test for (unlikely) errors
|
||||
if ( (res==-1) || (res==127) )
|
||||
{
|
||||
s = "Problem executing test of dir " + _dirName;
|
||||
throw runtime_error(s);
|
||||
}
|
||||
// now make sure there is a dir without any file in it - or quit
|
||||
if (res) // no dir present
|
||||
{
|
||||
s = string("mkdir ")+ _dirName;
|
||||
int res = system(s.c_str());
|
||||
(void)res;
|
||||
return true;
|
||||
}
|
||||
// else
|
||||
if (_erase) // OK to erase
|
||||
{
|
||||
s = string("/bin/rm ")+ _dirName + "/*";
|
||||
int res = system(s.c_str());
|
||||
(void)res;
|
||||
return true;
|
||||
}
|
||||
//else
|
||||
// WARNING: bug if dir exists and is empty; this says it is not!
|
||||
// shoudl use scandir instead - no time now :-((( MS Aug. 01
|
||||
s = "Dir " + _dirName + " is not empty";
|
||||
throw runtime_error(s);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
// Local Variables:
|
||||
// coding: iso-8859-1
|
||||
// mode: C++
|
||||
// c-file-offsets: ((c . 0))
|
||||
// c-file-style: "Stroustrup"
|
||||
// fill-column: 80
|
||||
// End:
|
||||
175
eo/src/utils/pipecom.cpp
Normal file
175
eo/src/utils/pipecom.cpp
Normal file
|
|
@ -0,0 +1,175 @@
|
|||
/* ----------------------------------------------------------------------
|
||||
* Where........: CMAP - Polytechnique
|
||||
* File.........: pipecom.c
|
||||
* Author.......: Bertrand Lamy (Equipe genetique)
|
||||
* Created......: Mon Mar 13 13:50:11 1995
|
||||
* Description..: Communication par pipe bidirectionnel avec un autre process
|
||||
* ----------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
// MSC equivalent must be written and tested or some #idef instructions added
|
||||
// with a clear message at compile time that this is for Unix only ???
|
||||
|
||||
#ifdef HAVE_CONFIG_H
|
||||
#include <config.h>
|
||||
#endif
|
||||
|
||||
#ifndef _WINDOWS
|
||||
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <stdio.h>
|
||||
#include <signal.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "pipecom.h"
|
||||
|
||||
|
||||
|
||||
int Check( PCom *com )
|
||||
{
|
||||
if( ! com ) {
|
||||
fprintf( stderr, "PipeCom: Null pointer.\n" );
|
||||
fflush( stderr );
|
||||
return 0;
|
||||
}
|
||||
if( kill( com->pid, 0 ) != 0 ) {
|
||||
fprintf( stderr, "PipeCom: process doesn't exists.\n" );
|
||||
fflush( stderr );
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
|
||||
PCom * PipeComOpen( char *prog )
|
||||
{
|
||||
char *args[2];
|
||||
args[0] = prog;
|
||||
args[1] = NULL;
|
||||
return PipeComOpenArgv( prog, args );
|
||||
}
|
||||
|
||||
|
||||
PCom * PipeComOpenArgv( char *prog, char *argv[] )
|
||||
{
|
||||
int toFils[2];
|
||||
int toPere[2];
|
||||
int sonPid;
|
||||
PCom * ret = NULL;
|
||||
|
||||
if( pipe( toFils ) < 0 ) {
|
||||
perror( "PipeComOpen: Creating pipes" );
|
||||
return ret;
|
||||
}
|
||||
if( pipe( toPere ) < 0 ) {
|
||||
perror( "PipeComOpen: Creating pipes" );
|
||||
return ret;
|
||||
}
|
||||
|
||||
switch( (sonPid = vfork()) ) {
|
||||
case -1:
|
||||
perror("PipeComOpen: fork failed" );
|
||||
return ret;
|
||||
break;
|
||||
|
||||
case 0:
|
||||
/* --- Here's the son --- */
|
||||
/* --- replace old stdin --- */
|
||||
if( dup2( toFils[0], fileno(stdin) ) < 0 ) {
|
||||
perror( "PipeComOpen(son): could not connect" );
|
||||
exit( -1 );
|
||||
/* --- AVOIR: kill my father --- */
|
||||
}
|
||||
if( dup2( toPere[1], fileno(stdout) ) < 0 ) {
|
||||
perror( "PipeComOpen(son): could not connect" );
|
||||
exit( -1 );
|
||||
}
|
||||
if( execvp( prog, argv ) < 0 ) {
|
||||
perror( prog );
|
||||
perror( "PipeComOpen: can't exec" );
|
||||
exit(1);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
ret = (PCom *) malloc( sizeof(PCom) );
|
||||
if( ! ret )
|
||||
return NULL;
|
||||
|
||||
ret->fWrit = (FILE *)fdopen( toFils[1], "w" );
|
||||
ret->fRead = (FILE *)fdopen( toPere[0], "r" );
|
||||
ret->pid = sonPid;
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
|
||||
int PipeComSend( PCom *to, const char *line )
|
||||
{
|
||||
int nb = 0;
|
||||
if( ! Check(to ) )
|
||||
return nb;
|
||||
nb = fprintf( to->fWrit, line, 0 );
|
||||
fflush( to->fWrit );
|
||||
return nb;
|
||||
}
|
||||
|
||||
|
||||
int PipeComSendn( PCom *to, const char *data, int n )
|
||||
{
|
||||
int nb = 0;
|
||||
if( ! Check(to) )
|
||||
return nb;
|
||||
|
||||
nb = fwrite( data, 1, n, to->fWrit );
|
||||
fflush( to->fWrit );
|
||||
return nb;
|
||||
}
|
||||
|
||||
|
||||
int PipeComReceive( PCom *from, char *data, int max )
|
||||
{
|
||||
if( ! Check(from) )
|
||||
return 0;
|
||||
if( ! data ) {
|
||||
fprintf( stderr, "PipeComReceive: Invalid data pointer\n" );
|
||||
fflush( stderr );
|
||||
return 0;
|
||||
}
|
||||
if( fgets( data, max, from->fRead ) )
|
||||
return strlen(data);
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
|
||||
int PipeComClose( PCom *to )
|
||||
{
|
||||
if( ! Check(to) )
|
||||
return 0;
|
||||
fclose( to->fRead );
|
||||
fclose( to->fWrit );
|
||||
free( to );
|
||||
return 1;
|
||||
}
|
||||
|
||||
|
||||
|
||||
int PipeComWaitFor( PCom *from, char *what )
|
||||
{
|
||||
char buffer[256];
|
||||
do {
|
||||
if( ! PipeComReceive( from, buffer, 256 ) )
|
||||
return 0;
|
||||
} while( strcmp( buffer, what ) );
|
||||
return 1;
|
||||
}
|
||||
|
||||
#endif /*_MSC_VER*/
|
||||
|
||||
|
||||
// Local Variables:
|
||||
// coding: iso-8859-1
|
||||
// c-file-style: "Stroustrup"
|
||||
// fill-column: 80
|
||||
// End:
|
||||
47
eo/src/utils/pipecom.h
Normal file
47
eo/src/utils/pipecom.h
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
/* ----------------------------------------------------------------------
|
||||
* Where........: CMAP - Polytechnique
|
||||
* File.........: pipecom.h
|
||||
* Author.......: Bertrand Lamy (EEAAX)
|
||||
* Created......: Thu Mar 9 17:21:15 1995
|
||||
* Description..: Pipe communication with a process
|
||||
* ----------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
// This file cannot be used from C any more due to some const additions.
|
||||
// However, if you remove the const, it should work in C as well.
|
||||
|
||||
#ifndef EO_PIPECOM_H
|
||||
#define EO_PIPECOM_H
|
||||
|
||||
#include <stdio.h>
|
||||
|
||||
|
||||
typedef struct PipeCommunication {
|
||||
FILE *fWrit;
|
||||
FILE *fRead;
|
||||
int pid;
|
||||
} PCom;
|
||||
|
||||
|
||||
extern PCom *PipeComOpen( char *prog );
|
||||
extern PCom *PipeComOpenArgv( char *prog, char *argv[] );
|
||||
|
||||
extern int PipeComSend( PCom *to, const char *line );
|
||||
extern int PipeComSendn( PCom *to, const char *data, int n );
|
||||
|
||||
extern int PipeComReceive( PCom *from, char *data, int max );
|
||||
|
||||
extern int PipeComClose( PCom *to );
|
||||
extern int PipeComWaitFor( PCom *from, char *what );
|
||||
|
||||
|
||||
#endif // EO_PIPECOM_H
|
||||
|
||||
|
||||
|
||||
// Local Variables:
|
||||
// coding: iso-8859-1
|
||||
// mode: C++
|
||||
// c-file-style: "Stroustrup"
|
||||
// fill-column: 80
|
||||
// End:
|
||||
173
eo/src/utils/rnd_generators.h
Normal file
173
eo/src/utils/rnd_generators.h
Normal file
|
|
@ -0,0 +1,173 @@
|
|||
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
-----------------------------------------------------------------------------
|
||||
rnd_generators.h
|
||||
Some utility functors for generating random generators:
|
||||
uniform_generator : generates uniform floats or doubles
|
||||
random_generator : generates unsigneds, ints etc.
|
||||
normal_generator : normally distributed floats or doubles
|
||||
|
||||
(c) Maarten Keijzer (mak@dhi.dk) and GeNeura Team, 1999, 2000
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
|
||||
*/
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef eoRND_GENERATORS_H
|
||||
#define eoRND_GENERATORS_H
|
||||
|
||||
#include "eoRNG.h"
|
||||
#include <stdexcept>
|
||||
|
||||
/** @addtogroup Random
|
||||
* @{
|
||||
*/
|
||||
|
||||
/**
|
||||
The class uniform_generator can be used in the STL generate function
|
||||
to easily generate random floats and doubles
|
||||
either in [0, _max) if only 1 value (_max) is given
|
||||
(or none, as _max defaults to 1.0)
|
||||
or in [_min,_max) if 2 values are given (_min, _max)
|
||||
*/
|
||||
template <class T = double> class uniform_generator
|
||||
{
|
||||
// added new ctor with 2 params, and modified the data to minim and range
|
||||
// (was maxim only). MS 3/11/2000
|
||||
public :
|
||||
uniform_generator(T _max = T(1.0), eoRng& _rng = rng) :
|
||||
minim(T(0.0)), range(_max), uniform(_rng) {}
|
||||
uniform_generator(T _min, T _max, eoRng& _rng = rng) :
|
||||
minim(_min), range(_max-_min), uniform(_rng)
|
||||
{
|
||||
if (_min>_max)
|
||||
throw std::logic_error("Min is greater than Max in uniform_generator");
|
||||
}
|
||||
|
||||
T operator()(void) { return minim+static_cast<T>(uniform.uniform(range)); }
|
||||
|
||||
private :
|
||||
T minim;
|
||||
T range;
|
||||
eoRng& uniform;
|
||||
};
|
||||
|
||||
/**
|
||||
The class boolean_generator can be used in the STL generate function
|
||||
to easily generate random booleans with a specified bias
|
||||
*/
|
||||
class boolean_generator
|
||||
{
|
||||
public :
|
||||
boolean_generator(float _bias = 0.5, eoRng& _rng = rng) : bias(_bias), gen(_rng) {}
|
||||
|
||||
bool operator()(void) { return gen.flip(bias); }
|
||||
private :
|
||||
float bias;
|
||||
eoRng& gen;
|
||||
};
|
||||
|
||||
/**
|
||||
The class random_generator can be used in the STL generate function
|
||||
to easily generate random ints
|
||||
either between [0, _max) if only one value (_max) is given to the ctor
|
||||
or in [_min,_max) if 2 values are given (_min, _max)
|
||||
*/
|
||||
template <class T = uint32_t> class random_generator
|
||||
{
|
||||
public :
|
||||
// added new ctor with 2 params, and modified the data to minim and range
|
||||
// (was maxim only). MS 3/11/2000
|
||||
random_generator(T _max, eoRng& _rng = rng) :
|
||||
minim(T(0.0)), range(_max), random(_rng) {}
|
||||
random_generator(T _min, T _max, eoRng& _rng = rng) :
|
||||
minim(_min), range(_max-_min), random(_rng)
|
||||
{
|
||||
if (_min>_max)
|
||||
throw std::logic_error("Min is greater than Max in random_generator");
|
||||
}
|
||||
|
||||
T operator()(void) { return (T) (minim + random.random(range)); }
|
||||
|
||||
private :
|
||||
T minim;
|
||||
T range;
|
||||
eoRng& random;
|
||||
};
|
||||
|
||||
/// Specialization for bool
|
||||
template <>
|
||||
inline bool random_generator<bool>::operator()(void)
|
||||
{
|
||||
return random.flip(0.5);
|
||||
}
|
||||
|
||||
/**
|
||||
Another class random_generator that can be used in the STL random_shuffle
|
||||
function (see eoPop::shuffle): its operator() takes an unsigned argument m
|
||||
and must return an unsigned uniformly distributed in [0,m}
|
||||
*/
|
||||
template <class T = uint32_t> class UF_random_generator
|
||||
{
|
||||
public :
|
||||
UF_random_generator(eoRng& _rng = rng) :
|
||||
random(_rng) {}
|
||||
|
||||
T operator()(T _t) { return (T) (random.random(_t)); }
|
||||
|
||||
private :
|
||||
eoRng& random;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
The class normal_generator can be used in the STL generate function
|
||||
to easily generate gaussian distributed floats and doubles. The user
|
||||
can supply a standard deviation which defaults to 1.
|
||||
*/
|
||||
template <class T = double> class normal_generator
|
||||
{
|
||||
public :
|
||||
normal_generator(T _stdev = T(1.0), eoRng& _rng = rng) : stdev(_stdev), normal(_rng) {}
|
||||
|
||||
T operator()(void) { return (T) normal.normal(stdev); }
|
||||
|
||||
private :
|
||||
T stdev;
|
||||
eoRng& normal;
|
||||
};
|
||||
|
||||
/**
|
||||
The class negexp_generator can be used in the STL generate function
|
||||
to easily generate negative exponential distributed floats and doubles. The user
|
||||
can supply a mean.
|
||||
*/
|
||||
template <class T = double> class negexp_generator
|
||||
{
|
||||
public :
|
||||
negexp_generator(T _mean = 1.0, eoRng& _rng = rng) : mean(_mean), negexp(_rng) {}
|
||||
|
||||
T operator()(void) { return (T) negexp.negexp(mean); }
|
||||
|
||||
private :
|
||||
T mean;
|
||||
eoRng& negexp;
|
||||
};
|
||||
|
||||
/** @} */
|
||||
#endif
|
||||
340
eo/src/utils/selectors.h
Normal file
340
eo/src/utils/selectors.h
Normal file
|
|
@ -0,0 +1,340 @@
|
|||
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
-----------------------------------------------------------------------------
|
||||
selectors.h
|
||||
A bunch of useful selector functions. They generally have three forms:
|
||||
|
||||
template <class It>
|
||||
It select(It begin, It end, params, eoRng& gen = rng);
|
||||
|
||||
template <class EOT>
|
||||
const EOT& select(const eoPop<EOT>& pop, params, eoRng& gen = rng);
|
||||
|
||||
template <class EOT>
|
||||
EOT& select(eoPop<EOT>& pop, params, eoRng& gen = rng);
|
||||
|
||||
where select is one of: roulette_wheel, deterministic_tournament
|
||||
and stochastic_tournament (at the moment).
|
||||
|
||||
(c) Maarten Keijzer (mak@dhi.dk) and GeNeura Team, 1999, 2000
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
|
||||
*/
|
||||
|
||||
#ifndef SELECT__H
|
||||
#define SELECT__H
|
||||
|
||||
#include <stdexcept>
|
||||
|
||||
#include "eoRNG.h"
|
||||
#include <eoPop.h>
|
||||
/**
|
||||
@addtogroup Selectors
|
||||
@{
|
||||
*/
|
||||
|
||||
template <class EOT>
|
||||
bool minimizing_fitness()
|
||||
{
|
||||
EOT eo1; // Assuming people don't do anything fancy in the default constructor!
|
||||
EOT eo2;
|
||||
|
||||
/* Dear user, when the two line below do not compile you are most
|
||||
likely not working with scalar fitness values. In that case we're sorry
|
||||
but you cannot use lottery or roulette_wheel selection...
|
||||
*/
|
||||
|
||||
#ifdef _MSC_VER
|
||||
eo1.fitness( EOT::Fitness(0.0) );
|
||||
eo2.fitness( EOT::Fitness(1.0) );
|
||||
#else
|
||||
eo1.fitness( typename EOT::Fitness(0.0) ); // tried to cast it to an EOT::Fitness, but for some reason GNU barfs on this
|
||||
eo2.fitness( typename EOT::Fitness(1.0) );
|
||||
#endif
|
||||
|
||||
return eo2 < eo1; // check whether we have a minimizing fitness
|
||||
}
|
||||
|
||||
inline double scale_fitness(const std::pair<double, double>& _minmax, double _value)
|
||||
{
|
||||
if (_minmax.first == _minmax.second)
|
||||
{
|
||||
return 0.0; // no differences in fitness, population converged!
|
||||
}
|
||||
// else
|
||||
|
||||
return (_value - _minmax.first) / (_minmax.second - _minmax.first);
|
||||
}
|
||||
|
||||
template <class It>
|
||||
double sum_fitness(It begin, It end)
|
||||
{
|
||||
double sum = 0.0;
|
||||
|
||||
for (; begin != end; ++begin)
|
||||
{
|
||||
double v = static_cast<double>(begin->fitness());
|
||||
if (v < 0.0)
|
||||
throw std::logic_error("sum_fitness: negative fitness value encountered");
|
||||
sum += v;
|
||||
}
|
||||
|
||||
return sum;
|
||||
}
|
||||
|
||||
template <class EOT>
|
||||
double sum_fitness(const eoPop<EOT>& _pop)
|
||||
{
|
||||
return sum_fitness(_pop.begin(), _pop.end());
|
||||
}
|
||||
|
||||
template <class EOT>
|
||||
double sum_fitness(const eoPop<EOT>& _pop, std::pair<double, double>& _minmax)
|
||||
{
|
||||
double rawTotal, scaledTotal;
|
||||
|
||||
typename eoPop<EOT>::const_iterator it = _pop.begin();
|
||||
|
||||
_minmax.first = it->fitness();
|
||||
_minmax.second = it++->fitness();
|
||||
|
||||
for(; it != _pop.end(); ++it)
|
||||
{
|
||||
double v = static_cast<double>(it->fitness());
|
||||
|
||||
_minmax.first = std::min(_minmax.first, v);
|
||||
_minmax.second = std::max(_minmax.second, v);
|
||||
|
||||
rawTotal += v;
|
||||
}
|
||||
|
||||
if (minimizing_fitness<EOT>())
|
||||
{
|
||||
std::swap(_minmax.first, _minmax.second);
|
||||
}
|
||||
|
||||
scaledTotal = 0.0;
|
||||
|
||||
// unfortunately a second loop is neccessary to scale the fitness
|
||||
for (it = _pop.begin(); it != _pop.end(); ++it)
|
||||
{
|
||||
double v = scale_fitness(_minmax, static_cast<double>(it->fitness()));
|
||||
|
||||
scaledTotal += v;
|
||||
}
|
||||
|
||||
return scaledTotal;
|
||||
}
|
||||
|
||||
template <class It>
|
||||
It roulette_wheel(It _begin, It _end, double total, eoRng& _gen = rng)
|
||||
{
|
||||
|
||||
double roulette = _gen.uniform(total);
|
||||
|
||||
if (roulette == 0.0) // covers the case where total==0.0
|
||||
return _begin + _gen.random(_end - _begin); // uniform choice
|
||||
|
||||
It i = _begin;
|
||||
|
||||
while (roulette > 0.0)
|
||||
{
|
||||
roulette -= static_cast<double>(*(i++));
|
||||
}
|
||||
|
||||
return --i;
|
||||
}
|
||||
|
||||
template <class EOT>
|
||||
const EOT& roulette_wheel(const eoPop<EOT>& _pop, double total, eoRng& _gen = rng)
|
||||
{
|
||||
double roulette = _gen.uniform(total);
|
||||
|
||||
if (roulette == 0.0) // covers the case where total==0.0
|
||||
return _pop[_gen.random(_pop.size())]; // uniform choice
|
||||
|
||||
typename eoPop<EOT>::const_iterator i = _pop.begin();
|
||||
|
||||
while (roulette > 0.0)
|
||||
{
|
||||
roulette -= static_cast<double>((i++)->fitness());
|
||||
}
|
||||
|
||||
return *--i;
|
||||
}
|
||||
|
||||
template <class EOT>
|
||||
EOT& roulette_wheel(eoPop<EOT>& _pop, double total, eoRng& _gen = rng)
|
||||
{
|
||||
float roulette = _gen.uniform(total);
|
||||
|
||||
if (roulette == 0.0) // covers the case where total==0.0
|
||||
return _pop[_gen.random(_pop.size())]; // uniform choice
|
||||
|
||||
typename eoPop<EOT>::iterator i = _pop.begin();
|
||||
|
||||
while (roulette > 0.0)
|
||||
{
|
||||
roulette -= static_cast<double>((i++)->fitness());
|
||||
}
|
||||
|
||||
return *--i;
|
||||
}
|
||||
|
||||
template <class It>
|
||||
It deterministic_tournament(It _begin, It _end, unsigned _t_size, eoRng& _gen = rng)
|
||||
{
|
||||
It best = _begin + _gen.random(_end - _begin);
|
||||
|
||||
for (unsigned i = 0; i < _t_size - 1; ++i)
|
||||
{
|
||||
It competitor = _begin + _gen.random(_end - _begin);
|
||||
|
||||
if (*best < *competitor)
|
||||
{
|
||||
best = competitor;
|
||||
}
|
||||
}
|
||||
|
||||
return best;
|
||||
}
|
||||
|
||||
template <class EOT>
|
||||
const EOT& deterministic_tournament(const eoPop<EOT>& _pop, unsigned _t_size, eoRng& _gen = rng)
|
||||
{
|
||||
return *deterministic_tournament(_pop.begin(), _pop.end(), _t_size, _gen);
|
||||
}
|
||||
|
||||
template <class EOT>
|
||||
EOT& deterministic_tournament(eoPop<EOT>& _pop, unsigned _t_size, eoRng& _gen = rng)
|
||||
{
|
||||
return *deterministic_tournament(_pop.begin(), _pop.end(), _t_size, _gen);
|
||||
}
|
||||
|
||||
template <class It>
|
||||
It inverse_deterministic_tournament(It _begin, It _end, unsigned _t_size, eoRng& _gen = rng)
|
||||
{
|
||||
It worst = _begin + _gen.random(_end - _begin);
|
||||
|
||||
for (unsigned i = 1; i < _t_size; ++i)
|
||||
{
|
||||
It competitor = _begin + _gen.random(_end - _begin);
|
||||
|
||||
if (competitor == worst)
|
||||
{
|
||||
--i;
|
||||
continue; // try again
|
||||
}
|
||||
|
||||
if (*competitor < *worst)
|
||||
{
|
||||
worst = competitor;
|
||||
}
|
||||
}
|
||||
|
||||
return worst;
|
||||
}
|
||||
|
||||
template <class EOT>
|
||||
const EOT& inverse_deterministic_tournament(const eoPop<EOT>& _pop, unsigned _t_size, eoRng& _gen = rng)
|
||||
{
|
||||
return *inverse_deterministic_tournament<EOT>(_pop.begin(), _pop.end(), _t_size, _gen);
|
||||
}
|
||||
|
||||
template <class EOT>
|
||||
EOT& inverse_deterministic_tournament(eoPop<EOT>& _pop, unsigned _t_size, eoRng& _gen = rng)
|
||||
{
|
||||
return *inverse_deterministic_tournament(_pop.begin(), _pop.end(), _t_size, _gen);
|
||||
}
|
||||
|
||||
template <class It>
|
||||
It stochastic_tournament(It _begin, It _end, double _t_rate, eoRng& _gen = rng)
|
||||
{
|
||||
It i1 = _begin + _gen.random(_end - _begin);
|
||||
It i2 = _begin + _gen.random(_end - _begin);
|
||||
|
||||
bool return_better = _gen.flip(_t_rate);
|
||||
|
||||
if (*i1 < *i2)
|
||||
{
|
||||
if (return_better) return i2;
|
||||
// else
|
||||
|
||||
return i1;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (return_better) return i1;
|
||||
// else
|
||||
}
|
||||
// else
|
||||
|
||||
return i2;
|
||||
}
|
||||
|
||||
template <class EOT>
|
||||
const EOT& stochastic_tournament(const eoPop<EOT>& _pop, double _t_rate, eoRng& _gen = rng)
|
||||
{
|
||||
return *stochastic_tournament(_pop.begin(), _pop.end(), _t_rate, _gen);
|
||||
}
|
||||
|
||||
template <class EOT>
|
||||
EOT& stochastic_tournament(eoPop<EOT>& _pop, double _t_rate, eoRng& _gen = rng)
|
||||
{
|
||||
return *stochastic_tournament(_pop.begin(), _pop.end(), _t_rate, _gen);
|
||||
}
|
||||
|
||||
template <class It>
|
||||
It inverse_stochastic_tournament(It _begin, It _end, double _t_rate, eoRng& _gen = rng)
|
||||
{
|
||||
It i1 = _begin + _gen.random(_end - _begin);
|
||||
It i2 = _begin + _gen.random(_end - _begin);
|
||||
|
||||
bool return_worse = _gen.flip(_t_rate);
|
||||
|
||||
if (*i1 < *i2)
|
||||
{
|
||||
if (return_worse) return i1;
|
||||
// else
|
||||
|
||||
return i2;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (return_worse) return i2;
|
||||
// else
|
||||
}
|
||||
// else
|
||||
|
||||
return i1;
|
||||
}
|
||||
|
||||
template <class EOT>
|
||||
const EOT& inverse_stochastic_tournament(const eoPop<EOT>& _pop, double _t_rate, eoRng& _gen = rng)
|
||||
{
|
||||
return *inverse_stochastic_tournament(_pop.begin(), _pop.end(), _t_rate, _gen);
|
||||
}
|
||||
|
||||
template <class EOT>
|
||||
EOT& inverse_stochastic_tournament(eoPop<EOT>& _pop, double _t_rate, eoRng& _gen = rng)
|
||||
{
|
||||
return *inverse_stochastic_tournament(_pop.begin(), _pop.end(), _t_rate, _gen);
|
||||
}
|
||||
|
||||
/** @} */
|
||||
|
||||
#endif
|
||||
Loading…
Add table
Add a link
Reference in a new issue